text:
Q: Geometric Algebra: How to prove that the Grade Projection Operator is well defined The Grade Projection Operator $<\cdot>_r$ is widely used in Geometric Algebra to prove numerous relations and results. I'm looking for a proof that Grade Projection is a well-defined operation.
To do as such it should be sufficient to show that an $r$-blade $f_1f_2...f_r$ (geometric product of $r$ normal vectors) becomes an $r$-vector when each $f_{i}$ is expressed in terms of a basis $\{e_1,e_2,...,e_n\}$, meaning:
$$f_1f_2...f_r = \sum_{i,j,...,k} (a_{1i}a_{2j}...a_{rk})e_ie_j...e_k = \sum_{i \neq j \neq ... \neq k} (a_{1i}a_{2j}...a_{rk})e_ie_j...e_k$$
Unfortunately, most texts I've found do not bother proving this fact, as they present Geometric Algebra axiomatically. Due to the fact that it remains to be proven that such an axiomatic definition produces an actually existing entity, a constructive approach (be it as a quotient of the tensor algebra or through direct construction from a canonical orthonormal basis) seems to still be necessary.
In An elementary construction of the geometric algebra, Alan Macdonald provides such a construction, including a short "proof" of what I'm looking for. The proof seems to me more of an example than an actual demonstration and moreover, it relies on the principle that you can transform a certain orthonormal basis to another one through a series of reflections operations.
This fact seems to me to be reliant on the fact Macdonald considers a vector space with a positive definite inner product (meaning $a\cdot b \ge 0$ or Euclidean space with Euclidean norm). Geometric Algebra is also used with the Minkowski metric $\{1,-1,-1,-1\}$ for example, for which I do not know if the "consecutive reflections method" for basis vectors transformation still holds.
I'm then looking for a general proof for a Geometric Algebra with signature $\{n,m\}$ (therefore, for any non-degenerate inner product).

Summary:
Prove that the $r$-blade $f_1f_2...f_r$ is expressed as an $r$-vector in another normal basis $\{e_1,e_2,...,e_n\}$ (all components of grade $\neq r$ are null)
N.B. I'm working with the definition of $r$-blade as geometric product of $r$ normal vectors, NOT with the definition using the wedge product. The definition of the wedge product should if possible come AFTER the verification that the Grade Projection Operator is well-defined.

EDIT 1:
I'd like to thank @Nullius in Verba for their answer. I report their answer with expanded algebraic passages (hoping no error has been made and eventually asking for corrections). This is mostly to help myself visualize better their explanation, but I hope this will be of help to others too. The reasoning is/should be the following:

*

*Consider $r$-blade $f_1f_2...f_j...f_k...f_r$

*Express it in another basis as:
$$f_1f_2...f_j...f_k...f_r=\sum_{i_1,i_2,...,i_j,..,i_k,...,i_r} (a_{i_1}a_{i_2}...a_{i_j}...a_{i_k}...a_{i_r})(e_{i_1}e_{i_2}...e_{i_j}...e_{i_k}...e_{i_r})$$

*Due to the anti-symmetry property of the product of normal vectors (the property can be shown to hold even if working with the $f_i$ basis vectors already expressed in the $e_i$ basis, as shown in An elementary construction of the geometric algebra by Alan Macdonald):

$$f_1f_2...f_j...f_k...f_r+f_1f_2...f_k...f_j...f_r=0$$

*By expressing both in the $e_i$ basis:

*

*$f_1f_2...f_j...f_k...f_r=
\sum_{i_1 \neq ... \neq i_j \neq i_k \neq ... \neq i_r} (a_{i_1}...a_{i_j}...a_{i_k}...a_{i_r})(e_{i_1}...e_{i_j}...e_{i_k}...e_{i_r}) +\\
\sum_{\exists i_j,i_k:i_j=i_k} (a_{i_1}...a_{i_j}...a_{i_k}...a_{i_r})(e_{i_1}...e_{i_j}...e_{i_k}...e_{i_r})$

*$f_1f_2...f_k...f_j...f_r=\sum_{i_1 \neq ... \neq i_k \neq i_j \neq ... \neq i_r} (a_{i_1}...a_{i_k}...a_{i_j}...a_{i_r})(e_{i_1}...e_{i_k}...e_{i_j}...e_{i_r}) +\\
\sum_{\exists i_j,i_k:i_j=i_k} (a_{i_1}...a_{i_k}...a_{i_j}...a_{i_r})(e_{i_1}...e_{i_j}...e_{i_k}...e_{i_r})$

*The second expression can be rewritten as:

$$f_1f_2...f_k...f_j...f_r=-\sum_{i_1 \neq ... \neq i_j \neq i_k \neq ... \neq i_r} (a_{i_1}...a_{i_j}...a_{i_k}...a_{i_r})(e_{i_1}...e_{i_j}...e_{i_k}...e_{i_r}) +\\
\sum_{\exists i_j,i_k:i_j=i_k} (a_{i_1}...a_{i_j}...a_{i_k}...a_{i_r})(e_{i_1}...e_{i_j}...e_{i_k}...e_{i_r})$$

*

*First summation: scalars reordered via commutativity and $e_{i_j}$ and $e_{i_k}$ reordered with the addition of a minus sign in front due to antisymmetry (in the first summation, the condition $i_1 \neq ... \neq i_j \neq i_k \neq ... \neq i_r$ holds)

*Second summation: indices re-labelled, due to the second summary containing ONLY and ALL members with at least one pair $e_{i_j}$ and $e_{i_k}$ for which $i_j=i_k$ holds (guaranteeing the possibility of re-labelling elements accordingly)

*By summing the two expressions, the following is obtained:

$$f_1f_2...f_j...f_k...f_r+f_1f_2...f_k...f_j...f_r=\\
2\sum_{\exists i_j,i_k:i_j=i_k} (a_{i_1}...a_{i_j}...a_{i_k}...a_{i_r})(e_{i_1}...e_{i_j}...e_{i_k}...e_{i_r})=0$$
Then $\sum_{\exists i_j,i_k:i_j=i_k} (a_{i_1}...a_{i_j}...a_{i_k}...a_{i_r})(e_{i_1}...e_{i_j}...e_{i_k}...e_{i_r})=0$, proving that even if the basis is changed, the only elements which have the possibility of "surviving" the geometric product are precisely those of grade $r$.
Proven this, the Grade Projection Operator $<\cdot>_r$ can be said to be well-defined, as no strange phenomena (appearance of terms of different grades) should happen even if the basis is changed.
N.B. If there exists also a "coordinate-free proof" (which seems to be the motto of Geometric Algebra), which does not require expansion in an orthonormal basis but which follows directly from the properties of Geometric Algebra defined as the quotient of the corresponding tensor algebra, it would be welcome. Nevertheless, I believe that the provided answer is more than satisfactory.

A: "it relies on the principle that you can transform a certain orthonormal basis to another one through a series of reflections operations"
That's the Cartan-Dieudonné Theorem: For an n-dimensional, non-degenerate symmetric bilinear space over a field with characteristic not equal to 2, every element of the orthogonal group is a composition of at most n reflections. It works fine on the Minkowski metric.
"N.B. I'm working with the definition of r-blade as geometric product of r normal vectors, NOT with the definition using the wedge product."
The concept of 'normal' vectors is probably best defined after defining the inner product, at the same time as the wedge product. For the axiomatic approach, you want to start with algebraic properties of the geometric product and derive the geometric interpretation of thoe properties later. Define r-blades by specifying the vector basis to be pairwise antisymmetric: $f_if_j=-f_jf_i$ for $i\neq j$.
Hopefully with the full Cartan-Dieudonné Theorem in hand, the McDonald proof may be deemed more acceptable. But I don't think it's too hard to prove using the antisymmetry property. Expand the product of $f_i$s writing each as a linear combination of $e_i$s.
$$f_1f_2\ldots f_r=(a_{11}e_1+a_{12}e_2+\ldots +a_{1n}e_n)\ldots (a_{r1}e_1+a_{r2}e_2+\ldots +a_{rn}e_n)$$
Multiply out all the $r$ brackets to get terms with $r$ vectors $e_{i_1}e_{i_2}\ldots e_{i_r}$ in each. If the vectors in a term are all distinct, then the product is an r-blade by the antisymmetry of the $e_i$. If any are repeated, then we can permute the order (with appropriate sign-changes because the $e_i$ are antisymmetric) to put them next to each other and collapse them to a scalar, which commutes under multiplication with any multivector. Now we use this and the antisymmetry of the $f_i$ to show that these must sum to zero. Swapping any pair of the brackets above swaps the order of the corresponding $e_{i_j}$, $e_{i_k}$ in the products, and by antisymmetry of the $f_i$ this must reverse the sign of the sum of all such terms. But if $i_j=i_k$ then $e_{i_j}e_{i_k}=e_{i_k}e_{i_j}$ for all such terms, and the only way this can reverse sign is if they sum to zero.
I am inclined to agree that elementary introductions to Geometric Algebra are lacking. Those directed at physicists do usually try to motivate them geometrically at the start, but at some point the leap to abstraction is made, and from that point on only the most minimal sketch is provided - a scaffold on which, with a lot of work, a full derivation could be constructed. Usually this seems to be because authors want to demonstrate the utility of Geometric Algebra to other professionals by getting on to the more interesting applications quickly. Teaching vector algebra ramps up gradually, from drawing arrows on graph paper at the age of 10 to maybe starting vector calculus (grad, div, curl and all that) at the age of 20. Introductory texts on Geometric Algebra do a couple of pages of drawing arrows to show willing, but only about 10 pages later are discussing Dirac spinors and general relativity and differential geometry! I exaggerate, but not by much. There are about 10 years worth of intermediate detail missing. But such student-oriented texts are unlikely to be written until Geometric Algebra is widely enough accepted and established to be taught at the same elementary stage as vectors are. (Hestenes made the attempt, but again, in my view, tried to do too much at once.) The pedagogy is still a work in progress. I expect it will be another 20 years or more before we get that far.

