Finding number of strings possible

Question: Consider the six letter alphabet: {A, B, C, D, E, F }.
(a). How many strings of length 15 have exactly 2 A's, 3 B's, 4 D's, and 6 F's?
(b). Of the strings described in part (b), how many have all 2 A's before the 3 B's?
For part (a), I got an answer by using $15 \choose 2$ * $13 \choose 3$ * $10 \choose 4$ *$6 \choose 6$
However, I am stuck on part B.
Answer: So for part (a) we could have gone straight in with a multinomial coeffient.
\begin{eqnarray*}
\binom{15}{2,3,4,6}.
\end{eqnarray*}
To do part (b) group all the $A$'s and $B$'s into one set of size $5$ and we have
\begin{eqnarray*}
\binom{15}{5,4,6}.
\end{eqnarray*}
When an element from this $5$-set is chosen, record an $A$ for the first two choices and $B$ for the others.
Answer: Almost stars and bars: we have 5 bars and 10 stars, say: $$**A*A***B**B*B*$$ But then for each configuration of stars you should put instead of them $4$ $C $ and 6 $D$, so the answer is $${15\choose 5}\cdot {10!\over  4!\cdot 6!}$$

Finding number of strings possible


Alternating Prime Sum

Question: How can one evaluate this sum:
$\sum_{n=1}^\infty (-1)^{n+1}/{p_n}$?
I've tried it for myself but didn't get any satifying answer although it does converge. I also can't find this sum anywhere else and not even Wolfram Alpha knows what to do.
Comment: You are asking for a simple closed form for the solution?  Not sure there is one.  Numerically, there is no problem...I get $.26960$ with an error bounded by about $10^{-5}$.
Comment: This sum is very unlikely to have a "nice" form.
Comment: I wonder is there a method to compute it up to, say, 100 or more digits in reasonable time...
Answer: I just found an upper bound function by myself.
We redefine the summation as below;
$$\sum_{n=1}^{\infty } \frac{(-1)^{n+1}}{p_{n}} = \sum_{n=1}^{\infty } \frac{p_{2n}-p_{2n-1}}{p_{2n}.p_{2n-1}}$$
According to prime number theorem, $\int_{0}^{x} \frac{dt}{logt} \sim π(x)$.
When we take the derivative of both sides we get;
$\frac{1}{log(x)} \sim π'(x)$, where π'(x) represents the derivative of prime counting function according to x. (note that this is only an assumption. Derivatives of two asymptotic functions don't have to be asymptotic again.)
Now, π'(x) is the prime density function around x. For instance, around 100, approximately 1 of every log(100) numbers will be prime. Under this assumption we can say;
$$p_{2n-1} = p_{2n} - log(p_{2n})$$
If we substitute this into the top equation, we get;
$$\sum_{n=1}^{\infty } \frac{(-1)^{n+1}}{p_{n}} = \sum_{n=1}^{\infty } \frac{log(p_{2n})}{p_{2n}.(p_{2n} - log(p_{2n}))}$$
Using Riemann-Stieltjes integral method ($\sum_{p primes}^{N} f(p) \sim \int_{2}^{N} \frac{f(x)}{log(x)}dx$), above summation can be represented an integral like below:
$$\sum_{n=1}^{\infty } \frac{log(p_{2n})}{p_{2n}.(p_{2n} - log(p_{2n}))} \sim \frac{1}{2} \int_{2}^{\infty } \frac{dx}{x(x-logx)}$$
Since the indices increase by two, we wrote 1/2 at the beginning of the integral.
Here we can find a better approach if we add the first few terms manually and express the rest by integral;
$$\sum_{n=1}^{\infty } \frac{(-1)^{n+1}}{p_{n}} \sim \sum_{n=1}^{x } \frac{(-1)^{n+1}}{p_{n}} + O(\int_{x}^{\infty } \frac{dx}{x(x-logx)})$$
"O" is big O notation here. If we consider the result of this sum as a fixed number k,
$$f(x) = \sum_{n=1}^{x } \frac{(-1)^{n+1}}{p_{n}} + \frac{1}{2} \int_{x}^{\infty } \frac{dt}{t(t-logt)}$$ $$\lim_{x\rightarrow \infty } f(x) = k$$
I found the value of k = 0.269606356970929... by summing the values up to 100000000 by hand (I mean computer). And in the table below we compared the values we obtained using this approach with the exact summation k for different x's.

x
f(x)
$|\frac{f(x)-k}{k}|$

3
0.39737469802526604
0.473907004604176

10
0.28225778161237654
0.046925542793532

96
0.27035676966262771
0.002783364235657

1000
0.26958796380480553
0.000068222301321

10070
0.26960698064666632
0.000002313282759

In order to make a good comparison in the table above, we made sure to write the x values that will return even values when we calculate π(x). That's why it's not all round numbers.
With better π'(x) approximations, better bounds can be found.
Comment: what do you mean by $\pi'(x)$? Being a function that is constant between primes and jumping at them, trivially $\pi'(x)=0$ ae so cannot be asymptotic with $1/\log x$ at least as given...
Comment: Of course the function π(x) is not continuous, but when we say π'(x), we assume that this function is continuous and take its derivative. Think of it as if we were taking the derivative of the best function that is asymptotic to π(x). You can find more detail in [here](https://en.wikipedia.org/wiki/Prime_number_theorem#Prime-counting_function_in_terms_of_the_logarithmic_integral)
Comment: Then write it like that so use a different function name, put the error in etc - what you wrote is very handwaving and maybe useful as a heuristic but not more

Alternating Prime Sum


How do I override a core constraint on an entity?

Question: I want to replace one of core's constraints, UserMailUnique, with a custom validator.  How can I do that?
Answer: You can use hook_validation_constraint_alter().
Use the id in the annotation of the Constraint you are trying to override:
function MYMODULE_validation_constraint_alter(array &$definitions) {
  $definitions['UserMailUnique']['class'] = '\\Drupal\\MYMODULE\\Plugin\\Validation\\Constraints\\MyClass';
}

Comment: Yes, this is one way, overriding the plugin class system-wide. The question, however, points more to the entity level where you can override constraints added to entities in hook_entity_type_alter or hook_entity_base_field_info_alter. Then you can use a custom validator with a custom plugin ID defined in the class annotations.


Which player has won the most prize money in professional golf?

Question: I am asking about the combined pool of prize money accumulated over a career. Which player has won the most in professional golf?
Answer: According to the PGA Tour, the answer is, indeed, Tiger Woods.

Tiger Woods,     $120,459,468
Phil Mickelson,  $90,761,239
Jim Furyk,       $71,234,957
Vijay Singh,     $71,216,128
Dustin Johnson,  $61,755,908


The line $DN$ bisects the line segment $AC$ if $AD=BC$.

Question: Consider a circle with diameter $AB$.  A point $D$ on the circle is chosen arbitrarily such that $D\ne A,B$.   A point $C\in AB$ is also chosen arbitrarily such that $C\ne A,B$. Draw $CH$ perpendicular to $AD$ at $H$. The internal angular bisector of $\angle DAB$ intersects the circle at $E$, and intersects $CH$ at $F$.  The line $DF$ intersects circle again at $N$.

Prove that the points $N$, $C$, and $E$  are collinear.  If $AD=BC$, then prove that $DN$ intersects $AB$ at the midpoint $I$ of $AC$.

I proved $N,C,E$  are collinear by cyclic quadrilateral and two congruent triangles. But I have no idea for the second problem.
Comment: It is highly recommended that you attach a picture for a geometry problem.  It attracts more users if you put a picture in your question.
Comment: Thanks for your advice, i fixed it.
Comment: Do not use semicolon ; to separate items within the same sentence.  Usually, a semicolon is used to separate sentences that are connected to the same idea.  And good that you have put a picture, because there is a grammatical error in your original problem statement which can make people interpret the question completely differently.
Comment: And if you could put your proof for the first part of the problem, then it would be best.  It may give some user an idea how to help you with the second part of the problem.
Answer: This is a trigonometric solution, so it is not very nice.
 In this part of my answer, I shall prove the first part of the problem.

Let $\theta:=\angle ABD$, $\alpha:=\angle HFD$, and $\beta:=\angle BEC$.  Write $d$ for the diameter of the circle (i.e., $d=AB$), and $l$ for the length of $BC$.  We see that
$$CH\parallel BD\text{ so that }DH=l\sin(\theta)\,.$$
Now, $\angle DAE=\angle EAB=\dfrac{\pi}{4}-\dfrac{\theta}{2}$.  Hence,
$$\angle AFD=\frac{\pi}{4}+\frac{\theta}{2}+\alpha\,.$$
Since $AD=d\sin(\theta)$, we get
$$\frac{DF}{\sin\left(\frac{\pi}{4}-\frac{\theta}{2}\right)}=\frac{d\sin(\theta)}{\sin\left(\frac{\pi}{4}+\frac{\theta}{2}+\alpha\right)}$$
via the Law of Sines on the triangle $ADF$.  Thus,
$$\sin(\alpha)=\frac{DH}{DF}=\frac{l\sin\left(\frac{\pi}{4}+\frac{\theta}{2}+\alpha\right)}{d\sin\left(\frac{\pi}{4}-\frac{\theta}{2}\right)}\,.\tag{1}$$
Note that $\angle AEB=\dfrac{\pi}{2}$, so
$$BE=d\sin\left(\frac{\pi}{4}-\frac{\theta}{2}\right)\,.$$
Applying the Law of Sines on the triangle $BEC$ yields
$$\frac{l}{\sin(\beta)}=\frac{d\sin\left(\frac{\pi}{4}-\frac{\theta}{2}\right)}{\sin\left(\frac{\pi}{4}+\frac{\theta}{2}+\beta\right)}\,,\tag{2}$$
noting that $\angle EBD=\angle EAD=\dfrac{\pi}{4}-\dfrac{\theta}{2}$.  Consequently,
$$\frac{\sin(\beta)}{\sin\left(\frac{\pi}{4}+\frac{\theta}{2}+\beta\right)}=\frac{l}{d\sin\left(\frac{\pi}{4}-\frac{\theta}{2}\right)}=\frac{\sin(\alpha)}{\sin\left(\frac{\pi}{4}+\frac{\theta}{2}+\alpha\right)}\,,$$
using (1) and (2).  Using the trigonometric identity $\sin(x)\sin(y)=\dfrac{1}{2}\big(\cos(x-y)-\cos(x+y)\big)$, we obtain
$$\cos\left(\frac{\pi}{4}+\frac{\theta}{2}+\alpha-\beta\right)=\cos\left(\frac{\pi}{4}+\frac{\theta}{2}-\alpha+\beta\right)\,.$$
Hence,
$$\sin\left(\frac{\pi}{4}+\frac{\theta}{2}\right)\sin(\alpha-\beta)=0\,.$$
Because $0<\theta<\dfrac{\pi}{2}$, we get $\sin\left(\dfrac{\pi}{4}+\dfrac{\theta}{2}\right)>0$, making $\sin(\alpha-\beta)=0$.  As $\alpha$ and $\beta$ belong to the interval $\left(0,\dfrac{\pi}{2}\right)$, the condition $\sin(\alpha-\beta)=0$ implies that $\alpha=\beta$.
Finally. we see that $\angle AEB=\dfrac{\pi}{2}$, so
$$\angle AEC=\frac{\pi}{2}-\beta=\frac{\pi}{2}-\alpha=\angle ADN=\angle AEN\,.$$
This shows that $E$, $C$, and $N$ are collinear.

I shall now prove the second part of the problem.  In fact, I shall prove a stronger result that $DN$ meets $AB$ at the midpoint $I$ of $AC$ if and only if $AD=BC$.
Let $G$ be the point of intersection between $DN$ and $AB$.  Using the Law of Sines on the triangle $GFC$ noting that $\angle GFC=\alpha$ and $\angle GCF=\theta$, we get
$$GC=GF\left(\frac{\sin(\alpha)}{\sin(\theta)}\right)\,.$$
We have
$$\frac{GF}{GD}=\frac{AG}{AG+AD}=\frac{AG}{AG+d\sin(\theta)}$$
by the Angle Bisector Theorem.  Therefore, $G=I$ if and only if $AG=GC$, which is equivalent to
$$\frac{\sin(\theta)}{\sin(\alpha)}=\frac{GD}{AG+d\sin(\theta)}\,.$$
The Law of Sines on the triangle $AGD$ gives
$$AG=AD\left(\frac{\cos(\alpha)}{\sin(\alpha+\theta)}\right)=\frac{d\sin(\theta)\cos(\alpha)}{\sin(\alpha+\theta)}$$
and
$$GD=AD\left(\frac{\cos(\theta)}{\sin(\alpha+\theta)}\right)=\frac{d\sin(\theta)\cos(\theta)}{\sin(\alpha+\theta)}\,.$$
That is, $G=I$ iff
$$\frac{\sin(\theta)}{\sin(\alpha)}=\frac{\cos(\theta)}{\cos(\alpha)+\sin(\alpha+\theta)}\,.\tag{3}$$
Note that
$$\begin{align}
\cos(\alpha)+\sin(\alpha+\theta)&=\sin\left(\frac{\pi}{2}-\alpha\right)+\sin(\alpha+\theta)
\\&=2\sin\left(\frac{\pi}{4}+\frac{\theta}{2}\right)\cos\left(\frac{\pi}{4}-\frac{\theta}{2}-\alpha\right)
\\&=2\cos\left(\frac{\pi}{4}-\frac{\theta}{2}\right)\sin\left(\frac{\pi}{4}+\frac{\theta}{2}+\alpha\right)\,,
\end{align}$$
where we have implemented the identity $$\sin(x)+\sin(y)=2\sin\left(\dfrac{x+y}{2}\right)\cos\left(\dfrac{x-y}{2}\right)\,.$$
Furthermore, from $\sin(2x)=2\sin(x)\cos(x)$, we have
$$\begin{align}\cos(\theta)&=\sin\left(\frac{\pi}{2}-\theta\right)\\&=2\sin\left(\frac{\pi}{4}-\frac{\theta}{2}\right)\cos\left(\frac{\pi}{4}-\frac{\theta}{2}\right)\,.\end{align}$$
That is, (3) is equivalent to
$$\sin(\alpha)=\sin(\theta)\left(\frac{\sin\left(\frac{\pi}{4}+\frac{\theta}{2}+\alpha\right)}{\sin\left(\frac{\pi}{4}-\frac{\theta}{2}\right)}\right)\,.$$
Combining the last result with (1), we conclude that $G=I$ if and only if $$BC=l=d\sin(\theta)=AD\,.$$
Answer: Reflect $A$ across $D$ to a new point $Q$. Then $\triangle QDE\cong \triangle ECB$ (sas).
Since $$\angle QEC = \angle DEB $$ we see that quadrilateral $ACEQ$ is cyclic, so $$\angle QCE =\angle QAE =  \angle DAE = \angle DNE$$ so $QC||DN$. Now since $D$ halves $AQ$ the line $DI$ is a middle line for triangle $QAC$ and thus it halves $AC$.
Comment: Since $FC||BD$ quadrilateral $ANCF$ is also cyclic: $$\angle ACF = \angle ABD = \angle AND = \angle ANF$$ Now do some angle chase...
Comment: Cool!  Do you have a geometric proof of the first part?  It would be great if you could share.
Comment: How?  This proof assumes $AD=BC$, but the collinearity is true even if $AD\neq BC$.
Comment: Marvelous!  Thanks for your work.


Questions about a linear mapping from $\mathbb{R^4}\rightarrow{}\mathbb{R^4}$

Question: My exam is in a couple hours and I wanted to clear a bit of confusion I have towards symmetric mappings, appreciate any help. Given is that $A:\mathbb{R^4}\rightarrow\mathbb{R^4}$ has, with respect to the standard basis of $\mathbb{R^4}$, the matrix,
$$ \left(\begin{matrix}1&-1&-1&-1\\-1&1&-1&-1\\-1&-1&1&-1\\-1&-1&-1&1\end{matrix}\right) $$
We are to find an orthonormal basis of eigenvectors of A.
Now am thinking because the matrix is symmetric, it has real eigenvalues and those eigenvectors with respect to different eigenvalues are orthogonal, so all I have to do here is find out the respective eigenvectors and apply gram-schmidt to the vectors corresponding to the same eigenvalue? What more can I say about this matrix? Or how can I tackle this problem best. Lastly, Saying that the mapping "with respect to the standard basis of $\mathbb{R^4}$", does that add any useable information to the question? Thanks a lot,
Comment: The method you suggest is fine. As soon as you find multiple (independent) eigenvectors belonging to the same eigenvalue, you can apply Gramm-Schmidt to these. Often you can avoid having to use Gramm-Schmidt by just chosing your eigenvectors with a bit more care. For example, if $\lambda$ is an eigenvalue with multiplicity $2$ and $v$ is already an eigenvector corresponding to $\lambda$, you can find a non-zero vector $w$ such that $w\perp v$ and $(A-\lambda I)w=0$. Clearly $w$ is an eigenvector corresponding to $\lambda$ and $w$ is already perpendicular to $v$. Often this is more efficient.
Comment: Note that $(1,1,1,1)$ is an eigenvector with eigenvalue $-2$. Note also that $A-2I$ has rank one, so nullity three, so it's easy to find three independent eigenvectors for the eigenvalue $2$.
Comment: The phrase "with respect to the standard basis..." adds no useable information. All you really need to know is that , in the space of 4-element coluln-vectors, multiplying on the left  by a fixed 4x4 matrix defines a linear transformation, There is a bad attitude, derived from physics, that every thing you do has to be done in terms of a basis but then you have to say immediately what happens if you change that basis. The classical definition of "tensor product," which leads to a 'debauche d'indices' is a particularly bad example.
Answer: Your general approach is good, but in this case you don't need to use Gram-Schmidt at all. An orthonormal eigenbasis can be found by inspection.
First, as Gerry Myerson noted in a comment, observe that all of the row sums are equal, so that $(1,1,1,1)^T$ is an eigenvector with eigenvalue $-2$. $A+2I$ has rank one, so the only other eigenvalue is $0$. So, you just have to find three pairwise orthogonal vectors that are orthogonal to $(1,1,1,1)^T$ and then normalize them all. Two fairly obvious choices are $(1,-1,0,0)^T$ and $(0,0,1,-1)^T$. If you can't spot $(-1,-1,1,1)^T$ as a third orthogonal vector, you can at this stage use row-reduction to find a null vector of $$\begin{bmatrix}1&1&1&1\\1&-1&0&0\\0&0&1&-1\end{bmatrix},$$ which I think is still less work than applying Gram-Schmidt to complete the basis.
Knowing that the matrix is expressed relative to the standard basis is important for determining orthogonality. Implicit in the problem is that you're using the standard Euclidean inner product, but its expression in terms of coordinates is basis-dependent. In particular, it only corresponds to the dot product of coordinate vectors when the basis is orthonormal, which the standard basis is.


Are suvey responses of ranking significantly different from mean ranking?

Question: I'm a stats dummy, so please use small words.  (-:
This might not be a valid test, so I'm sure you'll let me know if that's the case.
I have some survey responses in which the responses are rankings between 1 and 10.  I have a frequency for each ranking (2 1's, 3 2's, 2 3's, 10 4's and so on).
Intuitively, it looks like a lot of these responses fall in the middle and a few are on the tails, and I want to see if the reponses in the middle ranges are significantly different than the mean.  Is this a valid thing to do?  If so, whats the best (simple) test I can do?  I tried chi-squred, but a few of my rating categories have fewer than 5 responses, so is that valid?
Comment: What do you mean by "see if the responses in the middle ranges are significantly different than the mean"?  This needs to be clarified before this question can be answered.
Answer: First you need to decide whether to treat the responses as if they are at the interval or ordinal level of measurement.  "Interval" would assume that the difference between 1 and 2 is the same as the difference between 2 and 3 (and so on all the way to the difference between 9 and 10).  "Ordinal" would relax that assumption.
With data treated as interval, you could conduct a T-test to compare the mean response against some hypothesized mean, such as 5.5.
With ordinal data, as you suggested you could run a Chi-square test, but expected cell counts fewer than 5 (not observed counts; a Chi-square primer will explain the difference)  would pose problems.  So you might need to collapse your categories into, say, 1 & 2, 3 & 4, etc.  Then the trick would be to test your distribution against some hypothesized distribution--what would that be?  To be true to (I believe) your idea of testing observed responses against hypothesized responses that centered on 5.5, perhaps you'd want to designate, using the same N, a normal-ish distribution that had high percentages of 5s & 6s, fewer of 3s & 4s and 7s & 8s, and fewer still of 1s & 2s and 9s & 10s.
Comment: Ah, now I'm tracking.  Thanks so much!  So, I added in a normal distribution and did the chi-squared test with that (I had just been using the mean).  It makes so much more sense now!  I did do the t-test first, but I felt like it didn't quite get at what I wanted to express, since it's just showing if the mean is different.  I want to show that people overall responded with more positive or negative rankings than, say, asking people on the street.  Do you think comparing my response distribution to a normdist is reasonable for this? (It's a survey my company sent out to employees).
Comment: It's important to look closely at your expectation of the responses from "people on the street."  On what are your expectations based? Also, I'm having trouble reconciling "a lot of these responses fall in the middle" with "[my sample] overall responded with more positive or negative rankings than [others did]."