A: $
\newcommand\K{\mathbb K}
\newcommand\G{\mathcal G}
\newcommand\Ext{{\bigwedge}}
\newcommand\End{\mathrm{End}}
\newcommand\proj[1]{\langle#1\rangle}
\newcommand\form[1]{\langle#1\rangle}
\newcommand\lintr{\mathbin\lrcorner}
\newcommand\rintr{\mathbin\llcorner}
\newcommand\lcontr{\mathbin{{\rfloor}}}
\newcommand\rcontr{\mathbin{{\lfloor}}}
\newcommand\tr{\mathrm{tr}}
$
Let $\K$ be a field with characteristic $\not= 2$,
$V$ an $n$-dimensional $\K$-vector space,
$Q : V \to \K$ a quadratic form,
$\G(V, Q)$ the corresponding geometric algebra,
and $\Ext V$ the exterior algebra of $V$.
Once we have an isomorphism $\phi : \G(V, Q) \cong \Ext V$,
the grade projection is defined by
$$
  \proj{X}_r := \phi^{-1}\!\left(\proj{\phi(X)}^\wedge_r\right)
$$
where $\proj\cdot^\wedge_r$ is the grade projection on $\Ext V$.
I will give two ways of constructing
the canonical $\phi : \G(V, Q) \cong \Ext V$
in an essentially basis-free manner.
The first way I think is not too difficult to grasp,
but the second way feels much more involved to me.
If simplicity is what you're after,
I think that Nullius' answer is perfect for your question,
and is much more accessible that what I am going to get into.
Both of the constructions I will demonstrate
are special cases of Chevalley's construction;
see chapter 22 of Clifford Algebras and Spinors (2001)
by Pertti Lounesto constructing $\G(V, Q)$ in $\Ext V$,
and see these notes
for the full generality giving isomorphisms $\G(V, Q) \cong \G(V, Q+Q')$.
The key in both cases is to exploit the universal properties of $\Ext V$ and $\G(V , Q)$, which define them uniquely up to algebra isomorphism:

*

*We assume $V \subseteq \Ext V$ in the canonical fashion. Let $A$ be any associative algebra. Then every $f : V \to A$ such that $f(v)^2 = 0$ for all $v \in V$ extends uniquely to an algebra homomorphism $f_\wedge : \Ext V \to A$; i.e. $f_\wedge$ is linear, $f_\wedge(v) = f(v)$ for all $v \in V$, and
$$
  f_\wedge(v_1\wedge\cdots\wedge v_k) = f(v_1)f(v_2)\cdots f(v_k).
$$

*We assume $V \subseteq \G(V, Q)$ in the canonical fashion.
Let $A$ be any associative algebra.
Then every $f : V \to A$ such that $f(v)^2 = Q(v)1_A$
for all $v \in V$ extends uniquely to an algebra homomorphism
$f_Q : \G(V, Q) \to A$;
i.e. $f_A$ is linear, $f_Q(v) = f(v)$ for all $v \in V$, and
$$
  f_Q(v_1v_2\cdots v_k) = f(v_1)f(v_2)\cdots f(v_k).
$$
It should be apparent from these universal properties that $\Ext V$ is just $\G(V, 0)$.
Within $\G(V, Q)$
We construct an exterior product within $\G(V, Q)$
which gives us the isomorphism with $\Ext V$.
While we can construct the isomorphism completely basis-free,
we will appeal to the existence of an orthogonal basis
to show that it is indeed an isomorphism.
We assume $\K, V \subseteq \G(V, Q)$ canonically. Then for any $v \in V$ and $X \in \G(V, Q)$, define
$$
  v\wedge X := \frac12(vX + \hat Xv)
$$
where $\hat X$ is the main or grade involution of $X$; this is defined by extending the map $v \mapsto -v$ using the universal property of $\G(V, Q)$. The $\wedge$ operation gives us a map from $V$ into the linear endomorphisms $\End(\G(V, Q))$ by
$$
  v \mapsto (X \mapsto v\wedge X).
\tag{$*$}
$$
We then confirm for any $v, w \in V$ that
$$
  v\wedge (v\wedge X)
= \frac12(v(v\wedge X) + \widehat{(v\wedge X)}v)
= \frac14(vvX + v\hat Xv + \widehat{vX}v + \widehat{\hat Xv}v)
= \frac14(v^2X + v\hat Xv - v\hat Xv - Xv^2)
= 0,
$$
where we've used the fact that $X \mapsto \hat X$ is an algebra involution, that $\hat v = -v$, and that $v^2$ is a scalar. Hence the map ($*$) extends to an algebra homomorphism $\phi : \Ext V \to \End(\G(V, Q))$ (the product on $\End(\G(V, Q))$ being function composition) where
$$
  \phi(v_1\wedge\cdots\wedge v_k)(X) = v_1\wedge(v_2\wedge(\cdots\wedge(v_k\wedge X)\cdots)),\quad X \in \G(V, Q).
$$
Then we get a linear map $\phi_1 : \Ext V \to \G(V, Q)$ by $\phi_1(X) = \phi(X)(1)$ for $X \in \Ext V$. Now let $\{e_i\}_{i=1}^n$ be a basis; we know that
$$
  \{1\}\cup\{e_i\}_{1\leq i\leq n}\cup\{e_ie_j\}_{1\leq i<j\leq n}\cup\{e_ie_je_k\}_{1\leq i<j<k\leq n}\cup\cdots
$$
is a basis for $\G(V, Q)$. Then it is easy to confirm that when $\{e_i\}_{i=1}^n$ is an orthogonal basis that
$$
  e_i\wedge(e_{j_1}e_{j_2}\cdots e_{j_k}) = e_ie_{j_1}e_{j_2}\cdots e_{j_k}
$$
if $i \not\in \{j_1, j_2,\dotsc, j_k\}$; hence
$$
  \phi_1(e_{j_1}\wedge e_{j_2}\wedge\cdots\wedge e_{j_k}) = e_{j_1}e_{j_2}\cdots e_{j_k}
$$
and $\phi_1$ is a linear isomorphism. In this way, we've also explicitly constructed the exterior product on $X, Y \in \G(V, Q)$:
$$
  X\wedge Y
= \phi_1\bigl(\phi_1^{-1}(X)\wedge\phi_1^{-1}(Y)\bigr)
= \phi\bigl(\phi_1^{-1}(X)\bigr)(Y).
$$
We can easily verify that starting analogously with a product $X\wedge v$ in $\G(V, Q)$ and following the same procedure would again result in the same $\phi_1$.
Within $\Ext V$
We construct a geometric product within $\Ext V$
which gives us the isomorphism with $\G(V, Q)$.
While we can construct the isomorphism completely basis-free,
we will appeal to the existence of an orthogonal basis
to show that it is indeed an isomorphism.
To present this in full generality,
we will make use of the dual space $V^*$
(though we can avoid this in the case that $Q$ is non-degenerate).
Let $\form{\cdot,\cdot} : V^*\times V \to \K$
denote the bilinear natural pairing;
that is $\form{v^*, v} = v^*(v)$ for all $v^* \in V^*$ and all $v \in V$.
This extends (naturally and in a basis-free manner that I will not go into here)
to a bilinear pairing $\Ext V^*\times\Ext V \to \K$ given by
$$
  \form{v^*_k\wedge v^*_{k-1}\wedge\cdots v^*_1,\;
    v_1\wedge v_2\wedge\cdots\wedge\cdots v_l}
= \delta_{kl}\det\bigl(\form{v^*_i, v_j}\bigr)_{i,j=1}^n.
$$
This pairing is non-degenerate, so the exterior product has well-defined adjoints:
$$
  \form{X^*\wedge Y^*, Z} = \form{X^*, Y^*\lintr Z} = \form{Y^*, Z\rintr X^*},
$$
where ${\lintr} : \Ext V^*\times\Ext V \to \Ext V$ is the left interior product on $\Ext V$ and ${\rintr} : \Ext V\times\Ext V^* \to \Ext V$ is the right interior product on $\Ext V$. There are other conventions in defining these, but the above is the most natural from the perspective of $\G(V, Q)$. Now $Q$ gives us a symmetric bilinear form $B : V\times V \to \K$ by
$$
  \form{v, w}_Q := \frac12(Q(v+w) - Q(v) - Q(w))
$$
and this gives us a map $\flat : V \to V^*$ by
$$
  v^\flat := (w \mapsto \form{v, w}_Q),
$$
and note that in fact
$$
  \form{v, w}_Q = \form{v^\flat, w}.
$$
$\flat$ extends to an algebra homomorphism $\flat : \Ext V \to \Ext V^*$
by the universal property of $\Ext V$.x
Then $\form{\cdot,\cdot}_Q$ extends to $\Ext V\times\Ext V$
in the same way as $\form{\cdot,\cdot}$.
We may now define the left and right contractions
${\lcontr}, {\rcontr} : \Ext V\times\Ext V \to \K$ by
$$
  X\lcontr Y = X^\flat\lintr Y,\quad X\rcontr Y = X\rintr Y^\flat,
$$
where in fact we have
$$
  \form{X\wedge Y, Z}_Q = \form{X, Y\lcontr Z}_Q = \form{Y, Z\rcontr X}_Q,
$$$$
  \form{X, Y\wedge Z}_Q = \form{X\rcontr Y, Z}_Q = \form{Z\lcontr X, Y}_Q.
$$
(We cannot use this to define the contractions since $Q$ may be degenerate.) This definition of the contractions immediately gives us the properties
$$
  v\lcontr w = \form{v, w}_Q,\quad
  v\lcontr(w\wedge X) = (v\lcontr w)X - w\wedge(v\lcontr X),\quad
  v\lcontr(w\lcontr X) = (v\wedge w)\lcontr X
$$
for $v, w \in V$ and $X \in \Ext V$. We now define the geoemtric product between $v \in V$ and $X \in \Ext V$ by
$$
  v\bullet X = v\lcontr X + v\wedge X.
$$
This gives us a map $V \to \End(\Ext V)$ by
$$
  v \mapsto (X \mapsto v\bullet X),
$$
and we see that
$$\begin{aligned}
  v\bullet(v\bullet X)
&= v\lcontr(v\bullet X) + v\wedge(v\bullet X)
\\
&= v\lcontr(v\lcontr X) + v\lcontr(v\wedge X)
  + v\wedge(v\lcontr X) + v\wedge(v\wedge X)
\\
&= (v\wedge v)\lcontr X + (v\lcontr v)X - v\wedge(v\lcontr X)
  + v\wedge(v\lcontr X) + (v\wedge v)\wedge X
\\
&= Q(v)X.
\end{aligned}$$
Thus by the univeral property of $\G(V, Q)$ we get an algebra homomorphism $\phi : \G(V, Q) \to \End(\Ext V)$ where
$$
  \phi(v_1v_2\cdots v_k)(X) = v_1\bullet(v_2\bullet(\cdots\bullet(v_k\bullet X)\cdots)).
$$
Then we get a linear map $\phi_1 : \G(V, Q) \to \Ext V$ by $\phi_1(X) = \phi(X)(1)$ for $X \in \G(V, Q)$. Now, if $\{e_i\}_{i=1}^n$ is an orthogonal basis for $V$, it is straightforward to show (say, by induction) that
$$
  e_i\bullet(e_{j_1}\wedge\cdots\wedge e_{j_k})
= e_i\wedge e_{j_1}\wedge\cdots\wedge e_{j_k}
$$
when $i, j_1,\dotsc, j_k$ are all distinct. Hence
$$
  \phi_1(e_{j_1}e_{j_2}\cdots e_{j_k}) = e_{j_1}\wedge e_{j_2}\wedge\cdots e_{j_k}
$$
and so $\phi_1$ is an isomorphism $\G(V, Q) \to \Ext V$.
The Particular Case of the Scalar Projection
There is a actually a nice way of defining just the scalar projection
that is fairly simple.
For any $X \in \G(V, Q)$,
the left multiplication map $Y \mapsto XY : \G(V, Q) \to \G(V, Q)$ is linear.
So we define the trace $\tr(X)$ of $X$ as the trace of this map.
We can show that right multiplication
actually gives the same definition of trace.
The dimension of $\G(V, Q)$ is $2^n$, so $\tr(1) = 2^n$,
and we define the scalar projection as
$$
  \proj{X}_0 = \frac1{2^n}\tr(X).
$$
It is easy to show that $\proj{X}_0$ is the scalar component of $X$
expressed in any orthogonal basis.


text:
Q: Decimal clipped by concatenation I need to concatenate two decimal values like:
select 0.1 || ' - ' || 0.5 from dual

And get a result as "0.1 - 0.5", but I get ".1 - .5".
I tried to_char and cast functions but I get the same.

A: Use to_char() function with appropriate format model. Here is an example:
select to_char(0.1, 'fm0D9') || ' - ' ||
       to_char(0.5, 'fm0D9') as res
  from dual

Result:
RES
---------
0.1 - 0.5

Where D is decimal separator, period(.) in this case, and fm format model modifier - removes leading and trailing blanks.
SQLfiddle

redpajama_set_name: RedPajamaStackExchange


text:
Q: Alarms on an ESP32 I am using an ESP32 connected to Google Cloud IoT Core to control lights with a raspberry pi as a hub to send messages to the esp32 through IoT core to turn them on and off at set times of the day.
What I want to do now is just eliminate the raspberry pi and have the esp32 manage when it needs to turn them on or off but I cant see to find a way to set alarms or something like alarms that trigger at specific times of days.
The time value coming in is in milliseconds from UTC
Does something like that exists or how could I accomplish alarms on the esp32?

A: I don't know if you are using the ESP IDF or some sort of Arduino framework for the ESP32 (with which I am not familiar). This answer is for the ESP IDF. If you are not using the ESP-IDF and don't have access to the relevant header files and libraries, some of the ideas might still be relevant.
Activate SNTP
Ensure that the clock on the controller is updated by following the SNTP example at https://github.com/espressif/esp-idf/tree/master/examples/protocols/sntp .
Use localtime()
If you are using the ESP-IDF you will have access to the localtime_r() function. Pass this (a pointer to) the number of 'seconds since the Epoch' - as returned by time(NULL) - and it will fill a struct tm with the day of the week, day of the month, hour, minute and second.
The general procedure is (error handling ommitted) ...
#include <time.h>
// ...

struct tm now = {};
time_t tnow = time(NULL);
localtime_r(&tnow, &now);
// Compare current day, hour, minute, etc. against pre-defined alarms.

Note: You can use gmtime_r() instead of localtime_r() if you prefer to use UTC.
You can invoke this periodically from your main while() loop as outlined below.
Alarm structures
Define a structure for your alarm information. You could use something like the following - tweaking according to the level of granularity you need. Note that it includes a callback member - to specify what the program should actually do when the alarm is triggered.
typedef struct {
    int week_day;  // -1 for every day of week
    int hour;      // -1 for every hour
    int minute;    // -1 for every minute
    void (*callback)(void);
    void *callback_arg;
} alarm_t;

Define alarms and callbacks
Define your array of alarms, callback functions and arguments.
static void trigger_relay(const void *arg) {
    uint32_t num = *(uint32_t *)arg;
    printf("Activating relay %u ...\n", num);
    // Handle GPIO etc.
}

static uint32_t relay_1 = 0;
static uint32_t relay_2 = 1;

static alarm_t alarms[] = {
    // Trigger relay 1 at 9:00 on Sunday
    {0, 9, 0, trigger_relay, (void *)&relay_1},
    // Relay 2 at 7:30 every day
    {-1, 7, 30, trigger_relay, (void *)&relay_2},
};

Periodic scan
Define a check_alarms() routine which loads a struct tm structure with the current time and compares this with each of the alarms you have defined. If the current time matches that of the alarm, the callback is invoked.
static void check_alarms(void) {
    time_t tnow = time(NULL);
    struct tm now = {};
    localtime_r(&tnow, &now);
    ESP_LOGI(TAG, "Time: %u:%u:%u", now.tm_hour, now.tm_min, now.tm_sec);
    size_t n_alarms = sizeof(alarms) / sizeof(alarms[0]);
    for (int i = 0; i < n_alarms; i++) {
        alarm_t *alrm = &alarms[i];
        if (alrm->week_day != -1 && alrm->week_day != now.tm_wday) {
            continue;
        }
        if (alrm->hour != -1 && alrm->hour != now.tm_hour) {
            continue;
        }
        if (alrm->minute != -1 && alrm->minute != now.tm_min) {
            continue;
        }
        alrm->callback(alrm->callback_arg);
    }
}

This would then be called from your main while() loop with a frequency depending on the granularity of your alarm. Since the alarm_t defined above has a granularity of 1 minute, that is how often I will call check_alarms(). This example is for FreeRTOS but could be adapted as needs be.
while (1) {
   TickType_t tick = xTaskGetTickCount();
   if (tick - g_time_last_check > pdMS_TO_TICKS(60000)) {
       g_time_last_check = tick;
       check_alarms();
   }
}

Efficiency
The above is not very efficient if you have a lot of alarms and / or each alarm should be triggered at high frequency. In such a case, you might consider algorithms which sort the alarms based on time until elapsed, and - instead of iterating over the entire array every time - instead employ a one-shot software timer to invoke the relevant callback. It probably isn't the worth the hassle unless you have a very large number of timers though.
Alternatives
Both FreeRTOS and the ESP-IDF include APIs for software timers - but these can not be (easily) used for alarms at a specific time of the day - which you state as a requirement. On the other hand - as you may already know - the ESP32 system-on-a-chip does have a built-in RTC, but I think it is best to use a higher-level interface than communicating with it directly.

A: A real-time clock is what you are looking for. I've never worked with the ESP32 but apparently it has one and it is bad. However, 5% error might be good enough for you. If it's an option, I would use an external one.


text:
Q: Autocompletetextview with multiple variables I have a JSON :
{"results":[
    {"id":"21","name":"Jonny"},
    {"id":"22","name":"Samuel"},
    {"id":"23","name":"Martha"}
    ]}

I need to put "name" into an autocompletetextview.
I need to post "id" to other activity, based on selected name in autocompletetextview.
Please help, thanks in advance

A: First convert json to hashmap:
HashMap<String, Integer> result = readJson("Your json string here");

public HashMap<String, Integer> readJson(String json) {
    try {
        JSONObject jsonObj = new JSONObject(json);

        // Getting JSON Array node
        JSONArray results = jsonObj.getJSONArray("results");
        final int j = results.length();
        HashMap<String, Integer> resultMap = new HashMap<>(j);
        for (int i = 0; i < j; i++) {
            JSONObject item = results.getJSONObject(i);
            resultMap.put(item.getString("name"), item.getInt("id"));
        }
        return resultMap;
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
}

Now set autocomplete adapter like:
autoComplete.setAdapter(new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, new ArrayList<>(result.keySet())));

public void startNextActivity(int id) {
    Intent intent = new Intent(getContext(), NextActivity.class);
    intent.putExtra("id", id);
    getContext().startActivity(intent);
}

call the start activity like:
        startNextActivity(result.get(autoComplete.getText().toString()));


text:
Q: how does the "@" location tag work? for better understanding check out this link first: http://sxsw.usehipster.com/questions/where-are-the-best-breakfast-tacos-in-austin
as you can see there, some answers have a reference to a location which is show on the map on the right. A user can do that by adding the "@" symbol before the location name.
I'd like to know how that works. Did the guys from usehipster.com developed that by themselve or is that maybe a framework I can use too?
cheers

A: Looks custom-made - i.e. not a framework. Shouldn't be too hard - just scan the entry for @\w+, plug that into Google Local Search (possibly specify the city), and plug the output into a Google Map. See e.g. this for an example of Google Local Search API: http://code.google.com/apis/ajax/playground/?exp=localsearch#the_hello_world_of_local_search


text:
Q: Multiple linear regression with missing covariates Imagine I have a dataset like
df <- data.frame(y=c(11:16), x1=c(23,NA,27,20,20,21), x2=c(NA,9,2,9,7,8))
df
   y x1 x2
1 11 23 NA
2 12 NA  9
3 13 27  2
4 14 20  9
5 15 20  7
6 16 21  8

If I perform a multiple linear regression, I get
m <- lm(y~x1+x2, data=df)
summary(m)

Call:
lm(formula = y ~ x1 + x2, data = df)

Residuals:
         3          4          5          6
-1.744e-01 -1.047e+00 -4.233e-16  1.221e+00

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 19.72093   27.06244   0.729    0.599
x1          -0.24419    0.93927  -0.260    0.838
x2           0.02326    1.01703   0.023    0.985

Residual standard error: 1.617 on 1 degrees of freedom
  (2 observations deleted due to missingness)
Multiple R-squared:  0.4767,    Adjusted R-squared:  -0.5698
F-statistic: 0.4556 on 2 and 1 DF,  p-value: 0.7234

Here we have 2 observations (1 and 2) deleted due to missingness.
To reduce the effects of missing data, would it be wise to compute 2 different simple linear regressions?
I.e.
m1 <- lm(y~x1, data=df)
m2 <- lm(y~x2, data=df)

In this case, for each model we will have only 1 observation deleted due to missingness.

A: No, that would probably not be wise.
Because you run into the issue of omitted variables bias.
You can see how this will affect your estimates, for instance for x1, which is inflated:
summary(lm(y~x1, data=df))
Call:
lm(formula = y ~ x1, data = df)

Residuals:
      1       3       4       5       6
-2.5287  0.8276 -0.5460  0.4540  1.7931

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  21.3276     7.1901   2.966   0.0592 .
x1           -0.3391     0.3216  -1.054   0.3692
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.897 on 3 degrees of freedom
  (1 observation deleted due to missingness)
Multiple R-squared:  0.2703,    Adjusted R-squared:  0.02713
F-statistic: 1.112 on 1 and 3 DF,  p-value: 0.3692

Note that you're relation of interest is y~x1+x2, so the effect of x1 on y accounting for the effect of x2, and vice versa.
That is of course not the same as estimating y~x1 and y~x2separately, where you omit the effect of the other explanatory variable.
Now there are of course strategies to deal with missing values.
One option is estimating a Bayesian model, using JAGS for instance, where you can model the missing values. An example would be the following for instance, where I take the mean and standard deviation of each variable to model the missing values:
model{
  for(i in 1:N){
    y[i] ~ dnorm(yhat[i], tau)
    yhat[i] <- a+ b1*x1[i] + b2*x2[i]

    # Accounting for missing data
    x1[i]~dnorm(22,3)
    x2[i]~dnorm(7,1.3)
    }
  # Priors
  b1~dnorm(0, .01)
  b2~dnorm(0, .01)

  # Hyperpriors
  tau <- pow(sd, -2)
  sd ~ dunif(0, 20)
}

This is just off the top of my head.
For better and more insightful advice on how deal with missing values I would recommend paying a visit to stats.stackexchange


text:
Q: WebHeaderCollection & HttpWebRequest on Xamarin I'm trying to port my project from Xamarin Studio on Mac to Visual Studio 2012 on Windows 7.
On Mac and XS works all fine. On VisualStudio 2012 i've those 2 problems:

Error 3   'System.Net.WebHeaderCollection' does not contain a definition
  for 'Add' and no extension method 'Add' accepting a first argument of
  type 'System.Net.WebHeaderCollection' could be found (are you missing
  a using directive or an assembly
  reference?)   C:\Users\user\Documents\Visual Studio
  2012\Projects\MyProject\MyProject.Core\Services\MyProjectService.cs
Error 4   'System.Net.HttpWebRequest' does not contain a definition for
  'GetResponse' and no extension method 'GetResponse' accepting a first
  argument of type 'System.Net.HttpWebRequest' could be found (are you
  missing a using directive or an assembly
  reference?)   C:\Users\user\Documents\Visual Studio
  2012\Projects\MyProject\MyProject.Core\Services\MyProjectService.cs

on that code:
    var request = WebRequest.Create("https://www.myaddress.com/test/") as HttpWebRequest;
    request.Method = "GET";
    request.Accept = "application/json";
    request.Headers.Add(HttpRequestHeader.Cookie,"mycookievalue");

    // Get response
    using (var response = request.GetResponse() as HttpWebResponse)
    {
        // Get the response stream
        var reader = new StreamReader(response.GetResponseStream());
        content = reader.ReadToEnd();
    }

How could i solve it?

A: There is no implementation of the things mentioned by you so far.
But that's ok. They still do their work great!
Answering to your questions.
Error 3. Yes. Currently you can use only Headers["key"] = value. But. Not for every header. I was trying to put "Content-Length" there (as there is no "ContentLength" property implemented as well), but got "restricted headers" exception.
However, Request POST processed successfully for me, so I let it go.
Error 4. Yes. There is no such method. (The same way, as there is no "GetRequestStream" (For instance, if you want to write POST data to request stream)). Good news is that there are BeginGetResponse and BeginGetRequestStream respectively, and C# action methods simplify all that kitchen.
(plus, I am sure, that's pretty useful for asynchronous practices general understanding).
Basic sample can be found on Microsoft official docs.
But to do it with actions I used the following:
    public void MakeRequest(string url, string verb, Dictionary<string, string> requestParams,
        Action<string> onSuccess, Action<Exception> onError)
    {
        string paramsFormatted;

        if (verb == "GET")
        {
            paramsFormatted = string.Join("&", requestParams.Select(x => x.Key + "=" + Uri.EscapeDataString(x.Value)));
            url = url + (string.IsNullOrEmpty(paramsFormatted) ? "" : "?" + paramsFormatted);
        }
        else
        {
            // I don't escape parameters here,
            // as Uri.EscapeDataString would throw exception if the parameter length
            // is too long, so you must control that manually before passing them here
            // for instance to convert to base64 safely
            paramsFormatted = string.Join("&", requestParams.Select(x => x.Key + "=" + (x.Value)));
        }

        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = verb;

        requestParams = requestParams ?? new Dictionary<string, string>();

        Action goRequest = () => MakeRequest(request,
            response =>
            {
                onSuccess(response);
            },
            error =>
            {
                if (onError != null)
                {
                    onError(error);
                }
            });

        if (request.Method == "POST")
        {
            request.BeginGetRequestStream(ar =>
            {
                using (Stream postStream = request.EndGetRequestStream(ar))
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(paramsFormatted);
                    postStream.Write(byteArray, 0, paramsFormatted.Length);
                }
                goRequest();
            }, request);
        }
        else // GET
        {
            goRequest();
        }
    }

    private void MakeRequest(HttpWebRequest request, Action<string> onSuccess, Action<Exception> onError)
    {
        request.BeginGetResponse(token =>
        {
            try
            {
                using (var response = request.EndGetResponse(token))
                {
                    using (var stream = response.GetResponseStream())
                    {
                        var reader = new StreamReader(stream);
                        onSuccess(reader.ReadToEnd());
                    }
                }
            }
            catch (WebException ex)
            {
                onError(ex);
            }
        }, null);
    }

A: To answer error 4, I made two extension methods so that I can have the GetRespone() and GetRequestStream() methods in the WebRequest class and working like their original versions i.e. blocking the thread. So here it is:
public static class ExtensionMethods
{
    public static WebResponse GetResponse(this WebRequest request){
        ManualResetEvent evt = new ManualResetEvent (false);
        WebResponse response = null;
        request.BeginGetResponse ((IAsyncResult ar) => {
            response = request.EndGetResponse(ar);
            evt.Set();
        }, null);
        evt.WaitOne ();
        return response as WebResponse;
    }

    public static Stream GetRequestStream(this WebRequest request){
        ManualResetEvent evt = new ManualResetEvent (false);
        Stream requestStream = null;
        request.BeginGetRequestStream ((IAsyncResult ar) => {
            requestStream = request.EndGetRequestStream(ar);
            evt.Set();
        }, null);
        evt.WaitOne ();
        return requestStream;
    }
}

Just make sure to place this in a different namespace than your regular code and import that namespace. Then you will have the GetResponse() method for WebRequest instances. Oh and also GetRequestStream() which is usefull for sending POST data


text:
Q: Drupal ccavenue payment error -Illegal access detected I am new in drupal, and I don't have much knowledge about it.
I have enabled ccavenue payment module with commerce in my drupal system, and created and donation page. If I am using another "Example payment", It's working without any issue.

But when I try to do payment with ccavenue, On repsonse page, It givin me error message "Security Error. Illegal access detected. We will store your IP address".
Is I missing something?

A: *

*You should give the URL from which you're sending the request to ccavenue and then they will add it to the white list URLs and you could see it in your merchant console account. ccavenue will not accept any requests from an unknown URL.

*Also did you check the merchant ID, accept token & encryption key correct?

Hope this information helps.


text:
Q: Proper way to create domain models and viewmodels in microservices I am trying to create a microservice and I am trying to make sure i follow the best practices/patterns for designing my objects.
I plan on separating my objects so that there is one for returning (querying using dapper) to clients (class code below) and one that actually does state changes (code not in this question) that will commit changes to db
I have a entity CalendarEvents in the db and I have a viewmodel for this called CalendarEvent and it has basic properties for each of the entity fields for mapping and I have bunch of other properties for CalendarEvent that are aggregates of entity fields.
Questions:

*

*What is the proper way to fill this CalendarEvent object (viewmodel), should all the properties be passed through a constructor when creating from entity thats read from the db or is there a better way to do it.

*Should I be taking in the _dateformat or is there a more elegant way (this is coming from configuration file)
Below is my class for CalendarEntity (the class to be used as viewmodel)
Also if anyone can spot any other issues (probably many) with my approach, I would appreciate it.
public class CalendarEvent
{
    private readonly string _dateFormat;
    public CalendarEvent(string dateFormat)
    {
        _dateFormat = dateFormat;
    }

    public int EventId { get; set; }

    public string Title { get; set; }

    public DateTime? StartDateTimeUtc { get; set; }

    public DateTime? EndDateTimeUtc { get; set; }

    public string Summary { get; set; }

    public bool IsApproved { get; set; }

    public string TimeZoneId { get; set; }

    public bool IsDeleted { get; set; }

    public int ViewCount { get; set; }

    public DateTime CreatedDateUtc { get; set; }

    public DateTime? FeaturedStartDateUtc { get; set; }

    public DateTime? FeaturedEndDateUtc { get; set; }

    public string ContactEmailAddress { get; set; }

    public EventDateType DateType { get; set; }

    public int? Year { get; set; }

    public int? Period { get; set; }

    public EventCategory Category { get; set; }

    public string UrlFriendlyTitle => Helper.UrlFriendly(Title);

    public DateTime? EndDateTimeLocal { get; set; }

    public DateTime? StartDateTimeLocal { get; set; }

    public string FullEventDateString
    {
        get
        {
            string dateString;
            switch (DateType)
            {
                case EventDateType.Month:
                    {
                        var monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Period.Value);
                        dateString = $"{monthName} {Year}";
                        break;

                    }
                case EventDateType.Quarter:
                    {
                        dateString = $"{Period}{Helper.GetNumberOrdinalSuffix(Period.Value)} Quarter {Year}";
                        break;
                    }
                case EventDateType.Specific:
                    {
                        if (StartDateTimeLocal.HasValue && EndDateTimeLocal.HasValue)
                        {
                            if (StartDateTimeLocal.Value.Date == EndDateTimeLocal.Value.Date)
                            {
                                if (StartDateTimeLocal.Value.Date == EndDateTimeLocal.Value.Date
                                    && StartDateTimeLocal.Value.Hour == 0 && StartDateTimeLocal.Value.Minute == 0 &&
                                    StartDateTimeLocal.Value.Second == 0 && EndDateTimeLocal.Value.Hour == 23)
                                {
                                    dateString = StartDateTimeLocal.Value.ToString(_dateFormat);
                                }
                                else
                                {

                                    var eventDateTime =
                                        $"{StartDateTimeLocal.Value.ToString(_dateFormat)} {StartDateTimeLocal.Value.ToShortTimeString()} - {EndDateTimeLocal.Value.ToShortTimeString()}";
                                    dateString = eventDateTime;
                                }
                            }
                            else
                            {
                                var eventDateTime =
                                    $"{StartDateTimeLocal.Value.ToString(_dateFormat)} - {EndDateTimeLocal.Value.ToString(_dateFormat)}";

                                dateString = eventDateTime;
                            }

                            break;

                        }
                        //TODO: fix this
                        throw new NotImplementedException();

                    }
                default:
                    throw new ArgumentOutOfRangeException();
            }

            return dateString;
        }
    }

    public EventStatuses Status
    {
        get
        {
            if (IsDeleted)
            {
                return EventStatuses.Deleted;
            }
            if (StartDateTimeUtc > DateTime.UtcNow)
            {
                return EventStatuses.NotStarted;
            }
            if (StartDateTimeUtc <= DateTime.UtcNow && EndDateTimeUtc > DateTime.UtcNow)
            {
                return EventStatuses.InProgress;
            }
            return EventStatuses.Completed;
        }
    }

    public string UrlFriendlyTitleForDisplay
    {
        get
        {
            var textInfo = new CultureInfo("en-US", false).TextInfo;
            return textInfo.ToTitleCase(UrlFriendlyTitle.ToLower().Replace("-", " "));

        }
    }

    private void GenerateLocalTimes()
    {

        if (DateType == EventDateType.Specific && StartDateTimeUtc.HasValue && EndDateTimeUtc.HasValue)
        {

            var tz = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneId);

             //TODO: make sure ticks is zero in this case, this use to be totalSeconds comparison
            if (tz.BaseUtcOffset.Ticks == 0)
            {
                EndDateTimeLocal = EndDateTimeUtc;
                StartDateTimeLocal = StartDateTimeUtc;
            }
            else
            {
                EndDateTimeLocal = TimeZoneInfo.ConvertTimeFromUtc(EndDateTimeUtc.Value, tz);
                StartDateTimeLocal = TimeZoneInfo.ConvertTimeFromUtc(StartDateTimeUtc.Value, tz);
            }
        }
        else
        {

            //TODO: fix this
            throw new NotImplementedException();
        }
    }

    public string GoogleCalendarLink
    {
        get
        {
            if (DateType == EventDateType.Specific && StartDateTimeUtc.HasValue && EndDateTimeUtc.HasValue)
            {
                var text = string.Empty;
                if (!string.IsNullOrEmpty(Title))
                {
                    text = Uri.EscapeUriString(Title);
                }

                var startDate = StartDateTimeUtc.Value.ToString("yyyyMMddTHHmmssZ");
                var endDate = EndDateTimeUtc.Value.ToString("yyyyMMddTHHmmssZ");
                var details = string.Empty;
                if (!string.IsNullOrEmpty(Summary))
                {
                    details = Uri.EscapeUriString(Summary);
                }

                return
                    $"http://www.google.com/calendar/event?action=TEMPLATE&text={text}&dates={startDate}/{endDate}&details={details}&location=";
            }

            //TODO: fix this
            throw new NotImplementedException();

        }
    }
}

A: I am going to assume that you are using a Web Api but the same principles apply to an MVC app. I normally have a mapper layer that takes a domain object and maps it to a view model or dto. This way you can reuse the mapper anytime you want to return the same view model. So if you make a change to the view model it is all located in one place.
See code below to answer question 1.
Question 2: Why does your mircoservice care about what date the client wants. If you send back utc date then if a client wants it in a format then its up to them to format it.
//Fake view model
public class CalendarEventViewModel
{
    public int EventId { get; set; }

    public string Title { get; set; }

    public DateTime? StartDateTimeUtc { get; set; }

    public DateTime? EndDateTimeUtc { get; set; }

    public string Summary { get; set; }

    public bool IsApproved { get; set; }

    public string TimeZoneId { get; set; }
}

public interface IMapper<in TIn, out TOut>
{
        TOut Map(TIn model);
}

public class CalendarEventViewModelMapper : IMapper<CalendarEvent, CalendarEventViewModel>
{
    public CalendarEventViewModel Map(CalendarEvent model)
    {
        return new CalendarEventViewModel
        {
            EndDateTimeUtc = model.EndDateTimeUtc,
            EventId = model.EventId,
            IsApproved = model.IsApproved,
            StartDateTimeUtc = model.StartDateTimeUtc,
            Summary = model.Summary,
            TimeZoneId = model.TimeZoneId,
            Title = model.Title
        };
    }
}

[Route("api/Values")]
public class ValuesController
{
       public ValuesController( IMapper<CalendarEvent, CalendarEventViewModel> calendarMapper)
       {
           _calendarMapper = calendarMapper;
       }

        // GET api/values/5
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {

            var calendarEvent = GetMyCalendarEventFromDB(id);

            return this.Ok(_calendarMapper.Map(calendarEvent));
        }

        private CalendarEvent GetMyCalendarEventFromDB(int id)
        {
            return new CalendarEvent("yyyy-dd-MM")
            {
                EndDateTimeUtc = DateTime.UtcNow.AddHours(3),
                EventId = id,
                IsApproved = true,
                StartDateTimeUtc = DateTime.UtcNow.AddHours(2),
                Summary = "My magical Event",
                TimeZoneId = "UTC",
                Title = "Magical Event"
            };
        }
    }
}