Create nested stored procedure call to send a uniform result set to Entity Framework

Question: I am working on converting a web forms project to an ASP.NET MVC 4 project.
In this project we the .NET team are not allowed to modify the existing stored procedures, at max we are allowed to write a wrapper for this stored procedure. I.e. We can create an another stored procedure which calls the existing ones.
The existing stored procedure is of the following type
condition 1
  Select A,B,C,D from Table
condition 2
  Select ErrorCode as 100, ErrorMessage as 'Correct that'
condition 3
  Select ErrorCode as 101, ErrorMessage as 'Correct this'
condition 4
  Select ErrorCode as 102, ErrorMessage as 'Not found' from Table

And I am using Entity Framework in this project which requires a complex type to be pre-mapped so for the above type of stored procedure I have declared a complex type as
Complex Type :- SomeComplexType

    string A;
    string B;
    string C;
    string D;

    int ErrorCode;
    string ErrorMessage;

Now my problem is lack of SQL knowledge and syntax, I have been searching a lot on the google and SO, but was not able to find anything on this.
I want to know how to create a wrapper around this existing stored procedure, some thing like the one below.
condition 1
  Select A,B,C,D,ErrorCode as NULL, ErrorMessage as NULL from Table
condition 2
  Select A,B,C,D,ErrorCode as 100, ErrorMessage as 'Correct that' from Table