text:
Q: How to remove the last or some item from a sequence? How I can remove the last item from a sequence? I read the expl3 documentation, what I have is \seq_gpop_left/right, but I don't want to copy the deleted item in some tlist. Also I want to know, for example, how to remove items by index in expl3 sequences. Thanks everybody for answers.

A: To remove the last item of a sequence, use \seq_(g)pop_right:NN with a temporary token list.  There is no function in expl3 to "just remove" an item throwing it away because more often than not you need the popped item.  When you don't need it, just ignore the contents of the output token list.
There is no function to remove an indexed item, but it's not hard to build your own.  Here's a \kozlovskiy_(g)remove_seq_item:Nn <seq var> { <index> } that uses \seq_map_indexed_inline:Nn to loop over the <seq var>, and removes item number <index> from it.
\documentclass{article}
\ExplSyntaxOn
\seq_new:N \l__kozlovskiy_remove_tmp_seq
\cs_new_protected:Npn \kozlovskiy_remove_seq_item:Nn
  { \__kozlovskiy_remove_seq_item:NNn \seq_set_eq:NN }
\cs_new_protected:Npn \kozlovskiy_gremove_seq_item:Nn
  { \__kozlovskiy_remove_seq_item:NNn \seq_gset_eq:NN }
\cs_new_protected:Npn \__kozlovskiy_remove_seq_item:NNn #1 #2 #3
  {
    \seq_map_indexed_inline:Nn #2
      {
        \int_compare:nNnF {#3} = {##1}
          { \seq_put_right:Nn \l__kozlovskiy_remove_tmp_seq {##2} }
      }
    #1 #2 \l__kozlovskiy_remove_tmp_seq
  }
\ExplSyntaxOff

\begin{document}

\ExplSyntaxOn
\seq_new:N \g__kozlovskiy_vars_seq
\tl_new:N \g__kozlovskiy_tmp_tl

% Fill the sequence with some items
\seq_gset_from_clist:Nn \g__kozlovskiy_vars_seq
  { some, meaningless, items, to, populate, the, sequence, variable }

% To remove the last item use \seq_gpop_right:NN and just discard the token list
    \seq_show:N \g__kozlovskiy_vars_seq
\seq_gpop_right:NN \g__kozlovskiy_vars_seq \g__kozlovskiy_tmp_tl

% To remove the item in <index> use this function:
    \seq_show:N \g__kozlovskiy_vars_seq
\kozlovskiy_gremove_seq_item:Nn \g__kozlovskiy_vars_seq { 2 }
    \seq_show:N \g__kozlovskiy_vars_seq

\end{document}

The terminal shows (note that first {variable} is removed, then {meaningless}):
The sequence \g__kozlovskiy_vars_seq contains the items (without outer
braces):
>  {some}
>  {meaningless}
>  {items}
>  {to}
>  {populate}
>  {the}
>  {sequence}
>  {variable}.
<recently read> }

l.32     \seq_show:N \g__kozlovskiy_vars_seq

?
The sequence \g__kozlovskiy_vars_seq contains the items (without outer
braces):
>  {some}
>  {meaningless}
>  {items}
>  {to}
>  {populate}
>  {the}
>  {sequence}.
<recently read> }

l.36     \seq_show:N \g__kozlovskiy_vars_seq

?
The sequence \g__kozlovskiy_vars_seq contains the items (without outer
braces):
>  {some}
>  {items}
>  {to}
>  {populate}
>  {the}
>  {sequence}.
<recently read> }