condition 3
  Select A,B,C,D,ErrorCode as 101, ErrorMessage as 'Correct this' from Table
condition 4
  Select A as NULL, B as NULL, C as NULL, D as NULL,ErrorCode as 102, ErrorMessage as 'Not found' from Table

So if I am able to send data from SQL like shown above I can then handle it easily using Entity Framework's function import and complex type.
How do I check (in the wrapper stored procedure) what result set is returned (from the existing stored procedure)?
Please guide me with ideas on this. Thanks
Answer: edit:
old post was not helping, adding some more info just to help in the search:
ok, I googled a bit and I really can't find any way to solve your problem; though i found some useful links:
How to Share Data between Stored Procedures
and
Insert results of a stored procedure into a temporary table
I was hoping that the second one would've been useful but when i tried the OPENROWSET i got this error:

The metadata could not be determined because the statement 'SELECT
  '1','2','3'' in procedure 'testSP' is not compatible with the
  statement 'SELECT 100,200' in procedure 'testSP'.

so i suppose it's not the right way.
now, the only ideas I have left are:

Rewrite the old SP instead of building a wrapper around
Can you find a way to determine the returned resultset from the input values? if that is possible you can just use if / else to choose the appropriate columns for the temp table where you will insert the data and then build the complex datatype

I'm sorry that i couldn't help any better
edit (again):
the first link says (at the CLR chapter):

As a recap, here are the main situations where INSERT-EXEC fails you,
  and you would want to turn to the CLR:
The called procedure returns several result sets with different
  structures. This is true for many system procedures in SQL Server.

so i suggest you to read this chapter, maybe it will be useful
Comment: yea I am doing it somewhat like this only, But how do I check what result set is returned ?
Comment: lol... the answer says `The only time when it really becomes difficult (and maybe impossible, I've never seen it done) is when the stored procedure returns multiple recordsets (not multiple records) and the recordsets have different fields.` which is exactly my case !
Comment: changed my answer, I hope it helps at least a little bit
Comment: Thanks for all info, This didn't help though, but I am up-voting your answer for your efforts.


DFA Rejection State

Question: I'm being asked to construct a DFA for the language over $\{0,1\}$ such that each string of five consecutive symbols contain at least two zeroes. In my construction, it seems to me that it would make it easier if I could simply lead invalid strings to a "rejection state".
My question is whether such a "rejection state" is accepted convention: I am imagining something like this:

Where $q_3$ is the final, or accepting state, and $\emptyset$ is simply a state that denotes that the DFA rejects the string. Is such a "rejecting state" acceptable to write? Is it conventional? Any other thoughts on the matter?
Answer: DFA's don't usually have "reject" states.  But you can model these by so-called "sink" states: states which, once entered, you can never leave. What transitions from your $\varnothing$ state can you think of that will turn it into a sink?
Comment: Are you saying that the DFA simply 'dies', i.e. has to reject the input, if it arrives at a non-accepting state, out of which there are no transitions?
Comment: For example, say the DFA arrives at some $q_n$, which has only one outgoing transition on a symbol $a$. Suppose the DFA then reads some symbol $x \neq a$. The DFA then rejects the input, correct? Suppose the DFA reads $x \neq a$, and after that, it reads an $a$. The DFA then still rejects the input, right?
Comment: @Newb: DFAs are defined so that the transition function is total: for _every_ state $q$ and _every_ input letter $x$ the value $\delta (q,x)$ is defined to be a single state. But there is no demand that $\delta(q,x)$ is different from $q$.  (NFAs, however, can have "death states": since the range of the transition function is the family of _subsets_ (not necessarily nonempty) of the set of states.)
Comment: Arthur, please answer my questions from my earlier comment "For example, say (...) input, right?": they are quite important to me. I must make sure that I've understood this correctly. Thank You!
Comment: @Newb: I think my above comment addresses this: by definition the transition function of a DFA _must_ be total: defined for _every_ state and _every_ input symbol. What you are describing is _not_ a DFA (although the idea you have can be modeled by a DFA using these sink states).
Comment: @Newb: Arthur really has answered your question in the earlier comment, but I'll make it very explicit: no, that's not right, because what you've described is not a DFA. (It's actually a kind of NFA.) A DFA must by definition have a transition out of each state for each symbol of the input alphabet. Your picture does not show a DFA, because the automaton that it shows has no $a$-transition and no $b$-transition out of state $\varnothing$ or out of state $q_3$.

DFA Rejection State


Smallest n>0 such that $2001^n-1\:%$ is divisible by $\:2^{2002}$

Question: Smallest n>0 such that $2001^n-1\:%$ is divisible by $\:2^{2002}$, can you give me some hints as to what theorem/algorithm to use to approach this problem?
Comment: See my answer here: http://math.stackexchange.com/questions/2021531/find-min-natural-number-n-so-that-22002-divides-2001n-1/2021720#2021720
Comment: Well, $n=0$ is pretty small.
Comment: :( n has to be from the set of natural numbers
Answer: $2001$ is coprime with $2^{2002}$. By Euler's theorem, the smallest $n$ is a divisor of $\phi(2^{2002})=2^{2001}$.
So, one algorithm is to test for all $n=2^k$ with $k\le 2001$. This is just repeated squaring followed by reduction mod $2^{2002}$, which is not very hard to do: just repeated division by $2$.
You'll have to use arbitrary precision numbers to implement this.


Why does getComputedStyle not return display:none for an element hidden by a parent?

Question: According to this question page and the accepted answer here, the right way to get inherited CSS values via Javascript is getComputedStyle().  However, that does not work in the following example:
<!DOCTYPE html>

    <form id="iterateThroughMe">

<input name="myNum" type="number" />

<input name="myOtherNum" type="number" />

        <input name="myText" type="text" />

            <input name="hiddenElement" type="number" />

    </form>

Saved and opened in a browser, the following is visible on the console:
visible element:  <input name="myNum" type="number"> has display style inline-block
visible element:  <input name="myOtherNum" type="number"> has display style inline-block
visible element:  <input name="myText" type="text"> has display style inline-block
invisible element:  <input name="hiddenElement" type="number"> has display style inline-block

There is a specific way to access hidden/visible status in jQuery, noted here, which works in the example above but is not always appropriate.  Why does getComputedStyle not distinguish between hidden and non-hidden elements, producing inline-block on all four lines instead of none at the end of the output?
Answer: The element isn't rendered because it is contained within something that is display: none, not because it has inherited the value none for that property.


Django: how do you deal with queries that can not scale?

Question: In my code, I have a few queries that are not scalable at all.
For example, take a look at this code:
class OrderQuerySet(query.QuerySet):
    def for_day(self, day: date):
        """ Return all orders that concerns the given service day """

        day_order_pks = [order.pk for order in self.all()
                         if localdate(order.service.start) == day]
        return self.filter(pk__in=day_order_pks)

At the beginning, it perfectly worked.
The problem is, when order amount increase, the performance seems to decreases in a linear way, which makes senses because all orders need to be tested each time. Having 1000 new orders every day, it's obvious my system will not be usable anymore in a few time!
Usually, how do you deal with this kind of problem in Django?
I mean, sometimes I can find a trick to write a better query, using Django ORM only. But sometimes, to get what I want, I seems to be forced to create my queryset this way, using Python and a for loop.
Comment: Why do you think you are forced to loop in Python? That should rarely or never be the case.
Comment: What is `localdate(..)` doing here? Typicaly such filters can be moved to the database side, making it way more efficient.
Answer: Please don't enumerate over .all() unless you absolutely have to. It is more efficient to do filtering at the database side. Given localdate(..) does not do much, except extracting the date from a datetime, you can filter with:
class OrderQuerySet(query.QuerySet):

    def for_day(self, day: date):
        """ Return all orders that concerns the given service day """
        return self.filter(service__start__date=day)
If localdate(..) is more advanced, you can still try to do most of the work at the database side. For example by filtering the queryset down to orders that are within for example 24 hours of the given date, and then do advanced filtering at the Python/Django side. But the idea is to do as much as possible at the database side (unless you make some exotic queries that do not scale well at the database, but that is quite rare).
Comment: @DavidD.: I think it can pay off to make queryset variants, since filtering, annotating, joining, etc. at database are typically more efficient. In fact one of the main tasks of a database is to filter, join, etc. Note that a queryset is iterable, so some of your methods might already work on querysets.
Comment: You answer makes lots of sense. You and @Daniel Roseman are telling that I can (almost) always do filtering at the database level, instead of looping in Python. This means I probably have a lack of knowledge about how to make some advanced filtering in Django. In addition, another of my problem is that lots of my methods take a Python List of Django objects in parameter, instead of a queryset.
Comment: I'll do it thanks guys. To be sure, am I on the right way doing this for example? https://www.dropbox.com/s/sykfrqt3f2vqkz6/Screenshot%202019-01-22%2013.24.32.png?dl=0


How to make Java Anagrams from txt

Question: I have Main class in Java. And need to write class Anagrams.
Main is:
public class Main {
    public static void main(String[] args) throws FileNotFoundException {

           String home = System.getProperty("user.home");
           String allWords = home + "/allwords.txt";

           Anagrams an = new Anagrams(allWords);

           for(List<String> wlist : an.getSortedByAnQty()) {
                 System.out.println(wlist);
           }

           System.out.println("************************");

           Scanner scan = new Scanner(new File(home, "wordsToFind.txt"));

           while(scan.hasNext()) {
                 System.out.println(an.getAnagramsFor(scan.next()));
           }

           scan.close();
    }
}

For example:

File allwords.txt:
andes danes deans evil gals lags levi live sedan
  slag streets testers uprising veil vile
wordsToFind.txt:
evil streets uprising

Then in the end we'll have:

[evil, levi, live, veil, vile]
[andes, danes, deans, sedan]
[gals, lags, slag]
[streets, testers]
[uprising]

evil: [levi, live, veil, vile]
streets: [testers]
uprising: []

I created class Anagrams and wrote a method that checks if words are anagrams. The metod returns boolen:
public static boolean IsAnagrams(String str1, String str2) {
        char word1[] = str1.toLowerCase().replaceAll("\\W","").toCharArray();
        char word2[] = str2.toLowerCase().replaceAll("\\W","").toCharArray();
        Arrays.sort(word1);
        Arrays.sort(word2);
        return (Arrays.equals(word1, word2));

    }

But I don't understand what to do now.
I have to write methods:

getSortedByAnQty() -- return list of anagrams
String getAnagramsFor(String word) -- return list of anagrams for words from wordsToFind.txt

How can I do it?
Comment: for getAnagramsFor(String word) you could build a Map> when you read allWords.txt.  Use the sorted version of each word as the key.  When you want to find the anagrams for a word just sort the letters and get the List from the map.
Comment: What is getSortedByAnQty() supposed to do?  Can you give an example?
Comment: getSortedByAnQty() takes words from  allwords.txt and find anagrams. It was in first part of example. Like that: [evil, levi, live, veil, vile], [andes, danes, deans, sedan]. Method must return a list of anagrams.
Comment: In my understanding you have to produce every permutation of the "available" letters to get all anagrams for a word or sentence. I conclude from your sample "evil: [levi, live, veil, vile]" that you only want to accept permutations that are valid words, so you will need a dictionary.
Answer: Given the following code you get all character permutations of a word. If you flesh out isValidWord() you can reduce that set to words in your dictionary (allWords.txt?). The method builds up the permutations from the available characters so there is no need to check whether a permutation is an anagram.
public boolean isValidWord(String word) {
    return true; // return you dictionary check here
}

public Set<String> getAnagramsFor(String word, String letters) {
    Set<String> set = new HashSet<>(); // no duplicates because of a letter occuring more than once
    if (letters.isEmpty()) {
        if (isValidWord(word)) {
            set.add(word);
        }
    } else {
        for (int i = 0; i < letters.length(); i++) {
            String restOfLetters = letters.substring(0, i) + letters.substring(i + 1);
            set.addAll(getAnagramsFor(word + letters.charAt(i), restOfLetters));
        }
    }
    return set;
}

public void run() {
    System.out.println(getAnagramsFor("", "tea"));
    System.out.println(getAnagramsFor("", "foo"));
}

These test calls
    System.out.println(getAnagramsFor("", "tea"));
    System.out.println(getAnagramsFor("", "foo"));

print
[tea, aet, eta, ate, tae, eat]
[foo, oof, ofo]

Hope this helps.
EDIT: As a second solution and regarding your restricted dictionary you can walk through your dictionary and check for every word whether it is an anagram of your word. In this code are both solutions, BTW here the original word is no longer part of the result set:
private List<String> wordsToFind = Arrays.asList(new String[] { "evil", "streets", "uprising" });

private List<String> validWords = Arrays.asList(new String[] { "andes", "danes", "deans", "evil", "gals",
        "lags", "levi", "live", "sedan", "slag", "streets", "testers", "uprising", "veil", "vile" });

public boolean isValidWord(String word) {
    return validWords.contains(word);
}

public Set<String> getAnagramsFor(String word, String letters) {
    Set<String> set = new HashSet<>(); // no duplicates because of a letter occuring more than once
    if (letters.isEmpty()) {
        if (isValidWord(word)) {
            set.add(word);
        }
    } else {
        for (int i = 0; i < letters.length(); i++) {
            String restOfLetters = letters.substring(0, i) + letters.substring(i + 1);
            set.addAll(getAnagramsFor(word + letters.charAt(i), restOfLetters));
        }
    }
    return set;
}

public Set<String> getAnagramsFor1(String word) {
    Set<String> anagrams = getAnagramsFor("", word);
    anagrams.remove(word); // remove original word from the result set
    return anagrams;
}

public boolean isAnagram(String str1, String str2) {
    char word1[] = str1.toLowerCase().replaceAll("\\W", "").toCharArray();
    char word2[] = str2.toLowerCase().replaceAll("\\W", "").toCharArray();
    Arrays.sort(word1);
    Arrays.sort(word2);
    return (Arrays.equals(word1, word2));
}

public Set<String> getAnagramsFor2(String word) {
    Set<String> anagrams = new HashSet<>();
    for (String potentialAnagram : validWords) {
        if (!word.equals(potentialAnagram) && isAnagram(potentialAnagram, word)) {
            anagrams.add(potentialAnagram);
        }
    }
    return anagrams;
}

This test code
    for (String wordToFind : wordsToFind) {
        System.out.println(wordToFind + ": " + getAnagramsFor1(wordToFind));
        System.out.println(wordToFind + ": " + getAnagramsFor2(wordToFind));
    }

brings
evil: [veil, vile, levi, live]
evil: [veil, vile, levi, live]
streets: [testers]
streets: [testers]
uprising: []
uprising: []

How to make Java Anagrams from txt


How to move images in kinetic?

Question: I'm trying to move an image but I can't
...
  var imageObj = new Image();
      imageObj.onload = function() {
        var yoda = new Kinetic.Image({
          x: 200,
          y: 50,
          image: imageObj,
          width: 106,
          height: 118
        });
....
  // event button - move image;

  document.getElementById('show').addEventListener('click', function() {
      imageObj.move(0,5);
  }, false);

Answer: A few bugs:

be be sure to draw the layer so your changes are displayed
the element you want to move is yoda, not imageObj: yoda.move(0,5)
the yoda object must be declared outside imageObj.onload so its in scope later

Here's code and a Fiddle:  http://jsfiddle.net/m1erickson/T2pfZ/
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Prototype</title>

    <button id="show">Move!</button>

Comment: don't work  document.getElementById('show').addEventListener('click', function() {
              imageObj.move(10,10);
                layer.draw();
        }, false);

How to move images in kinetic?


Least squares method (curve fit): linear vs exponential function

Question: When we say least square method for linear functions, then we mean that for each point in our plot there is a corresponding square which is just touches the linear function (see picture below)

My question is: Is this the same for an exponential function? I mean, if we had a graph with exponential slope, would we also in theory make squares as on the picture above?
Comment: The typical way to fit an exponential function $y=ab^x$ is to take logs of both sides to get $\log y=\log a+b\log x$. One then does linear least squares on the variables $(\log x,\log y)$ rather than $(x,y)$. In your terms, this amounts to doing a log-log plot of $(x,y)$ and then put on the squares.
Answer: Squared residuals measure the distance between your data set and a data set with the same x coordinates modeled perfectly by your regression line/curve (as vectors in n-dimensional space).
That is to say, the mathematics of least squares works out very nicely and can be used for all sorts of types of regression: linear, quadratic, exponential, logarithmic, sinusoidal, etc. For any sort of collection of curves you can ask "what curve will give the smallest total area of these squares between the data and my curve?"
This will give you different answers than Semiclassical's suggestion in the comments of taking logs and doing a linear least squares. Taking logs will make it more important for your regression exponential to do well for values close to 0 (since their logs will be farther apart). Depending on your circumstances, this may actually be preferred.


Why isn't for /f working in this batch script?

Question: I'm trying to capture the output of a command in a batch script with for /f. Here is my code:
set RUNPS="powershell -NoProfile -ExecutionPolicy Bypass -Command"
set OLDPATHPS="[Environment]::GetEnvironmentVariable('PATH', 'User')"
for /f %%i in ('%RUNPS% %OLDPATHPS%') do ^
    set OLDPATH=%%i

When I run the script from the console, here is the output:
C:\Users\James\Downloads>testscript
' ' is not recognized as an internal or external command,
operable program or batch file.
' ' is not recognized as an internal or external command,
operable program or batch file.
' ' is not recognized as an internal or external command,
operable program or batch file.
...

On the other hand, when I run the command normally I get
C:\Users\James\Downloads>powershell -NoProfile -ExecutionPolicy Bypass -Command "[Environment]::GetEnvironmentVariable('PATH', 'User')"
C:\Users\James\.dnx\runtimes\dnx-clr-win-x126.96.36.199-beta6\bin;C:\Users\James\.dnx\bin;...

Why does this happen with for /f and what can I do to fix it?

EDIT: Thought it may have been an issue with the single quotes being unescaped. Tried using usebackq:
for /f usebackq %%i in (`%RUNPS% %OLDPATHPS%`) do ^
    set OLDPATH=%%i

But it looks like I'm getting the same output.
Answer: Why would you escape the linebreak after do? You should use:
set RUNPS="powershell -NoProfile -ExecutionPolicy Bypass -Command"
set OLDPATHPS="[Environment]::GetEnvironmentVariable('PATH', 'User')"
for /f %%i in ('%RUNPS% %OLDPATHPS%') do (
set OLDPATH=%%i
)

Note that if you want to use variables like OLDPATH inside a for loop (after the do) you have to use setlocal EnableDelayedExpansion at the top of your script, and use ! instead of % for variables inside the loop
EDIT: your powershell currently has this exception:

-Command : The term '-Command' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a
  path was included, verify that the path is correct and try again.
At line:1 char:1

-Command [Environment]::GetEnvironmentVariable('PATH', 'User')
~~~~~~~~

CategoryInfo          : ObjectNotFound: (-Command:String) [], CommandNot
  FoundException
FullyQualifiedErrorId : CommandNotFoundException
Comment: Thanks! It looks like your suggestion got rid of that error, but now `OLDPATH` is being set to a `+` for some reason. Could you please help?
Comment: Your powershell command has an exception. Look at my updated answer
Comment: Using the syntax `set "OLDPATH=%%i"` avoids many troubles with special characters...
Comment: @DennisvanGils Hmm... it seems to be failing even when I remove `-Command`.
Comment: @aschipfl Thanks for the tip!
Comment: If I may ask, why do you use powershell to get an environment variable? Is it part of the assignment, because batch can access environment variables itself. For a list of all of them, type `SET` in cmd, because I don't think User exists
Comment: @DennisvanGils I'm trying to append a string to PATH for only the current user via `[Environment]::GetEnvironmentVariable` and `SetEnvironmentVariable`, and unfortunately it looks like PowerShell is the only way to do it.
Comment: In that case I suggest creating a new question with the powershell tag where you ask for the correct code to do that.
Answer: Try this:
@ECHO OFF
SETLOCAL
set "RUNPS=powershell -NoProfile -ExecutionPolicy Bypass -Command"
set "OLDPATHPS=[Environment]::GetEnvironmentVariable('PATH', 'User')"
for /f "delims=" %%i in ('%RUNPS% "%OLDPATHPS%"') DO (
    set OLDPATH=%%i
)
SET o