l.38     \seq_show:N \g__kozlovskiy_vars_seq

?


text:
Q: EntityFramework, RIA insert problem - Updating child objects causes an Insert I've got a database which has a table called m_AttentionFlags which references a primary key in m_PermissionCollections. I've built an EntityFramework model from this and created a DomainService.
Now using RIA on the client I have loaded the flags into the local context on initialization of a control:
var query = _context.GetM_AttentionFlagQuery();
_context.Load(query, OnGetM_AttentionFlag, null);

Then I've wired up a button to add an m_PermissionCollection to a selected m_AttentionFlag.
if (lstSelected.SelectedItem != null) {
if (!(lstSelected.SelectedItem is m_AttentionFlag))
{
return;
}
m_AttentionFlag flag = lstSelected.SelectedItem as m_AttentionFlag;
m_PermissionCollection coll = new m_PermissionCollection(); //**
flag.m_PermissionCollections = coll; //**
_context.SubmitChanges();
}

Strangely this results in an Insert behaviour: an additional m_AttentionFlag with the same field values is added to the database with an associated m_PermissionCollection; the original remains intact without its m_PermissionCollections field being affected.
Interestingly if you remove the lines marked ** and replace with an update to a simple public property on m_AttentionFlag e.g. flag.Description = "new description", the update proceeds as expected.
The DomainService methods are the default ones generated by the wizards, and the only point of interest is that changing the m_PermissionCollections field on the m_AttentionFlag changes the EntityState on the item to Added when it is sent to the server.
I've asked this question on the RIA services forum and a member suggested I look for multiple DomainContext instances, but the _context member is only created once, and the code listed here is pretty much the only code not generated by the various visual studio tools. Any ideas as to what's happening here?
Help much appreciated.
Steve