GOTO :EOF

The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a can safely be used "quoteless".
The required syntax for the command is
powershell -NoProfile -ExecutionPolicy Bypass -Command "[Environment]::GetEnvironmentVariable('PATH', 'User')"

not
"powershell -NoProfile -ExecutionPolicy Bypass -Command" "[Environment]::GetEnvironmentVariable('PATH', 'User')"

The ' ' is not recognized ... message appears to be the consequence of attempting to use the caret. It appears to be invalid as you've used it - I've never seen that ateempted before.
Note that you need the "delims=" to ensure that a user-path-containing-spaces is not tokenised.


Firebug disabled in WebDriver after adding to profile

Question: I can't seem to figure out why my Firebug extension shows that its disabled when I try to click on it within the Firefox WebDriver.
Here's what my code looks like, I got some of the code from this SO answer:
private final String firefoxExtPath = "/Users/[NAME]/Library/Application Support/Firefox/Profiles/4izeq9he.default/extensions/";
private final String firebugPath = firefoxExtPath + "firstname.lastname@example.com";
private final String firepathPath = firefoxExtPath + "firstname.lastname@example.com";

private WebDriver dummy;
private WebDriver driver;
...

@BeforeClass
public void addFirefoxExt() {
    // Add extensions to FirefoxDriver
    FirefoxProfile profile = new FirefoxProfile();
    try {
        profile.addExtension(new File(firebugPath));
        profile.addExtension(new File(firepathPath));

        profile.setPreference("extensions.firebug.currentVersion", "1.11.1");
        profile.setPreference("extensions.firebug.onByDefault", true);
        profile.setPreference("extensions.firebug.defaultPanelName", "net");
        profile.setPreference("extensions.firebug.net.enableSites", true);
    } catch (IOException e) {
        e.printStackTrace();
    }

    dummy = new FirefoxDriver(profile);
    driver = new FirefoxDriver(profile);
}

@BeforeClass
public void setup() {
    dummy.get(BASE_URL);
    dummy.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    ...
}

Answer: That's what i could got from https://code.google.com/p/selenium/wiki/FirefoxDriver. They worked well.
Running with firebug
Download the firebug xpi file from mozilla and start the profile as follows:

File file = new File("firebug-1.8.1.xpi");
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.addExtension(file);
firefoxProfile.setPreference("extensions.firebug.currentVersion", "1.8.1");
// Avoid startup screen

WebDriver driver = new FirefoxDriver(firefoxProfile);


What matters the most when it comes to being successful in Formula One?

Question: I've been watching Formula One for the last 14 years. I have seen many drivers who came from the Driver Academies of Mercedes or Ferrari, with championship wins in GP3 and GP2. But when they enter into F1 they never ever win a race, let alone the championship.
Nico Hulkenburg is one such example. I enjoyed his driving, his radio messages, his style, but he never succeeded regularly. Jarno Trulli and Felipe Massa are other examples.
I think Mark Webber was an exceptional driver. But his car failed more than Vettel's did. Juan Pablo Montoya was absolutely fantastic but again, he never won the F1 Championship.
How does this whole thing work?
Should one be at the right place at the right time?
Or back-up?
Or is your hard work not the only thing?
Personal attributes, corporate inclination, political stand, nationality, media coverage?
It cannot be money. Lewis Hamilton is from a very humble background and he has won the F1 Championship many times. Timo Glock was his rival in GP2 but in F1, Lewis overshadowed him.
I checked the list of drivers who competed in the 2006 GP2 Series when Lewis won. Out of 27 drivers, only Lewis and Timo Glock made it to F1.
So what matters the most in getting success in F1?
Comment: There's the other side of this coin (people with talent that don't get to F1), like if your question were reversed. Consider Oscar Piastri: he won the F3 championship as a rookie in 2020, and he is about to win the F2 championship as a rookie again this year. We could be sure he will drive a F1 next year, couldn't we? He won't. And he might never will.
Answer: Racing isn't cheap. To go racing you need money. As a result, making it to F1 and many other motorsport categories isn't exclusively decided on success and talent.
Financial backing is also a major contributor in landing a seat in F1 by bringing personal sponsorship or money to a team with you, meaning we get drivers who are perceived to be so-called "pay drivers".  (And not all pay drivers are bad.)
This issue starts long before F1. Getting through the junior categories takes millions of pounds from karting to F1. The estimated costs for F1's main feeder series, which has been F2/GP2/F3000 for several years now, is estimated in the millions per season. Formula Renault 3.5, which Vettel came through and the old F3, which Verstappen came through are not far behind in terms of cost.
You mentioned Hamilton. He is from relatively humble beginnings, the stories of his father Anthony Hamilton working 3 or 4 jobs to support his karting are the stuff of legend.
In Hamilton's case, his talent was spotted and as a result, he was signed up to the McLaren Junior program, which supported him on and off during in various junior single-seaters, including GP2, before they promoted him to the F1 team, where he would go on to become the single most successful driver of all time.
Without the financial support from McLaren and the luck to be signed up by them, Hamilton likely would never have graduated from karts.
Vettel was also from a relatively humble background. In Vettel's case, he was part of the BMW and RedBull junior programs before being promoted to F1 and enjoying great success in F1.
Success in F1 requires a lot of things. The main 3 are money, luck and talent.
You need all 3 to succeed, but you don't need all 3 to land a F1 seat.
There have been many drivers over the years who either never made it to F1 or didn't succeed in F1 because they only possessed 2 of these attributes.
The one thing that all successful F1 drivers have had, including those who graduated from F2/GP2/F3000 is that they poses all 3 attributes: Money, luck and a massive amount of talent.


Read xml with namespace in IE, FF and chrome

Question: I have the below xml response with namespace.
<?xml version="1.0"?>
<response status="200">
  <ns3:op xmlns="http://xxx.com/details/"
              xmlns:ns2="http://xxx.com/mgmt/"
              xmlns:ns3="http://xxx.com/list/">
    <ns2:ntfs count="140">
      <ns2:ntf>
        <ns2:Nid>4687807</ns2:Nid>
      </ns2:ntf>
    </ns2:ntfs>
  </ns3:op>
</response>

I need to parse this and get the Nid value for each row. I tried using getElementsByTagName(ns3:op) but it doesnt work in safari.
Also tried using
xmlDoc.documentElement.selectNodes("/response/op/ntfs");
But it is not working in FF.
is there any way where i can read the response independent of namespace and browser.
Hi,
My output xml might change and the elements may or may not have namespace prefixes.
So i need to parse the xml irrespective of the namespace.
How can i achieve this?
This is little urgent to me , any pointers would be grateful.
Answer: With namespaces you need to use getElementsByTagNameNS with the namespace URI
document.getElementsByTagNameNS('http://xxx.com/list/', 'op')

However this apparently doesn't work in IE earlier than 9. A commonly recommended cross browser solution is Sarissa, a JavaScript library which implements the XPath approach in a way that works on more browsers:
var xmlDoc = new DOMParser().parseFromString(....);
xmlDoc.setProperty("SelectionNamespaces", 'xmlns:ns3="http://xxx.com/list/"');
xmlDoc.setProperty("SelectionLanguage", "XPath");
var op = xmlDoc.selectSingleNode("/response/ns3:op");

Comment: @ Ian ..Thanks for the reply. But getElementsByTagNameNS does not work in IE 8. Is there any way the code works in all browsers like IE , FF and chrome...
Comment: @later2013 I've done a bit more digging and edited my answer with another suggestion.


In a semiprime ring $R$, $Ann_R(S)_r=Ann_R(S)_l$ whenever $S$ is an ideal

Question: Let $R$ be a ring and $S$ be an ideal of $R$.
Let $Ann_R(S)_r=\{a\in R | Sa=0\}$ and $Ann_R(S)_l=\{a\in R | aS=0\}$ denote the right annihilator and the left annihilator of $S$ in $R$, respectively.
If $R$ is a semiprime ring (i.e Given an ideal $S$, a semiprime ring is one for which $S^n=0$ implies $S=0$ for any positive $n$), then $Ann_R(S)_r=Ann_R(S)_l$.
Answer: $A=Ann_R(S)_rS$ is an ideal.
$A^2=\{0\}$.
If $R$ is semiprime, this means $A=\{0\}$.
This means $Ann_R(S)_r\subseteq Ann_R(S)_l$.
By symmetry, the reverse containment holds.
QED.

One can also compare this to the obvious element-wise version that holds for noncommutative reduced rings: if $xy=0$ then $yx=0$.  Proof: $(yx)^2=0$, so $yx=0$.
Comment: Is $I$ an arbitrary ideal?
Comment: @Ninja Sorry, you're right, I was thinking $S$. There is no need for "let". I am just making an assertion.
Comment: "Let" was needed to make a edit containing $6$ characters.
Comment: @Ninja well, FFR don't make edits that necessitate corrections later just to dodge character limits. It's much better just to leave it as a suggestion in the comments in that case.


Pinterest for Lightbox and/or Colorbox

Question: Does anyone know if there is a project going on to add Pinterest to Lightbox or Colorbox?
I've been searching for some way of integrating quick share on Pinterest from my website and can't find any modules that work well. Pin It doesn't even work as far as I can tell and Service Links is difficult to figure out.
Plus the solution for Pinning isn't really the same user experience as tweeting a page or sharing on FB. An overlay on an image in lightbox or colorbox would be huge.
I'm just looking for some decent Pinterest solution for Drupal and am surprised I can't find anything.
Answer: I used the hook THEME_image_formatter to accomplish this.  It would be fairly easy to create a module to do this I just haven't had the time.  Anyway here is what I did.
function THEME_image_formatter($variables) {
  $item = $variables['item'];
  $image = array(
    'path' => $item['uri'],
  );

  if (array_key_exists('alt', $item)) {
    $image['alt'] = $item['alt'];
  }

  if (isset($item['attributes'])) {
    $image['attributes'] = $item['attributes'];
  }

  if (isset($item['width']) && isset($item['height'])) {
    $image['width'] = $item['width'];
    $image['height'] = $item['height'];
  }

  // Do not output an empty 'title' attribute.
  if (isset($item['title']) && drupal_strlen($item['title']) > 0) {
    $image['title'] = $item['title'];
  }

  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = '';
    // I targeted the blog post image style to add to all blog photos.
    if($image['style_name'] == 'blog_post') {
      $output .= '
';

      $media = urlencode(file_create_url($item['uri']));
      $title = variable_get('site_name', '') .' - '. str_replace('+', '%2B', $variables['item']['title']);
      $path = $variables['item']['path'];

      $output .= '

';
      $output .= '';
      $output .= variable_get('site_name', '') .'
'. $variables['item']['title'];
      $output .= '

';
    }
    $output .= theme('image_style', $image);
    if($image['style_name'] == 'blog_post') {
      $output .= '
';
    }
  }
  else {
    $output = theme('image', $image);
  }

  // The link path and link options are both optional, but for the options to be
  // processed, the link path must at least be an empty string.
  if (isset($variables['path']['path'])) {
    $path = $variables['path']['path'];
    $options = isset($variables['path']['options']) ? $variables['path']['options'] : array();
    // When displaying an image inside a link, the html option must be TRUE.
    $options['html'] = TRUE;
    $output = l($output, $path, $options);
  }

  return $output;
}

Just pay attention to the blog_post check and output that I created.  I have some javascript that shows and hides the button on hover but you can add that if you want.
Dont forget to add your pintrest JS to the head of your doc.
--Good Luck
Answer: There is nothing 'out of the box' that will add a 'pin it' button to Colorbox.
Placing a pin it button on the overlay means that when the pin it button is used you are pinning the page you were on not the image in the overlay. This means that the Pin It button must be customized to pin the source of the image. This is possible with javasript but as this is different for each CMS I have not seen anyone create a module or plugin to do it.
If you just looking to add a Pin it button to your site in general then the dev version of the 'service links' module says it contain this network, but I have not checked.

Pinterest for Lightbox and/or Colorbox


Tomcat localhost_access_log.txt encoding

Question: I run my web-app in Tomcat 7 and in the localhost_access_log.txt file I have the following lines
0:0:0:0:0:0:0:1 - - [25/Jun/2014:10:22:26 +0300] " Ì  Èc£Ï!#ò2Tç¡$EI «àµ«]ëñʯ¯Ù  (ÌÌÀ+À/ À " 400 -
0:0:0:0:0:0:0:1 - - [01/Jan/1970:02:59:59 +0300] "-" 400 -
0:0:0:0:0:0:0:1 - - [01/Jan/1970:02:59:59 +0300] "-" 400 -

My server.xml configuration
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />

How to change encoding and why the date is incorrect? Thanks
Answer: Maybe, if you are under Linux/Unix, it depends on the $LANG, $LC_TIME, and so on, environment variables used during tomcat startup script? Try to check these variables, and also under Windows, try to check your locale.


What sizes should be the images when loading from some CDN for Android

Question: I'm creating an app for Android and I should load images from a CDN and I want to support all the possible screen sizes. How should be done?
Should be many different versions of the same image stored in the CDN in different folders? Or one only resolution can cover all the screen sizes if it has high resolution?
Also How I know the exact numberXnumber? how I can know that? I should try manually or there are guidelines?
For example if that helps I have an ImageView 100dpX100dp how I know how much should be the pixels?
Thanks
Answer: You should probably set up essentially the basic ranges that android uses, mdpi, hdpi, hdpi-x, hdpi-xx.  So you would have low and medium resolution screens request cdn.com/mdpi/image.png, high resolution request cdn.com/hdpi/image.png and so on...  You define the resolutions within each grouping, for example on hdpi-xx Your images may be 1920x1080, but on hdpi it is only 1280x720.  Those are just examples pulled out of the air, but you can adjust to suit your needs.
You can even use the base android resource system to pull the correct url for each screensize.
i.e.
In the folder values-mdpi you put a string resource that will have the url with mdpi, and hdpi with the base url for hdpi, you get the idea.
For further information you the documentation here provides very clear examples and more detail.
Comment: So that means if I have an ImageView 100dp X 100dp in mdpi screen this is 100px X 100px right? so the cdn.com/mdpi/image.png the image should be 100px if I ask for cdn.com/hdpi/image.png this should be 150px X 150px because the ratio is 1.5 right? But What happen with images that are wrap_content and they don't have static size?
Comment: It is a little more varied depending on screen density, but more or less. You should try experimenting if you can at different screen resolutions to see how your application performs vs. how big your images are.


Anyone know how to get Sibelius to playback pizzicato at a softer dynamic level without writing the dynamic ridiculously soft?

Question: Sibelius playback of pizzicato is much louder than arco for strings. I end up making two copies of a score. One with the dynamics as they should be written for pizzicato for printing and another copy with the pizzicato sections being written at pp or ppp to not over balance any Arco instruments. Is there a global setting that can make pizzicato more realistic dynamically?
Comment: How is the sound created? Are you using the sounds straight from sibelius, or an external MIDI sound font? Are you notating the pizz in "technic text" (CMD + T) ?
Comment: idk Sibelius [haven't used it in 20 years] but check if it reads & writes ctrl 7 &/or ctrl 11 data
Answer:
Play|Instrument Changes|New Instrument Change

select the instrument(s) and adjust the volume


Taxonomy term as node css class

Question: Kind of similar to my previous question, but apparently doesn't work the same way: is there an easy way to use a taxonomy term or a token as node css class to theme different pages?
Answer: Edit you node-type.tpl.php for this.
<?php
    foreach($node->taxonomy as $term){
            $term_classes[] = $term->name;
    }
?>

And print those classes in your node content wrapper.
<div class="content <?php print implode(' ', $term_classes); ?>">
    <?php print $content ?>

Taxonomy term as node css class


Git move latest commit on a branch to stash

Question: When working on a git branch I got some changes in the latest commit. I suspect those changes to be wrong, but not sure. It is easy to remove the commit, and start over.
I want to move that commit to git-stash just incase I need them, and then try another solution on the branch, and still have the option to get the first commit back.
Comment: Why do you need stash? Create a new branch, rewind the old branch. (Or revert the commit)
Comment: That is much easier solution.
Comment: In fact, you should [stop using git stash](https://stackoverflow.com/a/27117335/23118) and use [temporary commits](https://stackoverflow.com/a/75010635/23118) exclusively instead. Normal commits are much safer in they do not have [dangerous](https://stackoverflow.com/questions/5737002/how-to-delete-a-stash-created-with-git-stash-create/5737041#comment27818770_5737041), [complicated](https://stackoverflow.com/q/48619276/23118) [quirks](https://stackoverflow.com/a/75512773/23118) like stash have. –
Answer: You don't need a stash in this case, a regular branch works just fine.
git branch backup-my-work
git reset --hard HEAD^

reset --hard HEAD^ will move your branch back by one commit and discard ALL changes in your working tree. Drop the --hard if you want to keep your local changes and the changes of the undone commit (you can then selectively remove the changes from your working tree)


Cant store the location of a android device and store it in sqlite

Question: I want to store the location and put it in a database i got this code from here.
But the app stops cant find any reasons why ?
i have also inserted my API key. link to the referencing site
The MainActivity.java file
<code>    package in.wptrafficanalyzer.locationmarkersqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class LocationsDB extends SQLiteOpenHelper{

    /** Database name */
    private static String DBNAME = "locationmarkersqlite";

    /** Version number of the database */
    private static int VERSION = 1;

    /** Field 1 of the table locations, which is the primary key */
    public static final String FIELD_ROW_ID = "_id";

    /** Field 2 of the table locations, stores the latitude */
    public static final String FIELD_LAT = "lat";

    /** Field 3 of the table locations, stores the longitude*/
    public static final String FIELD_LNG = "lng";

    /** Field 4 of the table locations, stores the zoom level of map*/
    public static final String FIELD_ZOOM = "zom";

    /** A constant, stores the the table name */
    private static final String DATABASE_TABLE = "locations";

    /** An instance variable for SQLiteDatabase */
    private SQLiteDatabase mDB;

    /** Constructor */
    public LocationsDB(Context context) {
        super(context, DBNAME, null, VERSION);
        this.mDB = getWritableDatabase();
    }

    /** This is a callback method, invoked when the method getReadableDatabase() / getWritableDatabase() is called
      * provided the database does not exists
    * */
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql =    "create table " + DATABASE_TABLE + " ( " +
                            FIELD_ROW_ID + " integer primary key autoincrement , " +
                            FIELD_LNG + " double , " +
                            FIELD_LAT + " double , " +
                            FIELD_ZOOM + " text " +
                        " ) ";

        db.execSQL(sql);
    }

    /** Inserts a new location to the table locations */
    public long insert(ContentValues contentValues){
        long rowID = mDB.insert(DATABASE_TABLE, null, contentValues);
        return rowID;

    }

    /** Deletes all locations from the table */
    public int del(){
        int cnt = mDB.delete(DATABASE_TABLE, null , null);
        return cnt;
    }

    /** Returns all the locations from the table */
    public Cursor getAllLocations(){
        return mDB.query(DATABASE_TABLE, new String[] { FIELD_ROW_ID,  FIELD_LAT , FIELD_LNG, FIELD_ZOOM } , null, null, null, null, null);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}
</code>
The locationscontentprovider.java
<code>    package in.wptrafficanalyzer.locationmarkersqlite;

import java.sql.SQLException;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;

/** A custom Content Provider to do the database operations */
public class LocationsContentProvider extends ContentProvider{

    public static final String PROVIDER_NAME = "in.wptrafficanalyzer.locationmarkersqlite.locations";

    /** A uri to do operations on locations table. A content provider is identified by its uri */
    public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/locations" );

    /** Constant to identify the requested operation */
    private static final int LOCATIONS = 1;

    private static final UriMatcher uriMatcher ;

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, "locations", LOCATIONS);
    }

    /** This content provider does the database operations by this object */
    LocationsDB mLocationsDB;

    /** A callback method which is invoked when the content provider is starting up */
    @Override
    public boolean onCreate() {
        mLocationsDB = new LocationsDB(getContext());
        return true;
    }

    /** A callback method which is invoked when insert operation is requested on this content provider */
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long rowID = mLocationsDB.insert(values);
        Uri _uri=null;
        if(rowID>0){
            _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
        }else {
            try {
                throw new SQLException("Failed to insert : " + uri);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return _uri;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

    /** A callback method which is invoked when delete operation is requested on this content provider */
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int cnt = 0;
        cnt = mLocationsDB.del();
        return cnt;
    }

    /** A callback method which is invoked by default content uri */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

        if(uriMatcher.match(uri)==LOCATIONS){
            return mLocationsDB.getAllLocations();
        }
        return null;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }
}
</code>
the logcat output
<code>    08-15 01:29:34.509: I/ActivityThread(543): Pub in.wptrafficanalyzer.locationmarkersqlite.locations: in.wptrafficanalyzer.locationmarkersqlite.LocationsContentProvider
08-15 01:29:34.818: D/AndroidRuntime(543): Shutting down VM
08-15 01:29:34.818: W/dalvikvm(543): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
08-15 01:29:34.828: E/AndroidRuntime(543): FATAL EXCEPTION: main
08-15 01:29:34.828: E/AndroidRuntime(543): java.lang.RuntimeException: Unable to start activity ComponentInfo{in.wptrafficanalyzer.locationmarkersqlite/in.wptrafficanalyzer.locationmarkersqlite.MainActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.os.Looper.loop(Looper.java:137)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.app.ActivityThread.main(ActivityThread.java:4340)
08-15 01:29:34.828: E/AndroidRuntime(543):  at java.lang.reflect.Method.invokeNative(Native Method)
08-15 01:29:34.828: E/AndroidRuntime(543):  at java.lang.reflect.Method.invoke(Method.java:511)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-15 01:29:34.828: E/AndroidRuntime(543):  at dalvik.system.NativeStart.main(Native Method)
08-15 01:29:34.828: E/AndroidRuntime(543): Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:251)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.app.Activity.setContentView(Activity.java:1835)
08-15 01:29:34.828: E/AndroidRuntime(543):  at in.wptrafficanalyzer.locationmarkersqlite.MainActivity.onCreate(MainActivity.java:33)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.app.Activity.performCreate(Activity.java:4465)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
08-15 01:29:34.828: E/AndroidRuntime(543):  ... 11 more
08-15 01:29:34.828: E/AndroidRuntime(543): Caused by: java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value.  Expected 4132500 but found 0.  You must have the following declaration within the <application> element:     <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.google.android.gms.common.GooglePlayServicesUtil.n(Unknown Source)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable(Unknown Source)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.google.android.gms.maps.internal.q.v(Unknown Source)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.google.android.gms.maps.internal.q.u(Unknown Source)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.google.android.gms.maps.MapsInitializer.initialize(Unknown Source)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.google.android.gms.maps.SupportMapFragment$b.eb(Unknown Source)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.google.android.gms.maps.SupportMapFragment$b.a(Unknown Source)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.google.android.gms.dynamic.a.a(Unknown Source)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.google.android.gms.dynamic.a.onInflate(Unknown Source)
08-15 01:29:34.828: E/AndroidRuntime(543):  at com.google.android.gms.maps.SupportMapFragment.onInflate(Unknown Source)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:279)
08-15 01:29:34.828: E/AndroidRuntime(543):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)
08-15 01:29:34.828: E/AndroidRuntime(543):  ... 21 more
08-15 01:29:36.898: I/Process(543): Sending signal. PID: 543 SIG: 9
</code>
Comment: The error message tells you what you did wrong.
Answer: Read the bottommost "caused by" exception to gain helpful information about the problem and its fix:
<code>The meta-data tag in your app's AndroidManifest.xml does not have the right value.
Expected 4132500 but found 0.
You must have the following declaration within the <application> element:
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
</code>
(I just added some linefeeds to make it more readable.)