A: It turns out the problem lay in the default DomainService implementation provided by VS2010 and the RIA services preview.
The problem is detailed here:
http://www.riaservicesblog.net/Blog/post/Bug-in-the-Create-DomainService-wizard.aspx


text:
Q: How to call ui object while in an inherited class I'm working on a Qt project. I have a inheritance class which is a Qt Gui class and I want to recover the ui object in the inherited class.
Here is my code :
inheritance class
namespace Ui {
class AddEditUser;
}

class AddEditUser : public QWidget
{
    Q_OBJECT

public:
    explicit AddEditUser(QWidget *parent = nullptr);
    virtual ~AddEditUser() = 0;

protected:
    Ui::AddEditUser *ui;
}

inherited class
#include "addedituser.h"

class AddUser : public AddEditUser
{
public:
    AddUser();

private slots:
    void on_validationButton_clicked();
};

call in inherited class
AddUser::AddUser()
{
    connect(ui->validateButton, SIGNAL(released()), this, SLOT(on_validationButton_clicked()));
}

I have this error (sorry, it's in french)
error

A: There will be a header in AddEditUser.cpp
#include "ui_addedituser.h"
or
#include "ui_ADDEDITUSER.h"

copy paste this header inside your inherited class and enjoy the access of ui.


text:
Q: Python formatting my json output # -*- coding: utf-8 -*-

import json
from pprint import pprint

drink_list = [23,601,633,673,607,662,6622,6014,6104,615,038,606,607,627,6094]

filename = (r'C:\Users\desktop\pizza\123template.json')

with open(filename, 'r') as f:
    data = f.read()

try:
    template = json.loads(data)
except Exception:
    # this file can also be here
    print('json exception')
    raise

for output in drink_list:
    print(output)
    temp = template.copy()
    temp["meta"]["sodanumber"] = output

    with open(r'C:\Users\desktop\pizza\123\{}.json'.format(output, indent=40), 'w', encoding='cp1252') as f:
        data = json.dumps(temp)
        f.write(data)
       # pprint.pprint(temp, width=60)

IndentationError: unindent does not match any outer indentation level.
But I think it's more than a simple indention. I can get my console to change formatting, but need the formatting to be changed in the actual output file. But where would I add my additional formatting to my "with open" line?
Have been reading material for 4 hours on this, and simple examples, but does the pprint do most of the work?
Current output is tons of work-wrapped text. Output needs to look like below. How can I get it to look like this?:
{
    "meta": {
        "drinkNumber": 662,
        "effectiveDate": "2016-10-12 16:00:31",
        "documentType": "checkout-device"
    },
    "documents": [
        {
            "code": "Checkout2",
            "name": "Printer 2",
            "port": "COM2",
            "type": "LABEL",

Current Output:
{ "meta": { "drinkNumber": 662, "effectiveDate": "2016-10-12 16:00:31", "documentType": "checkout-device" },"documents": [{
"code": "Checkout2","name": "Printer 2","port": "COM2","type": "LABEL",

A: import json

data = { "meta": { "drinkNumber": 662, "effectiveDate": "2016-10-12 16:00:31", "documentType": "checkout-device" },"documents": [{ "code": "Checkout2","name": "Printer 2","port": "COM2","type": "LABEL"}]}

json.dumps(data, sort_keys=True, indent=4)

Output:
{
    "documents": [
        {
            "code": "Checkout2",
            "name": "Printer 2",
            "port": "COM2",
            "type": "LABEL"
        }
    ],
    "meta": {
        "documentType": "checkout-device",
        "drinkNumber": 662,
        "effectiveDate": "2016-10-12 16:00:31"
    }
}

Note: your current output is not complete.


text:
Q: Internal vs External Include Guards I've heard that you should prefer writing internal include guards instead of external include guards. I have searched around the internet but haven't found an answer to it.
This is a snippet of the book C++ Coding Standards by Herb & Andrei that shows an "external include guard":

Avoid using the obsolete external include guards advocated in older
  books:

#ifndef FOO_HJNCLUDED_ //NOT recommended
#include "foo.h"
#define FOO_HJNCLUDED_
#endif

Now, this leads to the question below:
Q:
What is an internal include guard and what is an external include guard? What's the difference between the two, and why is internal include guards preferred? I would like that the answer also provide an example.
Edit: I ended up answering my own question.

A: Here's something I've seen that probably explains the comment.
Here, foo.h is defining an "internal include guard" (shortened to simply "include guard" by most people since it's the traditional way of doing it).
// foo.h
#ifndef _FOO_H__
#define _FOO_H__

// ...

#endif  // _FOO_H__

In contrast, bar.h is using foo.h's include guard outside of foo.h.  We can nickname this as an "external include guard".
// bar.h
#ifndef _BAR_H__
#define _BAR_H__

#ifndef _FOO_H__
#include "foo.h"
#endif

// ...

#endif  // _BAR_H__

One (very large) project I worked on claimed that this increased compiling speed, but the claim is dubious as this seems to me like a trivial compiler optimization and I haven't seen any metrics to prove the claim.  However, we did notice it was annoying to read when including multiple header files.

A: After a good digging around, I can now answer my own question.
 Internal Include Guard:
The common idiom putting "include guards" around the content of header files being included:
header.h
#ifndef HEADER_H
#define HEADER_H

// Contents of include file

#endif

Therefore, the content of the header will be processed once even though the header is #includeed multiple times. This is known as an "internal include guard" because the guard is entirely internal to the header file.

 External Include Guard:
However, there could be an issue with the above method if the compiler takes a simple approach, opening the file multiple times to check for "internal include guards" which could cause increased compile time in large projects.
header2.h
#ifndef HEADER_H
#include "header.h"
#endif

// Rest of header file goes here

The line: #ifndef HEADER_H is still defined and checked internally in header.h. But by checking it externally the compiler might avoid having to open the file at all.
It is only suggested to check externally when a header file is included from other header files. The check is not necessary when included from a source file.

Conclusion:

*

*Internal guard guarantees correctness

*External guard may improve speed of compilation on some compilers

*

*The cost involved is that of putting the check everywhere a header file is #included in another header file, and spelling the name of the guard symbol correctly. Therefore not preferred.


text:
Q: ORA-12560: TNS: protocol adapter error issue: Excel 64-bit/Windows 10 64-bit I'm running a VBA script I used to use when connecting to Oracle database through Excel 32-bit but now I'm using Excel 64-bit.
VBA code:
Set cn1 = New ADODB.Connection
Set rs1 = New ADODB.Recordset
cn1.ConnectionString = "Driver={Microsoft ODBC for Oracle};Server=BR1P1;Uid=BR1USER;Pwd=myPass"
cn1.Open
rs1.Open Query, cn1

When I execute "cn1.open" I get this error:
"Run-time error'-214746... [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
Then I tried to solve adding a new data source:
ODBC Data Source Administrator (64-bit)> File DSN> click in Add...> from list I select: Oracle em OraClient11g_home1 ("Oracle em" means "Oracle for", my OS in in portuguese)> Next> browse to the file: "C:\Windows\System32\odbcad32.exe"> Next> Finish
Doing so system will give me the driver name: "Oracle em OracleClient11g_home1"
Afterwards it will prompt for Service Name, User Name and Password. I inform server Name according to my TNSNAMES.ORA
Back to VBA I changed the code according to the driver name:
cn1.ConnectionString = "Driver={Oracle em OracleClient11g_home1}"

Now when execute "cn1.Open" in VBA I receive this new error message:
"Run-time error'-214746... [Oracle][ODBC]ORA-12560: TNS:protocol adapter error"

My TNSNAMES.ORA file is like this:
BR1P1 = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = myhost.com)(PORT = 1575))) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = BR1P1)))

Well I'm just stucked on this. Please I appreciate any help on this.
It's being a pain after I changed my MS Office to 64-bit version.

A: The Microsoft ODBC for Oracle exist only for 32-bit thus you cannot use it for 64-bit Excel.
If you like to use the 64-bit ODBC driver from Oracle then you must install it. Download the driver from 64-bit Oracle Data Access Components (ODAC) Downloads
The ConnectionString format of the Oracle ODBC Driver is different to the format of the Microsoft ODBC driver, see

*

*Microsoft ODBC Driver - Connection String Format and Attributes

*Oracle ODBC Driver - Format of the Connection String

*or https://www.connectionstrings.com/oracle/ -> ODBC drivers

So, for Oracle your ConnectionString
Driver={Microsoft ODBC for Oracle};Server=BR1P1;Uid=BR1USER;Pwd=myPass

will be
Driver={Oracle em OracleClient11g_home1};DBQ=BR1P1;Uid=BR1USER;Pwd=myPass


text:
Q: how to calculate the performed permutations of elements and display the sorting process of Quicksort in c++? I am a newbie in quicksort algorithm and I wanted to count swap and output the process of it(display the intermediate states of the array being sorted after each performed permutation.). Thank you.
#include <iostream>
#include <iomanip>
using namespace std;

void print(const int a[])
{
    for(int i=0;i < 10; i++) {
    cout << setw(3) << a[i];
    }
    cout << endl;
}

int Partition( int *A , int start , int end )
{
     int pivot = A[end];
     int partitionIndex = start;

     int i = start;
 while ( i < end ){
    if( A[i] < = pivot ){
        swap ( A[i], A[partitionIndex] );
        partitionIndex++;
    }
    i ++ ;
    print(A); //something wrong here?
}
    swap( A[partitionIndex], A[end]);
    return partitionIndex;
}

Here is my recursion function
void QuickSort( int *A , int start , int end ){
        if( start < end ){
           int partitionIndex = Partition( A , start , end );
            QuickSort( A , start , partitionIndex - 1 );
            QuickSort( A , partitionIndex + 1 , end );
 }

The main function
int main(){
     int n = 10;
     int *A = new int[n];

     for (int i = 0 ; i < n ; i ++ ){
         cin >> A[i];
     }
     cout<<endl;

  QuickSort( A , 0 , n - 1 );
  for(int i = 0 ; i < n ; i++){
    cout << A[i] <<" ";
  }
  delete []A;
 }

A: Here is a version of Quicksort that prints what it is doing.  It highlights in a certain colour the items an activity uses:

*

*yellow is used when two items are compared

*red is used when two items are swapped

*green is used to show where the pivot ends up

The code:
#include <iostream>
#include <iomanip>
using std::cout;
using std::setw;

void print(const char *prefix, const int a[], const int color, const int left, const int right, const int start, const int end, const int size)
{
    cout << setw(20) << prefix << " ";
    for (int i=0; i<size; i++)
    {
        if (i >= start && i <= end)
        {
            if (i == left || i == right)
                cout << " \x1b[1m\x1b[" << color << "m" << setw(3) << a[i] << "\x1b[0m";
            else
                cout << " \x1b[0m" << setw(3) << a[i];
        }
        else
            cout << setw(4) << " ";
    }
    cout << "\n";
}

int swaps = 0;

void swap(int A[], const int left, const int right, const int start, const int end, const int size)
{
    if (left == right)
        return;

    print("Swapping:", A, 31, left, right, start, end, size);

    int temp = A[left];
    A[left]  = A[right];
    A[right] = temp;

    swaps++;
}

int partition(int A[], const int start, const int end, const int size)
{
    int pivot = A[end];
    int partitionIndex = start;

    for (int i = start; i < end; i++)
    {
        print("Comparing:", A, 33, i, end, start, end, size);
        if (A[i] < pivot)
            swap(A, i, partitionIndex++, start, end, size);
    }

    swap(A, partitionIndex, end, start, end, size);
    return partitionIndex;
}

void quicksort(int A[], const int start, const int end, const int size)
{
    if (start > end)
        return;

    cout << "\n";
    print("About to sort:", A, 0, -1, -1, start, end, size);

    if (start == end)
        return;

    int p = partition(A, start, end, size);
    print("Partitioned:", A, 32, p, p, start, end, size);

    quicksort(A, start, p-1, size);
    quicksort(A, p+1, end, size);
}

int main()
{
    int A[] = { 7, 2, 9, 1, 8, 4, 6, 3, 10, 5 };
    quicksort(A, 0, 9, 10);

    cout << "\n";
    print("Sorted:", A, -1, -1, -1, 0, 9, 10);

    return 0;
}

Try it here: https://onlinegdb.com/BJJ-9IXGd
In case your environment doesn't understand ANSI escape sequences, here is a variant that displays similar info but doesn't use them:
#include <iostream>
#include <iomanip>
using std::cout;
using std::setw;

void print(const char *prefix, const int a[], const int start, const int end, const int size)
{
    cout << setw(20) << prefix << " {";
    for (int i=0; i<size; i++)
        if (i >= start && i <= end)
            cout << (i == 0 ? "" : ",") << setw(3) << a[i];
        else
            cout << (i == 0 ? "" : ",") << setw(3) << " ";
    cout << "}\n";
}

void print_swap(const char *prefix, const int a[], const int left, const int right, const int size)
{
    cout << setw(20) << prefix << " {";
    for (int i=0; i<size; i++)
        if (i == left || i == right)
            cout << (i == 0 ? "" : ",") << setw(3) << a[i];
        else
            cout << (i == 0 ? "" : ",") << setw(3) << " ";
    cout << "}\n";
}

int swaps = 0;

void swap(int A[], const int left, const int right, const int size)
{
    if (left == right)
        return;

    print_swap("Swapping:", A, left, right, size);

    int temp = A[left];
    A[left]  = A[right];
    A[right] = temp;

    swaps++;
}

int partition(int A[], const int start, const int end, const int size)
{
    int pivot = A[end];
    int partitionIndex = start;

    for (int i = start; i < end; i++)
    {
        print_swap("Comparing:", A, i, end, size);
        if (A[i] < pivot)
            swap(A, i, partitionIndex++, size);
    }

    swap(A, partitionIndex, end, size);
    return partitionIndex;
}

void quicksort(int A[], const int start, const int end, const int size)
{
    if (start > end)
        return;

    cout << "\n";
    print("About to sort:", A, start, end, size);

    if (start == end)
        return;

    int p = partition(A, start, end, size);
    print("Partition:", A, p, p, size);
    print("Partitioned:", A, start, end, size);

    quicksort(A, start, p-1, size);
    quicksort(A, p+1, end, size);
}

int main()
{
    int A[] = { 7, 2, 9, 1, 8, 4, 6, 3, 10, 5 };
    quicksort(A, 0, 9, 10);

    cout << "\n";
    print("Sorted:", A, 0, 9, 10);

    return 0;
}

Try it here: https://onlinegdb.com/rktvKUQfd


text:
Q: Attempt to index field (a nil value) I am trying to make simple object container in Lua ( to practice a language a little)
Container = {}
Container.__index = Container

function Container.create( maxNumber )
   local c = {}             -- our new object
   setmetatable(c, Container)
   c.maxNumberOfRecords = maxNumber
   c.cont = {}
   return c
end

function Container:add(index, val)
         self.cont[index] = val
end

function Container:getAt(index)
    return self.cont[index]
end

return Container

but I always get error Attempt to index field 'cont' (a nil value) when I try to add to container. Can anyone tell me what is a problem ?
I am totally new to lua but I looked at code at documentation http://lua-users.org/wiki/SimpleLuaClasses

A: Can you show an example of code that does not work? It looks OK to me:
> Container = require "Container"
> c = Container.create(5)
> c:add(2, 42)
> =c:getAt(2)
42


text:
Q: Looping through all the ACF fields whose key starts with a specific string I have some custom fields on some posts, and I have assigned some of them keys with unique values: 'field_tab_' . uniqid()
I would like to loop through all the ACF fields whose key starts with specific string field_tab_.
This is what I have so far, but I cannot work it out how to check for a certain string in the key.
<?php
$fields = get_field_objects();
if( $fields ): ?>

        <?php foreach( $fields as $field ): ?>

<?php echo $field['label']; ?>: <?php echo $field['value']; ?>

        <?php endforeach; ?>

<?php endif; ?>

I can use the name instead of the key as well, if that makes it easier.
What would be the best way to do this?

A: If $field[label] is the key and contains the string field_tab_ then try this:
    <?php
    $fields = get_field_objects();
    if( $fields ): ?>

            <?php foreach( $fields as $field ): ?>
                <?php if(strpos($field[label],'field_tab_') { ?>

<?php echo $field['label']; ?>: <?php echo $field['value']; ?>

                <?php } ?>
            <?php endforeach; ?>

    <?php endif; ?>

https://www.php.net/manual/de/function.strpos.php
Code is unchecked.


text:
Q: django - clean dynamic field I have a model:
class Order(models.Model):
    order_type = models.ForeignKey(OrderType)
    quantity = models.IntegerField(max_digits=10, decimal_places=4)
    product = models.ForeignKey(Product)

I added the form filed dynamically:
class OrderForm(ModelForm):
    class Meta:
        model = Order
        fields = [
            'order_type', 'product'
        ]
        widgets = {
            'order_type': Select(attrs={'class': 'form-control'}),
            'product': Select(attrs={'class': 'form-control'}),
        }

    def __init__(self, types=[],*args, **kwargs):
        super(OrderForm, self).__init__(*args, **kwargs)

        if "AMOUNT" in types:
            self.fields['quantity'] = IntegerField(
                NumberInput(attrs={'class': 'form-control'})
            )

And in CreateView I overwrite post. In the frontend I'm sending ajax with data or not (if data is sent, I want to generate form with addition quantity field), then I replace the old form with this new:
class OrderCreateView(CreateView):
    model = Order
    form_class = OrderForm

    def post(self, request, *args, **kwargs):
        self.object = None
        d = request.POST.get('DATA', None)
        if d is not None:

            form = self.form_class(
                types=["AMOUNT"],
                **self.kwargs
            )
            return render(
                request, 'form.html', {'form': form}
            )
        else:
            form = self.form_class(**self.kwargs)
            return render(
                request, 'form.html', {'form': form}
            )
        return super(OrderCreateView, self).post(request, *args, **kwargs)

And it "works". I get new form with a quantity. But when I'm trying do submit this form, I get an error
null value in column "quantity" violates not-null constraint

A: In your model try to change
quantity = models.IntegerField(max_digits=10, decimal_places=4)

to
quantity = models.IntegerField(max_digits=10, decimal_places=4, null=True, blank=True)

Whenever you don't have the flag "AMOUNT" it tries to create an Order without filling that field.
UPDATE:
Try this in your form
fields = [
        'order_type', 'product', 'quantity'
    ]
widgets = {
        'order_type': Select(attrs={'class': 'form-control'}),
        'product': Select(attrs={'class': 'form-control'}),
        'quantity': NumberInput(attrs={'class': 'form-control'}),
    }
def __init__(self, types=[],*args, **kwargs):
    super(OrderForm, self).__init__(*args, **kwargs)

    if "AMOUNT" not in types:
        del self.fields['quantity']

In your view put the super() before as @neverwalkaloner mentioned

A: Last line of your post method is unreachable. Post function will never go here:
return super(OrderCreateView, self).post(request, *args, **kwargs)

I suppose you need to change logic of your code. For example if it possible instead of sending 'DATA' with POST try to send it with GET. Or create another view to render form with 'AMOUNT' field.
UPDATE
Also please note that super().post() calls get_form() which return default instance of form_class. Considering this super().post() probably is not what you really need. Try to perform form validation and form saving manually:
form = self.form_class(
        types=["AMOUNT"],
        **self.kwargs
    )
if form.is_valid():
    instance = self.form.save()
    return super().get()


text:
Q: plotting a curve in MATLAB with prefefined x-axis I have two vectors:
x = [1, 2, 3, 5, 6, 10, 20, 50, 100]
and
y=[7, 1, 2, 4, 2, 1, 5, 1, 1];
I am interested to plot Y as a function of X in MATLAB. So, this can be done by:
figure;
plot(x, y, '--rs');

In fact, the code above plots the curve, but the x-axis seems to be spaced as follows: 0, 10, 20, ..., 100.
What I want is to draw a curve which exhibits just the values in x as x-axis and their corresponding y-axis values. An example of x-axis is shown in the picture below.

Any help will be very appreciated!!

A: Instead of plotting using plot(x,y), use plot(1:numel(x),y) and use the XTick and XTickLabels` properties to change the labelling of the graph to suit your need.
Example:
clc
clear

x = [1, 2, 3, 5, 6, 10, 20, 50, 100];

y=[7, 1, 2, 4, 2, 1, 5, 1, 1];

plot(1:numel(x),y,'--rs')

set(gca, 'XTick', 1:length(x)); %// Change x-axis ticks
set(gca, 'XTickLabel', x); %// Change x-axis ticks labels.

Result:

Hope that helps!


text:
Q: GWT Compiler cannot find Collect.gwt.xml, but I have Guava as a dependency I'm moving over to a new computer, and in the processing I'm creating new Intellij 12 projects from my git source.
I have a gwt module file containing the following:
<!-- Other module inherits                                      -->
<inherits name="com.google.common.collect.Collect" />
<inherits name="com.google.common.base.Base" />
<inherits name="com.bdl.message.Message" />
<inherits name="com.bdl.universal.Universal" />
<inherits name="com.bdl.appengine.AppEngine" />
<inherits name="com.bdl.gwt.BdlGwt" />
<inherits name="com.google.gwt.inject.Inject"/>

The com.bdl.* entries are from another library I've written and I have their jar files (and sources) in the module dependencies.  I can confirm that removing those dependencies causes the corresponding inherits nameto turn red, indicating an error.
I also have as a dependency, a global library Guava (GWT) which contains:
classes:
    guava-14.0-rc2.jar
sources:
    guava-14.0-rc2-sources.jar
    guava-gwt-14.0-rc2.jar
javadoc
    guava-14.0-rc2-javadoc.jar
But despite this, the inherits for Collect and Base are red and the GWT compiler fails, saying it can't find Collect.gwt.xml.
On my old system I have an Intellij 11 project, which is set up the same way (there must be some difference somewhere, but I've been looking for hours to find it and can't)
That also has the same library as a dependency, and the inherits lines in my app's module are still red, but the GWT compiler succeeds, finding the Collect.gwt.xml right where it should be, at:
jar:file:/[path-to-guava]/guava-gwt-14.0-rc2.jar!/com/google/common/collect/Collect.gwt.xml
There must be something simple and stupid that I'm missing, but I can't find it.

A: You probably need to add guava-gwt-14.0-rc2.jar to your dependencies. Notice that the name has -gwt- embedded in it and you said that you have just these as dependencies:guava-14.0-rc2.jar sources: guava-14.0-rc2-sources.jar guava-gwt-14.0-rc2.jar javadoc guava-14.0-rc2-javadoc.jar
You can check that the jar is the appropriate one because when you open it (it is just a zip file) you should see the Collect.gwt.xml file somwhere within.


text:
Q: Hello Google Maps Example NULL Pointer Exception I am creating a google maps application for android and I am following the guide at http://developer.android.com/resources/tutorials/views/hello-mapview.html to get started.
I can run the app just fine in my emulator, but when I click on the overlay item I get a NULL Pointer Exception. The trace is below. I'm new to Android and have no idea how to debug this. So any help would be greatly appreciated.
12-20 02:57:05.898: W/dalvikvm(473): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-20 02:57:05.928: E/AndroidRuntime(473): FATAL EXCEPTION: main
12-20 02:57:05.928: E/AndroidRuntime(473): java.lang.NullPointerException
12-20 02:57:05.928: E/AndroidRuntime(473):  at com.android.internal.app.AlertController$AlertParams.<init>(AlertController.java:742)
12-20 02:57:05.928: E/AndroidRuntime(473):  at android.app.AlertDialog$Builder.<init>(AlertDialog.java:273)
12-20 02:57:05.928: E/AndroidRuntime(473):  at hello.google.maps.HelloItemizedOverlay.onTap(HelloItemizedOverlay.java:41)
12-20 02:57:05.928: E/AndroidRuntime(473):  at com.google.android.maps.ItemizedOverlay.onTap(ItemizedOverlay.java:453)
12-20 02:57:05.928: E/AndroidRuntime(473):  at com.google.android.maps.OverlayBundle.onTap(OverlayBundle.java:83)
12-20 02:57:05.928: E/AndroidRuntime(473):  at com.google.android.maps.MapView$1.onSingleTapUp(MapView.java:356)
12-20 02:57:05.928: E/AndroidRuntime(473):  at com.google.android.maps.GestureDetector.onTouchEvent(GestureDetector.java:533)
12-20 02:57:05.928: E/AndroidRuntime(473):  at com.google.android.maps.MapView.onTouchEvent(MapView.java:683)
12-20 02:57:05.928: E/AndroidRuntime(473):  at android.view.View.dispatchTouchEvent(View.java:3885)
12-20 02:57:05.928: E/AndroidRuntime(473):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903)
12-20 02:57:05.928: E/AndroidRuntime(473):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
12-20 02:57:05.928: E/AndroidRuntime(473):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
12-20 02:57:05.928: E/AndroidRuntime(473):  at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1691)
12-20 02:57:05.928: E/AndroidRuntime(473):  at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1125)
12-20 02:57:05.928: E/AndroidRuntime(473):  at android.app.Activity.dispatchTouchEvent(Activity.java:2096)
12-20 02:57:05.928: E/AndroidRuntime(473):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1675)
12-20 02:57:05.928: E/AndroidRuntime(473):  at android.view.ViewRoot.deliverPointerEvent(ViewRoot.java:2194)
12-20 02:57:05.928: E/AndroidRuntime(473):  at android.view.ViewRoot.handleMessage(ViewRoot.java:1878)
12-20 02:57:05.928: E/AndroidRuntime(473):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-20 02:57:05.928: E/AndroidRuntime(473):  at android.os.Looper.loop(Looper.java:130)
12-20 02:57:05.928: E/AndroidRuntime(473):  at android.app.ActivityThread.main(ActivityThread.java:3683)
12-20 02:57:05.928: E/AndroidRuntime(473):  at java.lang.reflect.Method.invokeNative(Native Method)
12-20 02:57:05.928: E/AndroidRuntime(473):  at java.lang.reflect.Method.invoke(Method.java:507)
12-20 02:57:05.928: E/AndroidRuntime(473):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-20 02:57:05.928: E/AndroidRuntime(473):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-20 02:57:05.928: E/AndroidRuntime(473):  at dalvik.system.NativeStart.main(Native Method)

Thanks!

A: That rings a bell. I think the solution can be found here: http://www.anddev.org/map-problems-f26/error-when-trying-to-access-overlay-text-t12324.html?sid=87163bc814ce6ded7400844529c7d7f3#wrap

A: generally speaking, try to catch exceptions and make use of Log and TAG.
http://developer.android.com/reference/android/util/Log.html.
This helped me a lot!
A basic tutorial: http://www.androidza.co.za/beyond-hello-world-logcat-and-exception-handling/

A: Maybe you use the one-param constructor like I did,But theAlertDialog.Builder need a instantiated object,which you may forget to do.


text:
Q: How to use JSON with react-ace? Im using react-ace and trying the readme example with java syntax. Works great. But I can't seem to set it to JSON.
Java works
import AceEditor from "react-ace";
import "ace-builds/src-noconflict/mode-java";
import "ace-builds/src-noconflict/theme-github";

<AceEditor
    mode="java"
    theme="github"
    name="UNIQUE_ID_OF_DIV"
    editorProps={{ $blockScrolling: true }}
/>

JSON does not work?
import AceEditor from "react-ace";
import "ace-builds/src-noconflict/mode-json";
import "ace-builds/src-noconflict/theme-github";

<AceEditor
    mode="json"
    theme="github"
    name="UNIQUE_ID_OF_DIV"
    editorProps={{ $blockScrolling: true }}
/>

The error

Refused to execute script from '...../worker-json.js' because its MIME type ('text/html') is not executable.
(anonymous) @ 2f896707-86be-497a-93b2-e1711942d7c7:1
2f896707-86be-497a-93b2-e1711942d7c7:1 Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at '...../worker-json.js' failed to load.

How to use JSON?

A: Try to setOption useWorker: false
      <AceEditor
        mode="json"
        theme="github"
        onChange={onChange}
        name="UNIQUE_ID_OF_DIV"
        editorProps={{ $blockScrolling: true }}
        setOptions={{
          useWorker: false
        }}
      />

A: From my understanding, you would need to do either way to resolve the worker problem.

*

*Import this ace-builds/webpack-resolver:

import AceEditor from "react-ace";

import "ace-builds/src-noconflict/mode-json";
import "ace-builds/src-noconflict/theme-github";

import 'ace-builds/webpack-resolver';

*

*Use file-loader to load worker-json file & then configure ace worker:

import AceEditor from "react-ace";

import "ace-builds/src-noconflict/mode-json";
import "ace-builds/src-noconflict/theme-github";

import ace from "ace-builds";

// `webpack` would return the url for `worker-json.js`
// then we use it to configure `ace`
import jsonWorkerUrl from "file-loader!ace-builds/src-noconflict/worker-json";

ace.config.setModuleUrl("ace/mode/json_worker", jsonWorkerUrl);

A: One way I made it work was to use mode/json5 (json5 is a superset of json so it work normal) instead of mode/json.
Looking at the some github issue on this problem it seems to have few good options to be able to use mode/json.

*

*not every project works to import the worker via webpack/file-loader

*using the webpack-resolver makes the build to big

Some issues on ace own library and some componentes of some other frameworks that use ace.

*

*Vue ace component

*Ace

*Agular ace component

A: For those searching how to implement workers now, when file-upload is deprecated with Webpack 5 asset/resource.
webpack config:
rules: [
  {
      test: /ace-builds.*\/worker-.*$/,
      type: "asset/resource"
  },
],

component:
import AceEditor from "react-ace";
import { config } from "ace-builds";
import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/theme-github";
import "ace-builds/src-noconflict/ext-language_tools";
import jsWorkerUrl from "ace-builds/src-noconflict/worker-javascript";
config.setModuleUrl("ace/mode/javascript_worker", jsWorkerUrl);

To fix the typescript "no module declaration" error, just add the global.d.ts file to your src folder:
declare module "ace-builds/src-noconflict/worker-javascript";


text:
Q: Automated script or program for copying and renaming a file I would like to have a script or maybe some kind of program that is monitoring selected file, and when the date of a file changes(file gets updated every hour), this script copies this file to another folder and renames it at the same time. But needs to overwrite the old one.
For example. File aaa.dat gets updated, script recognizes change, moves file to desired folder, renames file to bbb.dat, overwrite the old bbb.dat.

A: You can use entr to achive this.
 <<<"aaa.dat" entr cp -f \_ dest_path/bbb.dat

cp will overwrite bbb.dat file in dest_path


text:
Q: Get index of a specific element in vector using %>% operator I want the index of an element in a vector x
x <- c("apple", "banana", "peach", "cherry")

With base R i would do that
which(x == "peach")

But as my x is at the end of a pipe I would like to get the index the magrittr way.
x %>% getIndex("peach")

My desired output is 3.

A: You can refer the left-hand side (lhs) of the pipe using the dot (.). There's two scenarios for this:

*

*You want to use the lhs as an argument that is not in the first position. A common example is use of a data argument:
mtcars %>% lm(mpg~cyl, data = .)

In this case, margrittr will not inject the lhs into the first argument, but only in the argument marked with ..

*You want to include the lhs not as a single function argument, but rather as part of an expression. This is your case! In this case magrittr will still inject the lhs as the first argument as well. You can cancel that with the curly braces ({).
So you need to use . notation with { braces:
x %>% { which(. == "peach") }

[1] 3

Excluding the { would lead to trying to run the equivalent of which(x, x == "peach"), which yields an error.

A: Or simply:
x %>% match(x = "peach")

# [1] 3

(Differs from which() in that it only gives you the first match):
y <- c("apple", "banana", "peach", "cherry", "peach")
y %>% `==`("peach") %>% which()
# [1] 3 5
y %>% match(x = "peach")
# [1] 3


text:
Q: Custom menu is not clickable I am trying to create a 3 horizontal dot menu. My code below sets the 3 dots fine but the menu can't be clicked and doesn't show the menu item with the header "Remove item".
Any ideas why?
<Window.Resources>
        <Style TargetType="{x:Type Menu}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Menu}">
                        <Canvas >
                            <Path Data="M12.5,6.5 C12.5,9.8137085 9.8137085,12.5 6.5,12.5 C3.1862915,12.5 0.5,9.8137085 0.5,6.5 C0.5,3.1862915 3.1862915,0.5 6.5,0.5 C9.8137085,0.5 12.5,3.1862915 12.5,6.5 z M30.5,6.5 C30.5,9.8137085 27.813708,12.5 24.5,12.5 C21.186292,12.5 18.5,9.8137085 18.5,6.5 C18.5,3.1862915 21.186292,0.5 24.5,0.5 C27.813708,0.5 30.5,3.1862915 30.5,6.5 z M48.5,6.5 C48.5,9.8137085 45.813708,12.5 42.5,12.5 C39.186292,12.5 36.5,9.8137085 36.5,6.5 C36.5,3.1862915 39.186292,0.5 42.5,0.5 C45.813708,0.5 48.5,3.1862915 48.5,6.5 z"
                                    Fill="Black"
                                    HorizontalAlignment="Left"
                                    Stretch="Fill"
                                    Stroke="Black"
                                    VerticalAlignment="Top"
                                    Height="7" Width="23"/>
                        </Canvas>

                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

    </Window.Resources>
    <Grid>
        <Menu>
            <MenuItem Header="Remove item" FontSize="12" />
        </Menu>
    </Grid>

A: The ControlTemplate is supposed to include an <ItemsPresenter /> element for the child items to be generated.
So you should add the <ItemsPresenter /> element to your custom template. You may for example use a Grid or some other Panel as the root element of the template and then add both the Canvas and the ItemsPresenter to it.


text:
Q: I am trying to write a program that determines if the sequence of characters is valid or invalid If the user enters any character other than ACGT (sequence does not matter) then it should print "INVALID". The user just keeps entering the sequence not more than 250 characters.
#include <stdio.h>
#include <string.h>
int main(void)
{
    char dna[250];
int i;
for(i=0; i<250; i++)
{
    scanf("%c", dna[i]);
}
fgets(*dna, 250, scanf("%c", dna));
int k;
for(k=0; k<250; k++)
{
    if(dna[k] == 'A' || 'C' || 'G'|| 'T')
    {
        i++;
        //printf("%c\n", dna[0])
    }
}
if(i > 0)
{
    printf("VALID sequence \n");
}
else
{
    printf("INVALID sequence \n");
}

}

A: like this
#include <stdio.h>

int main(void){
    char dna[250+1], rest;
    if(scanf("%250[ACGT]%c", dna, &rest) == 2 && rest == '\n')
        printf("VALID sequence \n");
    else
        printf("INVALID sequence \n");
}

A: There are a large number of ways to approach the problem. You can use scanf with character classes as shown, or you can use any other method to read the input (e.g. getchar, fgets, POSIX getline) and then simply analyze the characters entered for anything other than "ACGT".
Additionally, in your problem statement you state "The user just keeps entering the sequence not more than 250 characters". Obviously you will need to loop to handle entry of multiple strings, but beyond that, you will also need to protect against and handle the remainder of any strings greater than 250 characters. It is unclear whether in that case, you want to keep the first 250 valid characters entered (seems logical you would), and then discard any over the 250 character limit.
Your tools for validating the input are, in the case of using character-oriented input (e.g. using getchar) are simply to check each character input against your ACGT. When using line-oriented input, (e.g. fgets or getline) the C library provides a number of tools to check for characters within a string, or substrings within a string (strchr is applicable here) or you can simply walk a pointer down the entire string of input checking each character. (you also need to check for, and remove the '\n' the line-oriented functions read and include in the buffer)
Putting the pieces together into a short example using fgets for input and strchr to check whether each character is one of ACGT, you could do something like the following. Here the user can enter as many strings as desired. The program terminates when EOF is read (manually generated with Ctrl + D on Linux, Ctrl + Z on windoze). In the event an invalid string is entered, the code identifies the position of the first invalid character in the entry:
#include <stdio.h>
#include <string.h>

#define MAXC 250

int main (void) {

    char str[MAXC+1] = "", *valid = "ACGT";

    printf ("Enter sequences [ctrl+d] to quit:\n");
    while (fgets (str, MAXC+1, stdin))          /* read input */
    {
        size_t len = strlen (str), good = 1;    /* get length, set flag */
        char *p = str;                          /* pointer to str */
        int c;

        if (str[len-1] == '\n')                 /* trim '\n' char */
            str[--len] = 0;                     /* overwrite with nul */
        else                                    /* line > 250, discard extra */
            while ((c = getchar()) != '\n' && c != EOF) {}

        for (; *p; p++)                         /* for each char in str */
            if (!strchr (valid, *p)) {          /* check against valid  */
                good = 0;                       /* not found - invalid */
                break;
            }

        if (good)
            printf ("VALID\n");
        else
            fprintf (stderr, "INVALID ('%c' at character '%ld'\n", *p, p - str);
    }

    return 0;
}

Example Use/Output
$ ./bin/acgtvalid
Enter sequences [ctrl+d] to quit:
ACGTTTGGCCCATTAGGC
VALID
ACCGGTTCCGGAITT
INVALID ('I' at character '12')


text:
Q: Get a daterange in extjs 4 Im working on an application in extJS4 and i need to enter 2 values: startdate and enddate.
Both of them require an Ext.Date object.
Link to the date object
What i want is for the startdate to be todays date minus 4 months and enddate should be todays date plus 4 months. Anyone know how i can achieve that?
Also would i be possible to get these values through an ajax call. So i can define them somewhere else and do an ajax call for them?

A: There's example of using Date.add right there in the docs you linked:
var d = new Date(),
    eDate = Ext.Date,
    start = eDate.add(d, eDate.MONTH, -4),
    end = eDate.add(d, eDate.MONTH, 4);


text:
Q: Flutter app keeps stoping when i'm trying to extarct text from image using google_ml_vision: ^0.0.7 I'm trying to extract Arabic text from an image using  google_ml_vision: ^0.0.7,
I wrote the function below, but when I call it the app crashed(its crashed in this point await textRecognizer.processImage(visionImage))  without providing any logs
the image path is correct but it still didn't work
  Future _extarctArabicTexFromImage() async {
    try {
      // final File imageFile = File(imgPath);

      final GoogleVisionImage visionImage =
          GoogleVisionImage.fromFilePath(imgPath);

      final TextRecognizer textRecognizer =
          GoogleVision.instance.textRecognizer();
      late VisionText visionText;
      try {
        visionText = await textRecognizer.processImage(visionImage);

      } catch (e) {
        print(e.toString());
      }
      // String  text = visionText.text;
      for (var block in visionText.blocks) {
        final List<RecognizedLanguage> languages = block.recognizedLanguages;

        for (var line in block.lines) {
          for (var textElement in line.elements) {
            txt = txt + " " + textElement.text.toString();
          }

          txt = txt + '\n';
        }
      }
    } catch (e) {
      print(e.toString());
    }
  }


text:
Q: breadcrumbs for multi-level url I want to create multi-level breadcrumbs, like if user go to  Home->Step1->step2->step3 page then goes to Step4 :  i want  to see my breadcrumbs Home:->step1->step2-step3->->step4.
Here is my code :
<?php
    $path = parse_url($_SERVER['HTTP_REFERER'],PHP_URL_PATH);
    $parts = explode('/',$path);
    $stepname='Step'.$step->step_code;
    if (count($parts) < 2)
    {
        echo("home");
    }
    else
    {
        for ($i = 2; $i < count($parts); $i++)
        {
            if (!strstr($parts[$i],"."))
            {
                echo("<a href=\"");
                for ($j = 0; $j <= $i; $j++)
                {
                    echo $parts[$j]."/";
                };
                echo("\">". str_replace('-', ' ', $parts[$i])." » ");
            }
        };
    };
?>

but its  show only Home->step3>step4 ,its not show step2 and step3.
Actually I want multilevel breadcrumbs.

A: I recommend using Yii built in class CBreadcrumbs.
Besides that, you have logic error in your if statement. Home will show only if there are no other items.
Move if after echo home:
echo("home");

if (count($parts) > 2)
{
...

A: <?php
# Rewritten Ajmal PraveeN
    $path = parse_url($_SERVER['HTTP_REFERER'],PHP_URL_PATH);
    $parts = explode('/',$path);
    $stepname='Step'.$step->step_code;
    if (count($parts) < 2)
    {
        echo("home");
    }
    else
    {
        for ($i = 0; $i < count($parts); $i++)
        {
            if (!strstr($parts[$i],"."))
            {
                echo("<a href=\"");
                for ($j = 0; $j <= $i; $j++)
                {
                    echo $parts[$j]."/";
                };
                echo("\">". str_replace('-', ' ', $parts[$i])." » ");
            }
        }
    }
?>

The above code works fine with slash directories
ex: If php explodes a path is /home/website/public or Infinite path levels, the script generates what you are looking for ;)
Changes I made are $i = 2 to $i = 0
and A suggestion instead of str_replace use CSS styling for the »
Thank you..!


text:
Q: Non-homogeneous Poisson Process Suppose that a store opens at 0pm and customers arrive according to a non-homogenous Poisson process ${N(t),t\geq0}$ with the intensity function $λ(t)=3t$ per hour.
a) Let $S_2$ denote the time at which the second customer arrives. Calculate $P[2<S_2\leq3|N(1)=1]$.
b) Find the probability that the total number of customers arriving at the store during the three intervals 1-1:15pm, 2-2:15pm and 3-3:30pm is at least 3.
Here is what I tried so far for a)
$P[2<S_2\leq3|N(1)=1]$
=$P[2<S_2|N(1)=1]$-$P[3\leq S_2|N(1)=1]$
=$P[N(2)\leq2|N(1)=1]$-$P[N(3)\leq2|N(1)=1]$
=$P[N(2)-N(1)\leq1]$-$P[N(3)-N(1)\leq1]$
=$e^{4.5}$-$e^{12}$+$4.5e^{4.5}$-$12e^{12}$
Can someone confirm if I'm on the right track ?


text:
Q: Fixes positions for nodes in r igraph? Suppose we want to visualise a network like the one below
library(igraph)
a<- cbind(c(1,2,3,4,5),
c(2,4,1,2,2))
b<- graph.edgelist(a, directed=FALSE)

Is there any way to keep the nodes in the same position apart from setting the coords by hand?? For example, can we edit the graph with tkplot and save the layout so that it remains the same no matter how many times we run the code? By using the function tkplot.getcoords, I manage to save the layout only once. Is repeatablility possible?
Thank you in advance.

A: A solution is to set a seed with set.seed:
library(igraph)
a<- cbind(c(1,2,3,4,5),
c(2,4,1,2,2))
b<- graph.edgelist(a, directed=FALSE)

set.seed(123)
plot(b)

And you'll get this each time you run the code:


text:
Q: replace special characters with null while reading from DB2 table I need to replace special characters like "VT" (Vertical tab), new line, carriage return etc while reading from the DB2 table with null value.
I see that REGEXP_REPLACE function is not working in DB2 or not taking it as a function in the select clause.
Is there any way to replace all special characters in general with null ?

A: The REGEXP functions accept Unicode character classes, and also ranges of Unicode code-points.
You might need to define what you class as a "Special Character". E.g. is £ a special character? What about ?
If you take the Unicode Definition of "Control" characters at the set you want to remove, then you could use this to remove them
REGEXP_REPLACE(your_column, '[\p{Control}]*','')

If you want to remove say all characters apart from e.g. "plain" printable 7-bit ASCII equivalents, you could use this
 REGEXP_EXTRACT(your_column,'[^\u0020-\u007E]+','')

This remove every character that is not between U+0020 SPACE and U+007E TILDE in Unicode. I.e. it will leave everything that is Basic Latin https://en.wikipedia.org/wiki/List_of_Unicode_characters#Basic_Latin  but all other code-points will be removed (including e.g. £, €, À and )

A: try with x'code ascii' (cf: x'OA' for LF), it work for me on DB2 LUW 11.5
db2 => select 'AE'||x'0A'||'MN' from sysibm.sysdummy1;

1
-----
AE
MN

replace LF with : -
db2 => select REGEXP_REPLACE('AE'||x'0A'||'MN',x'0A','-') from sysibm.sysdummy1;

1
-----------
AE-MN