Como comparar os elementos de uma lista

Question: Então, to precisando desenvolver o corpo de um codigo que percorre uma lista ja ordenada para descobrir em quais posições estao os elementos iguais. Como faço isso?
Answer: Acredito que o código abaixo possa te ajudar. Basicamente ele faz uma iteração item a item na lista e identifica se o item em uma determinada posição é igual ao anterior, já que você disse que a sua lista já está ordenada
lista1 = [1,2,2,3,4,5,6,6,6,6,7,8,9,10]

prev_item = lista1[0]-1 # garante que prev_item está fora da lista1

for index in range(0,len(lista1)):
    if lista1[index] == prev_item:
        print(f'valor repetido na posição {index}')

    prev_item = lista1[index]

resultado:
valor repetido na posição 2
valor repetido na posição 7
valor repetido na posição 8
valor repetido na posição 9

Comment: tem a possibilidade de utilizar um dicionário, retornando depois cada posição para cada item procurado.
Comment: Vou tentar com esse ai! Mas esqueci de mencionar tbm que nao tenho acesso aos elementos da lista, a priori (pode modificar de acordo com quem digita). Posso seguir nesse mesmo esquema?
Comment: mesmo não tenho acessa à lista em si, a parte do `for` pra frente deve funcionar, desde que você consiga importar a lista no seu código.

Como comparar os elementos de uma lista


How is it possible to make an object array public with a variable

Question: I want this following array to be public with a int variable to two functions.
I do not know how to write this as a struct. I know this struct can be GET and SET but I am stuck on how to write  for this array. This has been nagging me about C OOP for a long time.
int pixelCount = 0

public CustomVertex.TransformedColored[] points_data
                             = new CustomVertex.TransformedColored[pixelCount];

Comment: Not entirely clear what your question is
Comment: @Jamiec yeah I tried, but I could only fix cosmetic issues in the hopes someone else could understand it better.
Answer: My mindreading skills are at half tilt today, if Ive got this entirely wrong I apologise.
I think what you're after is an Indexer, which allows you to add array-like get/set access to your own classes.
public class MyClass
{
    private CustomVertex.TransformedColored[] points_data;

    public CustomVertex.TransformedColored this[int pixelCount]
    {
       get{ return points_data[pixelCount]; }
       set{ points_data[pixelCount] = value; }
    }
}

Usage:
 var obj = new MyClass();
 obj[0] = some_value; //set
 var result = obj[0]; // get

Comment: When I set, the compiler throws an error.
            var objPoints = new PointsDataClass();
            objPoints[0] = CustomVertex.TransformedColored[countPixels];

Error 1 'Microsoft.DirectX.Direct3D.CustomVertex.TransformedColored' is a 'type', which is not valid in the given context
Comment: You have to do it on an *instance* of `MyClass` not the class itself.
Comment: I think I know where the confusion is. I don't want an array of CustomVertex.TransformedColored objects. I want one public object CustomVertex.TransformedColored where pixelCount sets the size of CustomVertex.TransformedColored
Comment: Cool, glad you found your issue.
Comment: Getting error trying to SET. Cannot modify the return value of 'Object_Namespace.Form1.PointsDataClass.this[int]'

                    objPoints[pointCount].X = (float)(item1);
                    objPoints[pointCount].Y = (float)(item2);
                    objPoints[pointCount].Z = 1.0f;
                    objPoints[pointCount].Rhw = 1.0f;
                    objPoints[pointCount].Color = Color.White.ToArgb();

Please help.
Comment: ... because it is not a variable
Comment: It is still not possible to publicly access the stored objects from the class in across different functions.


Inserir component depois da renderização Vue.js

Question: Oi, estou aprendendo como que se usa Vue.js e até o momento estou sabendo como que cria components.
Porem estou como uma dificuldade, estou querendo renderizar um componente depois de carregar a pagina. Eu no meu projeto vou fazer call ajaxs e com o json que receber, inserir os componentes, mas antes, para testar a renderização deles estou usando esse código Jquery basico:
<code>$('#test123').html('<inventory message="Click on the Item to activate it."></inventory>');
</code>
Porem esse componente não é renderizado e não acontece nada com ele, eu vi algumas coisas na internet, porem as soluções que eu achei renderizava um componente só, mas eu preciso renderizar varios, porque o json que eu vou receber, o javascript vai fazer foreach e colocar na div.
Obrigado pela atenção.
Comment: Cara não sei por onde está aprendendo **Vue**, mas não está indo em um caminho bacana não! Só de utilizar jQuery junto com Vue, já demonstra isto. Não entendi muito bem o que quer fazer, mas, Vue.js tem em uma das suas premissas principais a **NÃO** manipulação direta do DOM, te aconselho a ir aprendendo na documentação oficial no site: https://br.vuejs.org/
Comment: https://pt.stackoverflow.com/questions/254378/inserindo-componente-vue-no-dom-via-jquery
Comment: Olá @LeAndrade, estou usando Jquery só como teste, pois estou começando a aprender a usar Vue, e estou sabendo usar no momento componentes, esse Jquery era só para fazer um teste. Meu objetivo é que, no meu projeto vai ter tipo um joguinho, onde você tem seu inventario e seus itens, eu quero fazer com que quando o usuario clique para usar/ativar o item, a api vai retornar um json do inventario atualizado (sem o item, pois ele acabo de usar), só que os itens são componentes, fiz o teste com jquery e vi que o Vue não renderizava eles.
Answer: O VueJS possui um ciclo de vida próprio. https://br.vuejs.org/v2/guide/instance.html na própria documentação ele explica os métodos que controlam esse ciclo de vida. Ao invés de usar  o Jquery, o VueJS também tem o reatividade para código HTML, para isso, você pode usar "v-html" ao invés do "v-model" ou "v-bind".
Comment: Desculpa cara, mas não entendi muito bem como eu posso resolver o meu problema com o v-html :/ poderia me explicar melhor, por favor?
Comment: Diferente do v-model e v-bind, esses controlam o valor de input ou select, por exemplo. O V-HTML  vai permitir escrever código HTML e o VueJS escreverá esse html para ser executado.
Comment: Você pode criar um atributo na sua instância do Vue e adiconar da seguinte forma: "". Quando o call do ajax ser executado, você pode fazer o foreach e adcionar a variável html.


What is meant by PDF in describing a distribution? Is a PDF ( or PMF) always also a probability function?

Question: I am trying to understand the following statement

Consider a random variable that follows the distribution
$PDF(Y=y|p) =(1-p)^y p$
where $y \in\{0,1,2 ... \}$ is a non-negative
integer and p is the parameter of a distribution.

I am familiar with describing a distribution as $p(x|\theta)$ where $\theta$ is a parameter and I am (almost) familiar with a pdf as a probability density function of a distribution. But I am not familiar with a distribution being described as a pdf.  Is this common practice?
[Update]
I received a correction stating that it should be PMF not PDF to distinguish that the RVs are discrete. But I am still confused.
Is a probability distribution and the PDF (or PMF) of a distribution one and the same thing? Is a distribution defined by it's PDF ?
For example my lecture notes state that the PDF for the normal distribution is
$f(y_i|\theta : \mu, \sigma^2) = p(y_i | \theta : \mu, \sigma^2)= (\frac{1}{2\pi\sigma^2})^\frac{1}{2} exp ( - \frac{(y_i-\mu)^2}{2\sigma^2}) $
This seems to be different from what whuber is telling me.
My Cheatsheet states that the Gaussian is also this formula.
Comment: Yes it's common: just search our site for "PDF."  But this formula is not a PDF: it's the formula of a *probability function.*  It clearly and thoroughly describes the distribution.
Comment: See [Wikipedia](https://en.wikipedia.org/wiki/Geometric_distribution) on 'geometric distribution' (2nd parameterization counting failures before first success).
Comment: Yes.  Thomas Lumley has explained it well.
Comment: Oh dear, I am still confused. I updated the question.
Comment: Unclear what you are asking.
Comment: @whuber why do you say that the formula is not a PDF? Because it is a PMF? I was used to seeing the function name written  as P or Pr so it threw me when it was written as PDF
Comment: I guess it looks odd to write $P(Y=y|p)$ hence the use of PMF instead of P?
Answer: Any one-dimensional probability distribution can be defined by its cumulative distribution function $P(X\leq x)$, and you can specify a model (a set of probability distributions) by letting this depend on parameters, $P(X\leq x; \theta)$
Most of the probability distributions you encounter can also be written in terms of either a probability (mass) function or a probability density function.
The probability function (or probability mass function) specifies $P(X=x)$ for any $x$.  If the distribution is discrete, that makes sense and $P(X=x)=P(X\geq x)-P(X>x)$ is uniquely defined. Your example specifies $P(Y=y)$, and so is the probability function of a family of discrete distributions. As @BruceET says, it's the geometric distribution family.
The probability density function is the derivative of the CDF with respect to $x$, so it makes sense if the CDF has a derivative[1]. We usually say these are continuous distributions, though the precise mathematical term is 'absolutely continuous'. In your example of a Gaussian distribution, you are quoting the probability density function. The density function doesn't specify $P(X=x)$, because that is zero. Instead, you need to integrate the density function over a set to find the probability of that set.
There are probability distributions that are neither discrete nor continuous and so have neither a probability function nor a density function. A relatively realistic example is a positive continuous random variable with a discrete spike at zero. These are used in modelling medical cost data.  There are also more mathematically complicated ways a distribution can be neither discrete nor continuous.
Most of this is also true for higher-dimensional variables, though the classification of ways it can go wrong is more complicated. It can also mostly be made true for settings where there isn't an ordering on $X$ (such as compass bearing, which wraps around at $360^{\circ}$.


Android application without GUI

Question: I have been developing a simple application without UI using broadcast receiver.
The app doesn't contain any ACTIVITIES.
I have given necessary permissions.
I took the code from this url:http://developerandro.blogspot.in/2013/09/check-internet-connection-using.html
The app shows a toast "Not connected to internet" when I click change wifi state. It's working correctly.
But my question is There is an activity registered in my manifest file which I don't have. So I delete those lines from my manifest. Then no toasts are shown and I checked the logs too. No output on changing wifi state.
Why this happened? Please help me guys...
Here is the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcast_internetcheck"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.broadcast_internetcheck.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.example.broadcast_internetcheck.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

Here is my Broadcastreceiver class:
public class NetworkChangeReceiver extends BroadcastReceiver{

  @Override
     public void onReceive(final Context context, final Intent intent) {

         String status = NetworkUtil.getConnectivityStatusString(context);
          /*Above line will return the status of wifi */
         Toast.makeText(context, status, Toast.LENGTH_LONG).show();

     }
}

Comment: you mean you are not able to connect to internet ?? is that so?
Comment: that's not my situation, I need a simple toast when I change my wifi state.
Comment: So you want to make toast button, i don't your code but i'll make a simple Toast button for you?
Comment: As your question, it's because the activity hold the showing Toast function, when the activities hasn't been launched, it will not show Toast. You can write a service to do so without any activity.
Comment: @user2652394 the toast is shown from BroadcastReceiver class, in onReceive method.
Comment: @user2652394 u r not following me. The above code working correctly. If took off the lines ..., no toast are shown.
Comment: @user2652394 bcoz, I have no activities to register in the manifest.
Answer: You will need to create a dummy activity for a Service which will be triggered in the onCreate() of the dummy, maybe a non-UI with finish() .
Without that the required implementation is not possible, esp above Android 3.1.
http://developer.android.com/about/versions/android-3.1.html#launchcontrols
Run only a background service when application start
Start android application without activity
http://commonsware.com/blog/2011/07/13/boot-completed-regression-confirmed.html
And for more on Service:
http://developer.android.com/guide/components/services.html
https://developer.android.com/training/run-background-service/create-service.html
http://www.vogella.com/tutorials/AndroidServices/article.html
Answer: You can use service instead. But showing Toast through service bit complicated instead you can show notification through service for No Internet Connection.
Comment: http://stackoverflow.com/questions/21603884/android-notify-from-my-alarm-class/21604104#21604104
Comment: can u tell me how to notify using service? That'd be great.
Answer: If you don't want any activity check this answer. Actually you would have to create service for this: link
Comment: Yes, I knew about services. but there should not be any activities.
Answer: Create a transparent activity. Launch the toast while the activity is active and immediately finish the activity.

Android application without GUI


A WinUI 3 question about accessing the UI thread from another thread

Question: A WinUI 3 question about accessing the UI thread from another thread, say, a Timer tick.
In WinForms that was extremely easy with a (someControl).InvokeRequired and .Invoke.
In WPF we had to add .Dispatcher. and in UWP we had to specify a specific dispatcher:
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(...).
But it still all worked just fine.
When I port my UWP solution (an extremely simple program to just show the issue), and adjust the name of the class (and thus its constructor), it still builds fine, but when I run it, I get an "a method was called at an unexpected time" exception. (Again: works fine as a UWP app)
I'll include my test code below:
Any idea what's happening here? HOW do I fix this, and, bonus answer: why does this happen in WinUI 3 and not in UWP?
(And yes, I'm aware of DispatcherTimer, I use Timer to demonstrate my problem: in my actual app I use something far more complicated than a timer, and I wanted to keep the demo code as concise and short as possible).
Demo code:
using Microsoft.UI.Xaml;
using System;
using System.Threading;
using Windows.UI.Core;

namespace WinUI3NotOwner
{
    public sealed partial class MainWindow : Window
    {
        public Timer timer;
        public int counter = 0;

        public MainWindow()
        {
            this.InitializeComponent();
            timer = new Timer(TimerTick, null, 1000, 1000);
        }

        public void TimerTick(Object stateInfo)
        {
            if (++counter == 3)
            {
                Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () => { TbTest.Text = "Works!"; }); // WinUI 3 code. Ignore the warning: we actually DON'T want to wait for its completion!
            }
        }
    }
}

/* XAML code used:
<Window
    x:Class="WinUI3NotOwner.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WinUI3NotOwner"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid>
        <TextBox x:Name="TbTest" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="50,50,0,0" TextWrapping="Wrap" Text="TextBox" Width="200" Height="40"/>
    </Grid>

</Window>

*/
Answer: You should use the DispatcherQueue.
public void TimerTick(Object stateInfo)
{
    if (++counter == 3)
    {
        //Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        //() => { TbTest.Text = "Works!"; }); // WinUI 3 code. Ignore the warning: we actually DON'T want to wait for its completion!
        DispatcherQueue.TryEnqueue(() => { TbTest.Text = "Works!"; });
    }
}

Your code doesn't work in WinUI 3 because it doesn't support desktop apps. You might find this doc helpful.
Comment: I created a video about the [DispatcherQueue](https://www.youtube.com/watch?v=HtE_1v7X8Cc).
Comment: THANK you! That indeed did it!
I read the document you mentioned: my head is still spinning, will have to re-read it a few more times. ;-)

But what really gets me is this "WinUI 3 [because it] doesn't support desktop apps"
Am I really the last person on Earth to use a desktop ... and an app running on it? ;-)

But again: thanks! At least my MIDI ap now works! Much obliged!


Como concatenar 2 Strings com Java no HTML

Question: Estou utilizando o seguinte input com 2 valores pré-setados.
<input type="text" class="read-only" value="${FORM.dataAgendamento + FORM.horaAgendamento}" readonly="readonly" size="40"/>

Caso os mesmos sejam inteiros, funciona perfeitamente, porém para strings estou recebendo java.lang.NumberFormatException:
Queria saber como realizar essa concatenação de strings nesse mesmo input.
Comment: Esse valor será analisado pelo Java ou pelo JavaScript? O erro é no Java, mas as tags são JavaScript.
Comment: Você está usando JSP? Quais são os valores dessas variáveis?
Answer: No caso você tentou somar dois objetos que não são números. Tente o seguinte:
<input type="text" class="read-only" value="${FORM.dataAgendamento} ${FORM.horaAgendamento}" readonly="readonly" size="40"/>


How many unique combination of $n$ numbers are there when multiplying $x$ numbers?

Question: If you have $n$ numbers and you multiply them in every combination
$$A\cdot A,\  A\cdot B,\ B\cdot A,\ B\cdot B$$
and so on, how many times do you get the same answer? Or, how many times do you get a unique answer? That is just for a product of two numbers, what if you did product of $3, 4,... n$ numbers. Is there a formula that could calculate this?
An example would be, let's say you have numbers $2,3,5,7$. You can do
$$2\cdot 2,\; 2\cdot 3,\; 3\cdot 2, \;3\cdot 3, \;2\cdot 5, \;5\cdot 2, \;3\cdot 5, \; 5\cdot 3,\; 5\cdot 5,\; 2\cdot 7,\; 7\cdot 2, \;3\cdot 7, \;7\cdot 3, \;5\cdot 7,\; 7\cdot 5, \;7\cdot 7$$
With that you get 16 combinations and only 10 unique answers.
Comment: For  $n$ "generic" numbers (no two products are equal unless they must be) the number of distinct products is $\binom{n}{2}+n$, which is $\frac{n(n+1)}{2}$.
Comment: Thank you, Ill have to do more research on the below, until then how could I convert the formula above for combination of three $S_1*S_2*S_3$ rather than just two?
Comment: You are welcome. Again we assume all products are distinct. .We can do it the long way, $\binom{n}{3}$ for all numbers different, $n(n-1)$ for two the same, one different, and $n$ for all the same, add. But there is a better way that generalizes to products of $k$ things, not necessarily different. It uses Stars and Bars, please see Wikipedia. For $k$ the count is $\binom{n+k-1}{k}$, so $\binom{n+2}{3}$ for products of three not necessarily distinct $S_i$.
Answer: We assume that we are given a set $S=\{s_1,s_2,\dots,s_n\}$ of $n$ distinct numbers, and want to count the number of numerically distinct products  $a_1a_2\cdots a_k$, where the $a_i$ range over $S$.
The answer very much depends on numerical properties of the numbers in the set $S$. We will find the maximum possible number of numerically distinct products. We get this maximum if, for example, the elements of $S$ are distinct primes, and in many other cases.
Let $P$ be a product of $k$ elements of $S$. Let $x_1$ be the number of copies of $s_1$ that we used to form $P$. Let $x_2$  be the number of copies of $s_2$ that we used, and so on.
Then the $x_i$ are non-negative integers, and $x_1+\cdots+x_n=k$. Furthermore, under our assumptions any solution of $x_1+\cdots +x_n=k$ in non-negative integers gives a numerically distinct product.
Thus by Stars and Bars (please see Wikipedia) the number of numerically distinct products, under our assumptions, is $\binom{n+k-1}{n-1}$ or equivalently $\binom{n+k-1}{k}$.
Remark: The case $n=4$, $k=2$ of the OP does not require the above machinery, and neither does $n$ arbitrary, $k=2$. But note that for the case $k=2$, the general formula above gives the answer $\binom{n+1}{2}$.