A problem on the existence of bijections

Question: Let $ A_i, i = 1, 2, \cdots, n $ be finite sets of the same size. For all $ i = 1, 2, \cdots, n $, let $ f_i: A_i \to A_1 $ be a bijective function, where $ f_1 $ is an identity function. Suppose that the functions satisfy the following property, for all $ i = 1, 2, \cdots, n $ and $ j = 1, 2, \cdots, n $:
$$ \forall x \in A_i \cap A_j, f_i(x) = f_j(x). $$
Given the sets $ A_i, i = 1, 2, \cdots, n $, is it always possible to find the bijections $ f_1, f_2, \cdots, f_n $, which satisfy the property?
Answer: No.
Let $A_1=\{0,1\}$, $A_2=\{0,2\}$ and $A_3=\{0,3\}$.
Then the functions $f_i$ are determined for $i=1,2,3$ with $f_2(2)=f_3(3)=1$.
Now let $A_4=\{2,3\}$.
Then $f_4(2)=f_2(2)=1$ and $f_4(3)=f_3(3)=1$ according to the demands.
But then $f_4$ is not injective.

edit (counterexample for $n=3$)
Let $A_1=\{0,1,2\}$, $A_2=\{0,1,3\}$ and $A_3=\{0,2,3\}$.
Then $f_2(0)=0$, $f_2(1)=1$ and $f_2(3)=2$ according to the demands.
But also $f_3(3)=f_2(3)=2$ and $f_3(2)=2$ is demanded so $f_3$ is not injective.
Comment: What if $ n = 3 $?
Comment: I have added a counterexample for $n=3$.


how to make a installer for .net

Question: How to make an installer for windows .net?
Comment: I believe the trial logic is usually done inside the application, not the installer.
Comment: possible duplicate of [How to create setup for any exe ?](http://stackoverflow.com/questions/1264457/how-to-create-setup-for-any-exe)
Comment: Hey, i need a installer with trial capatibilities
Comment: The Shareware Start Kit was quite slick.  Might be a bit hard to find these days.
Answer: Visual Studio can generate rudimentary installers.  New Project ==> Other Project Types ==> Setup and Deployment
Deploying Applications on MSDN
Answer: I would use this http://nsis.sourceforge.net/Main_Page to create the installer. (though there may be more suitable options for a .NET app)
The trial capability requirement should be coded into your app with your own logic, otherwise it can probably be broken by a simple system-restore operation.

how to make a installer for .net


About a spectrum of a C*-algebra

Question: Let $A$ be an unital commutative C*-algebra.
Show that the spectrum of $A$ is disconnected iff there is a projection $p \in A$ not trivial.
Answer: Let $\Gamma:A\to C(\hat{A})$ be the Gelfand representation (that is, $\Gamma(a)(f)=f(a)$ for $a\in A$ and $f\in\hat{A}$).
First, suppose there exists a non-trivial projection $p$ in $A$. consider the polynomial $P(X)=X(X-1)$. Then
$$P(\sigma(p))=\sigma(P(p))=0,$$
so $\sigma(p)\subseteq P^{-1}(0)=\left\{0,1\right\}$. Also, notice that $p(p-1)=0$, so neither $p$ nor $p-1$ can be invertible, since $p$ is non-trivial. Therefore, $\sigma(p)=\{0,1\}$.
Now, we know that $\left\{0,1\right\}=\sigma(p)=\left\{f(p):f\in\hat{A}\right\}=\Gamma(p)(\hat{A})$. That way, $\Gamma(p)$ is a continuous function in $\hat{A}$ with disconnected image. Thus, $\hat{A}$ has to be disconnected as well.
Conversely, suppose $\hat{A}$ is disconnected, and let $Y$ be a non-trivial clopen subset of $\hat{A}$. The characteristic function $1_Y:\hat{A}\to\mathbb{C}$ ($x\in Y\mapsto 1$, $x\not\in Y\mapsto 0$) is continuous, and it is a non-trivial projection in $C(\hat{A})$. By the Gelfand Representation Theorem, $\Gamma$ is an isomorphism, so there exists $a\in A$ such that $\Gamma(a)=1_Y$, and $a$ must also be a non-trivial projection in $A$.
Answer: Here is a shorter argument. Since $A$ unital and commutative, we have $A\simeq C(X)$, where $X$ is the spectrum.
Let $p\in C(X)$ be a nontrivial projection. As $p$ is continuous, the sets $X_0=p^{-1}(\{0\})$ and $X_1=p^{-1}(\{1\})$ are open, and $X=X_0\cup X_1$. So $X$ is disconnected.
Conversely, if $X$ is disconnected, then $X=X_0\cup X_1$ with $X_0,X_1$ open. Let $p=1_{X_1}$, the characteristic function of $X_1$. Because the possible pre-images of sets by $p$ are $\emptyset, X_0, X_1, X$, which are all open, $p$ is continuous. Thus $p\in C(X)$ and $p\ne0$, $p\ne1$, $p^2=p$, $p^*=p$, as $p$ only takes the values $0,1$.

About a spectrum of a C*-algebra


Differential forms: algebraic curves vs Riemann surfaces

Question: I've tried to read about both Riemann surfaces and algebraic curves (over an algebraically closed field) and in both cases I found definitions of objects called differential forms (or 1-forms).
For instance, here meromorphic 1-forms on a Riemann surface are introduced as a set of expressions in the form $\omega dz$ that behave in a certain way with respect to chart changes. The same kind of definition is encountered in the book Complex Algebraic Curves, F. Kirwan.
On the other hand, books on algebraic curves such as Algebraic curves, W. Fulton introduce objects called differential 1-forms in an algebraic way (see also here for instance).
So I'm wondering:

do both those concepts coincide or are related in the case of complex curves?
if yes, how do we show this?
also, which of those concepts emerged first chronologically?
Answer: To have any hope of this being true, we need to look at global differentials on projective curves (or compact riemann surfaces).
For example, take $C = \mathbb{C}$. Then, $\Omega^{alg}_{C}(C) = \mathbb{C}[z]dz \subsetneq \Omega^{an}_C(C)$, where the left and right hand sides denote global algebraic and analytic 1-forms respectively. The inclusion is strict since there are many entire functions which are not polynomials. (eg. $e^zdz \notin \Omega_{C}^{\text{alg}}(C)$).
If $C$ is a smooth projective curve, then this is true. In fact, we can show this holds for a smooth projective variety $X$ over $\mathbb{C}$, using GAGA. The content of the GAGA theorems is that if $X^{an}$  denotes the complex manifold over $\mathbb{C}$ obtained from $X$, then there is an operation $V \mapsto V^{an}$ which takes in an algebraic vector bundle of finite rank and outputs a complex analytic one of the same rank. Furthermore, there is a natural map $V \to V^{an}$ coming from the fact that algebraic forms are always analytic. This generalizes $\Omega_C^{alg} \subset  \Omega_{C}^{an}$.
The most relevant GAGA theorem to us is the following:

The map $V \to V^{an}$ induces an isomorphism of sheaf cohomology $$H^i(X, V) \to H^i(X^{an}, V^{an})$$ for all $i \geq 0$.

Taking $i = 0$, $X = C$, and $V = \Omega^{alg}_C$ gives an affirmative answer to your first question when $C$ is compact. I won't say much about the proofs in GAGA; I just wanted to point out that for your second question, this is a special case of a very general phenomenon. (In fact, GAGA is usually stated in terms of coherent sheaves; a vast generalization of finite rank vector bundles.)
Lastly, I won't say a lot about the history since I don't know it well. The algebraic differentials here are also called Kähler Differentials, which were introduced in the 1930s. On the other hand, differentials are a much older concept, and the credit for organizing (analytic) differential forms algebraically using exterior algebra is usually given to Élie Cartan and his 1899 paper.


Find the largest angle for which sine and tangent agree to within two significant figures.

Question: I am kind of stuck with the solving process of this question:
\begin{align}
& \text{error } = 0.01 \\
\implies & \tan\theta = \text{ error }+ \sin\theta \\
\implies & \tan\theta = 0.01 + \sin\theta \\
\implies & \tan\theta - \sin\theta = 0.01 \\
\implies & \dfrac {\sin\theta}{\cos\theta}  - \sin\theta = 0.01
\end{align}
And this is where I stop, I don't know where to go from here.
Comment: Do you mean the largest angle less than $\pi/2$?  Otherwise, $\sin(n \pi) = \tan(n \pi) = 0$ for all integers $n$.
Comment: Also "agree to within two significant figures" is not the same as a difference of $0.01$.
Comment: I suspect that this is just a numerical problem, and you just plot |tan $\theta$ - sin $\theta$| until this is equal to 0.01
Comment: In the old days (not too long ago) we used tables: http://math2.org/math/trig/tables.htm
Answer: It $\sin(\theta) = x \in (0,\pi/2)$, $\tan(\theta) = x/\sqrt{1-x^2}$.  The equation $\tan(\theta) - \sin(\theta) = r$ then implies
$${x}^{4}+2\,r{x}^{3}+{r}^{2}{x}^{2}-2\,rx-{r}^{2} = 0$$
For $r = 1/100$ this is irreducible.  It does have closed-form solutions in terms of radicals, but they are not pleasant.  Numerical methods can be used.
Comment: It can be slightly simplified by using $t=\tan(\theta/2)$ substitution, we end up with $t^4+400t^3-1=0$ giving an approximate $\dfrac{2}{\sqrt[3]{400}}$.
Answer: The greatest value of $x$ is $\tan^{-1} 0.275$ radians, or something infinitely smaller than that.
Plotting the graph $round(100 \tan x) - round(100 \sin x)$ on Desmos gives many solutions, but the greatest solution that satisfies $x < \pi/2$ is approximately $0.26386$.
However, $\tan 0.26386$ $\approx 0.2749933$, and $\sin 0.26386 \approx 0.26515$. This suggests that $\tan x$ can get as close to $0.275$ as you want, and $\sin x$ will still round to $0.27$. However, once $\tan x$ is $0.275$, then it rounds to $0.28$, but $\sin x$ still rounds to $0.27$.
The idea of this formula is to round $\tan x$ and $\sin x$ to $2$ significant figures, and find $x$ where they are equal, or in other words, find the zeroes of $round(\tan x) - round(\sin x)$.
Since in Desmos, the function $round()$ rounds only to the nearest integer, then we can multiply by $100$, round it, and then divide back by  $100$, which results in $\frac{1}{100}(100 \ round(\tan x)$ $- 100\ round(\tan x)) = 0$, and simplifies to the formula above.
Answer: Robert Israel gave the rigorous answer; the solution implies solving a quartic. Zwin gave also an approximation.
Just for the fun of it, let me give another one.
Assuming that $r$ and $x$ are small, we could use Taylor series giving
$$\tan(x)-\sin(x)=\frac{x^3}{2}+O\left(x^5\right)$$ then
$$\tan(x)-\sin(x)=r\implies \frac{x^3}{2}=r\implies x=\sqrt[3]{2r}\tag 1$$ which exactly Zwin's result.
We can do a little better, using, instead of Taylor series, Padé approximants and get
$$\tan(x)-\sin(x) \approx \frac{2 x^3}{4-x^2}$$ You will be amazed to see how close rhs and lhs are if you plot the two functions for $-1 \leq x \leq 1$. So, using it
$$\tan(x)-\sin(x)=r\implies \frac{2 x^3}{4-x^2}=r\implies 2x^3+ rx^2-4 r=0$$
So, using approximations, we reduced the problem to a cubic equation which has the good idea to show only one real root. Using this, we get as an explicit solution
$$x=\frac{1}{3} r \cosh \left(\frac{1}{3} \cosh
   ^{-1}\left(\frac{216}{r^2}-1\right)\right)\tag 2$$
The pitty is that for your case, $(1)$ and $(2)$ lead to almost identical results.
Edit
By analogy with the result from $(1)$, let us assume that we can write
$$x=\sum_{n=1}^p a_n\left(\sqrt[3]{2r}\right)^n$$ and use Taylor series for the expansion of $\tan(x)-\sin(x)=r$ around $r=0$. This leads to
$$a_1=1 \qquad a_3=-\frac{1}{12}\qquad a_5=-\frac{1}{120}\qquad a_7=\frac{1}{336}\qquad a_9=\frac{1}{2304}$$ all even coefficients being $0$.
As shown in the table below, the results are extremly good even for "large" values of $r$.
$$\left(
\begin{array}{ccc}
 r& \text{approximation} & \text{exact} \\
 0.005 & 0.214606 & 0.214606  \\
 0.010 & 0.269763 & 0.269763  \\
 0.015 & 0.308200 & 0.308200  \\
 0.020 & 0.338625 & 0.338625  \\
 0.025 & 0.364183 & 0.364183  \\
 0.030 & 0.386414 & 0.386414  \\
 0.035 & 0.406202 & 0.406202  \\
 0.040 & 0.424105 & 0.424105  \\
 0.045 & 0.440501 & 0.440501  \\
 0.050 & 0.455660 & 0.455660  \\
 0.055 & 0.469783 & 0.469783  \\
 0.060 & 0.483021 & 0.483021  \\
 0.065 & 0.495495 & 0.495495  \\
 0.070 & 0.507300 & 0.507300  \\
 0.075 & 0.518513 & 0.518513  \\
 0.080 & 0.529200 & 0.529200  \\
 0.085 & 0.539414 & 0.539414  \\
 0.090 & 0.549200 & 0.549200  \\
 0.095 & 0.558598 & 0.558597  \\
 0.100 & 0.567640 & 0.567639  \\
 0.105 & 0.576356 & 0.576355  \\
 0.110 & 0.584771 & 0.584770  \\
 0.115 & 0.592908 & 0.592907  \\
 0.120 & 0.600787 & 0.600786  \\
 0.125 & 0.608424 & 0.608423  \\
 0.130 & 0.615837 & 0.615836  \\
 0.135 & 0.623039 & 0.623038  \\
 0.140 & 0.630043 & 0.630041  \\
 0.145 & 0.636861 & 0.636859  \\
 0.150 & 0.643504 & 0.643501  \\
 0.155 & 0.649980 & 0.649977  \\
 0.160 & 0.656299 & 0.656296  \\
 0.165 & 0.662469 & 0.662465  \\
 0.170 & 0.668497 & 0.668493  \\
 0.175 & 0.674390 & 0.674386  \\
 0.180 & 0.680155 & 0.680150  \\
 0.185 & 0.685797 & 0.685792  \\
 0.190 & 0.691323 & 0.691317  \\
 0.195 & 0.696736 & 0.696729  \\
 0.200 & 0.702042 & 0.702035
\end{array}
\right)$$
Answer: Using zwin's suggestion, using $t=\tan \left(\frac{x}{2}\right)$,
$$\tan(x)-\sin(x)-r=0\implies r t^4+4 t^3-r=0$$ We can solve the quartic equation with radicals (ugly/monstreous solutions) and develop the valid one as Taylor series around $r=0$. Using $z=\sqrt[3]{2r}$, this leads to
$$t=\frac{z}{2}-\frac{z^5}{96}+\frac{z^9}{1536}-\frac{35 z^{13}}{663552}+\frac{77
   z^{17}}{15925248}+O\left(z^{21}\right)$$
Now, using $x=2 \tan ^{-1}(t)$ and repeating the expansion, we get
$$x=z-\frac{z^3}{12}-\frac{z^5}{120}+\frac{z^7}{336}+\frac{z^9}{2304}-\frac{5
   z^{11}}{25344}-\frac{35 z^{13}}{1078272}+\frac{z^{15}}{61440}+\frac{385
   z^{17}}{135364608}+O\left(z^{19}\right)$$
For $r=\frac 12$ that is to say $z=1$, the above expansion gives as an estimate $x=\frac{617563433269}{677499863040}\approx 0.911533$ while the "exact" solution would be $0.911531$.
For $r=\frac 1{100}$, this would lead to the approximation
$$x=0.269763141387359251$$ while the "exact" solution would be
$$x=0.269763141387359224$$


video module, MIME problem

Question: I have installed the video module of the Drupal 7 distribution. I have added the "video" field to my content type. When I upload the mp4 format of the video, I get the following message:

No video with support format and MIME type found.

What should I do?
Answer: Changing the player set to play files of that type might help. If not, installing one of the transcoders like ffmpeg or Zencoder will fix it. If that's not practical, you can use other modules besides Video, and create your own video field, for example the jPlayer module (which takes any m4v videos, a variation on mp4)

video module, MIME problem


Computing the length of a finite group

Question: Can someone suggest a GAP or MAGMA command (or code) to obtain the length $l(G)$ of a finite group $G$, i.e. the maximum length of a strictly descending chain of subgroups in $G$?
Thanks in advance.
Comment: Does the length depend on more than the composition factors? If so you just need a table for simple groups, but I don't think the length is known exactly (even for alternating groups if I recall correctly).
Comment: I don't think so either, but it is precisely for simple groups that I want it. In my mind this is equivalent to asking for a path of maximal length in a directed graph (by looking at the subgroup lattice), but this problem is known to be generally hard. For relatively small cases brute force should work though. I'm just not sure how to ask either GAP or MAGMA to do this.
Comment: Thanks to both Jack and Derek for their answers. Quick question: once you have defined a function in MAGMA, can you save it somehow so that there's no need to define it all over again whenever you start a new session?
Comment: I use the "load" command for simple scripts, and "Attach" for things I spent more time on. I made an Attach-able version on my website. Download http://www.ms.uky.edu/~jack/2012-06-07-SubgroupLength.m and in magma `Attach("SubgroupLength.m")`.
Comment: I'd like to raise an issue at this point: could it be that the length of a finite group $G$ is a good "recognizability" criterion for testing simplicity? For example it's not difficult to see that $l(PSL_2(2^n))=n+\Omega(2^n-1)+1$, so unless $2^n+1$ is a Fermat prime, you can always tell it apart from the soluble groups of the same order at least.
Answer: Just to get you started, here is a very short recursive Magma function to compute
this. You could do something similar in GAP. Of course, it will only work in reasonable time for small groups. On my computer it took about 10 seconds to do $A_8$. To do better you would need to do something more complicated like working up through the subgroup lattice. It is not an easy function to compute exactly.
 Len := function(G)

 if #G eq 1 then return 0; end if;
 return 1 + Max([$$(m`subgroup) : m in MaximalSubgroups(G)]);
 end function;

Comment: Do you have a function that converts the output of CompositionFactors back into something that one could use MaximalSubgroups on? That would allow handling some nastier composite maximal subgroups.
Comment: You could call CompositionSeries and find some permutation representation of the quotients, which would probably work in this situation, because the simple groups involved will not be very big.
Answer: I believe the length of the simple groups are not known in general, so this will require the groups involved to be small enough to do some brute force calculations.
Assuming the length is an invariant of the composition factors, we try an inductive approach for simple groups: l(G) = max( l(M) : M a maximal subgroup of G ) + 1.  For composite groups, we just add up the lengths on the composition factors.
Since magma has large precomputed tables of maximal subgroups of groups (that have had errors), I recommend it for speed.
subgroupLength := function( grp )
  len := $$;
  if #grp eq 1 then return 0;
  elif IsSolvable( grp ) then return &+[ pn[2] : pn in FactoredOrder( grp ) ];
  elif IsSimple(grp) then return 1 + Max( { len( max`subgroup ) : max in MaximalSubgroups( grp) } );
  // else return &+[ len( groupForm( cf ) ) : cf in CompositionFactors( grp ) ];
  else // use the series 1 < O_oo(O^oo(G)) < O^oo(G) < G
    top := SolvableQuotient( grp );
    if #top gt 1 then bot := SolvableResidual( grp );
    else top, _, bot := RadicalQuotient( grp );
    end if;
    if #top gt 1 and #bot gt 1 then return &+[ len( part ) : part in [* top, bot *] ];
    else // oh no! resort to Len
      return 1 + Max( { len( max`subgroup ) : max in MaximalSubgroups( grp ) } );
    end if;
  end if;
end function;

This is much faster than Len above for Alt(8) but still slow on A5 wr A5 which has a large composite insoluble section.  This would be fixed if one could convert the output of CompositionFactors to a form suitable as input for MaximalSubgroups.
Comment: I wrote a version using composition factors and a simple group cache.  It is more complicated, but works on any group I've succeeded at calling CompositionFactors on.  Download: http://www.ms.uky.edu/~jack/2012-06-07-SubgroupLength.m  and then in magma use `Attach("SubgroupLength.m")`
Answer: Here is yet another version. It includes all of Jack's ideas, but it also uses a lazy way of adding up the lengths of the nonabelian composition factors. It performs much faster on example lie $A_5 \wr A_5$. I am sure it could be further improved!
subgroupLengthNew := function( grp )
  len := $$;
  if #grp eq 1 then return 0;
  elif IsSolvable( grp ) then return
      &+[ pn[2] : pn in FactoredOrder( grp ) ];
  elif IsSimple(grp) then return
      1 + Max( { len( max`subgroup ) : max in MaximalSubgroups( grp) } );
  else
    top := SolvableQuotient( grp );
    if #top gt 1 then bot := SolvableResidual( grp );
    else top, _, bot := RadicalQuotient( grp );
    end if;
    if #top gt 1 and #bot gt 1 then
      return &+[ len( part ) : part in [* top, bot *] ];
    else //add up over composition factors
      tot := 0;
      cs := CompositionSeries( grp ); //goes from top down
      for i in [1..#cs-1] do
        ind := Index( cs[i], cs[i+1] );
        fac := Factorisation( ind );
        if IsPrime( ind ) then tot +:= 1;
        else
         //nonabelian simple factor - get perm rep on Sylow normaliser
          if i eq #cs-1 then I :=  cs[i];
          else
            _,pos := Max( [ f[1]^f[2] : f in fac ] );
            S := sub< cs[i] | cs[i+1], Sylow(cs[i], fac[pos][1]) >;
            I := CosetImage( cs[i], Normalizer( cs[i], S ) );
          end if;
          tot +:= len(I);
        end if;
      end for;
      return tot;
    end if;
  end if;
end function;

Computing the length of a finite group


How do I disable fields for a user account?

Question: The site I am developing has 2 type of profiles: the main account, and the alternative account associated with it. The alternative user gets blog posts, forum posts, under its own name. "He-man" and "Frodo" could be two examples.
The main accounts have signature, and image fields that never apply to them because the system always defaults to the alternative account for these things.
Since alternative accounts, and the main accounts both have different roles/permissions, how can I hide these fields using permissions?
I see that http://drupal.org/project/user_picture_field can be used to hide the picture field by setting permissions. How can I hide more than just the picture?
Answer: With the Field Permissions module you can hide fields per role.

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
Features

Enable field permissions on any entity, not just nodes.
Role-based field permissions allowing different viewing patterned based on what access the user has.
Author-level permissions allow viewing and editing of fields based on who the entity owner is.
Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.


How to set the default value of a CCK field

Question: I got a CCK field to select a currency; this field is not required, and the dropdown displays '-None-'. I want to change that.
There's the option to let PHP-Code return the value. It says:
return array(
    0 => array('value' => 'value for value'),
    // You'll usually want to stop here. Provide more values
    // if you want your 'default value' to be multi-valued:
    1 => array('value' => 'value for value'),
    2 => ...
);

So I tried with:
return array(
  0 => array('value' => 'my_text'),
);

Drupal now tells me:
The PHP code for 'default value' returned Array ( [0] => Array ( [value] => my_text ) ) , which is invalid.

I got a list of 4 currencies to choose from, which are the allowed values in my dropdown. What do I have to do to replace '-None-' with my own default?
Answer: In order for you to use PHP you must return a simpler array:
return array(
  'value' => 'my_text'
);

Also, if all you want is to set a default value, you don't need to use the PHP option.

First, define the allowed values (manually or via PHP, doesn't matter)
Then click save
Now click edit to go back to the form. Close to the top there will be a "Default Value" fieldset populated with the allowed values. Just select one!
Comment: Then make the select required? It will have a default so it doesn't matter. If it is not required, then there must be a way to select no value, which in your case is '- None -'.
Comment: This solves just part of my problem. When I add 'my_text' in the allowed values list. I can select it as the default one and it shows up but there is still the '- None -' value which I want to replace by a different one.

It's just the dummy key for non required inputs that I want to replace.
Comment: I actually want a way to select no value but I don't like '- None -'. Is there no way to change it?
Answer: The tip from Alex about doing this without using the PHP option is great. However, remember to set the permissions on the new cck field. Until you have done this, you will not be able to see the "Default Value" box.
.. remembering to do this will save much frustration :-$
Comment: This should really be a comment on the related answer.


$.getJSON fired at last

Question: On my click event, I am trying to open a bootstrap modal. Modal has some values, which I am trying to get from ajax call using  getJSON. Problem is that the getJSON is fired at last when the jQuery function ends.
Here is my code:
$('.poplinks').popover().parent().on('click', '.insert-submission', function () {
            var baKey = 8701;
            var obj;

            $.getJSON('/urltogetobjectwithvalue/', {id: baKey}, function (result) {
                debugger; //it comes here at last after modal('show') executes
                obj = result;
            });

            debugger; //first it come here
            $("#span_unk_sub_baid").html(baKey);
            if (obj !== undefined)
                $("#span_unk_sub_baid").append(' Eff Date: ' + obj.EffectiveDate);

            $('#dialog_ins_purc').modal('show'); //now it will go to $.getJSON
        });

I want to show some values which I am getting from JSON call. After the modal is loaded, then it goes to get values. How to I make sure, json call is made in the same sequence I want. Please help.
Comment: No, it's fired as soon as you call it, *however* since AJAX (Asynchronous Javascript And XML) is asynchronous (you guessed it), it continues the code while waiting for a response, hence it first calls the *callback* when your *server* responds which is after your browser has finished the rest of the anonymous function. Put the code you want to execute when you've gotten the result into your callback (`function (result)`) anonymous function instead and you're good to go.
Comment: possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call)
Answer: JavaScript is an event driven language which means it can work Asynchronously
Ajax - is the way for accessing a server in an asynchronous way.
functions like getJSON works in an async way (using AJAX) - which means that instead of blocking the whole script until it gets the result from the server - it starts an action (in this case requesting a resource from the server) and receives a function to call (usually referred as "callback") whenever some event occur (in this case the request got to its end - i.e. you got the response from the server)
If it was working the way you imagined it should work - there was no need to pass the function like you did and you could instead write:
obj = $.getJSON('/urltogetobjectwithvalue/', {id: baKey}); //WRONG CODE - DON'T USE IT

There is a good explanation about async programming in Javascript (using setTimeout which also works asynchronously) in this question as well
In order to get things in the order that I guess you wanted you should do something like:
$('.poplinks').popover().parent().on('click', '.insert-submission', function () {
    var baKey = 8701;
    var obj;

    function afterResponse(){
        $("#span_unk_sub_baid").html(baKey);
        if (obj !== undefined)
            $("#span_unk_sub_baid").append(' Eff Date: ' + obj.EffectiveDate);
        $('#dialog_ins_purc').modal('show');
    }

    $.getJSON('/urltogetobjectwithvalue/', {id: baKey}, function (result) {
        obj = result;
        afterResponse();
    });
});

Comment: if you have something that you want to happen after you get the result from the server - it should go inside the callback function (or in another function that will be called from the callback function).
I've edit the answer with an example
Comment: what you are suggesting I should be using?
Comment: "function afterResponse()" should be inside the click event or I can put it outside?
Comment: The `baKey` variable lives only inside the function so it must be inside the click handler - if you want to take it out you'll need to take the `baKey` out as well. Same applies for `obj` variable but as opposed to`baKey` you can ignore`obj` easily by sending the result a parameter to the `afterResponse` callback
Comment: can I pass baKey and obj both as parameter to afterResponse callback like afterResponse(obj, baKey)?
Comment: If the server returns them as part of the response you'll get them inside `result`
Answer: Instead of using short hand use
$.ajax({
    type:'GET',
    async:false,
    url:"your url",
    dataType:'JSON',
    data:{id,baKey}
    success:function(result)
    {
      debugger;obj = result;
    }
});

Async is default set to true.So your js executes the code after this ajax call and does not wait for the server to return with a response.If it is set to false js waits for the server to respond back with the data and proceeds with further execution.
Comment: Perhaps use a note that the reason for this is to use `async:false`?
Comment: -1, using a synchronous request will lock the UI, there are better ways to work around it.

$.getJSON fired at last


Set php environment variable for cron via Plesk admin interface

Question: Within our application we make use of a environment variable named SERVER_ENV that is used to set whether we are in a production or development environment.  This is set through the httpd.conf file for apache.  The issue we are having is that using the scheduled task command below set through the Plesk administration interface there is of course no interaction with apache and so the environment variable is not set.
The command used is as follows:
/usr/bin/php -d safe_mode=Off  /var/www/vhosts/example.com/httpdocs/index.php cron file-cleanup

Having spent some time researching it would appear that I could set the variable using:
SERVER_ENV="production"
but I've tried various methods and this does not appear to be picked up.
Can anybody shed any light as to where I can include this within the command string?
Answer: You could try something like
export SERVER_ENV="production"; /usr/bin/php -d ...

which sets the environment variable SERVER_ENV to production which can then bve read by php $server_environment=getenv("SERVER_ENV");
Comment: the export causes the environment variable SERVER_ENV to be passed into the environment of child processes. Without the export your php wouldn't see it.
Comment: that seems to work thanks.  Excuse my stupidity though, could you offer a quick explanation as to what "export" is actually doing here?


Sus chords? Or Ret chords?

Question: We are often seeing 'sus4', where the ^3 is replaced by ^4, which then usually resolves to said ^3.
But there seems to be a 'sus2', which I've always regarded as, in reality, a 'ret2'. That also usually resolves to a regular triad, containing the displaced ^M3.
I feel it ought to have the ret2 name (retarded 2), as it's accurate, although if sus is short for suspended, maybe even sus3 might be more accurate - after all, it's that ^3 that's suspended.
What is actually the correct term, and why?
Comment: This seems like a rant and/or advocacy for "correct" terminology (a statement of opinion) that is thinly disguised as a question. What is the problem you are trying to solve that having an answer from this community will help you solve? It is not only clear that common parlance is that "sus2" is widely used and preferred, it's also clear that **you already know that**. So what is your actual question?
Comment: It doesn't matter what the correct term is, everybody else writes (and understands) 'sus2' (or even just '2')
Comment: @ToddWilcox - the actual question is - what is the correct terminology? For me, it's rhetorical, but I've been wrong before, and would be appreciative to find out more than I already know. Hence the question. Always found the best way to find an answer is to ask a question. Opinion shouldn't be present here.
Comment: So you don't actually already know that the correct terminology is "sus2"? You've "always regarded" sus2 as "ret2", which suggests you've been familiar with the use of "sus2" for some amount of time **and** you know what "sus2" means. Seems like you already know if you want to communicate about a chord of the form C-D-G or similar, you should call it a "sus2" chord to have the greatest chance of being understood.
Comment: Does this answer your question? [Sus2 doesn't exist?](https://music.stackexchange.com/questions/100002/sus2-doesnt-exist)
Comment: The chord is an imposter.
Comment: @PiedPiper - the same as Abm exists instead of G#m in key E? Come on!
Answer: A suspension is a case where a note within the chord is approached from a dissonant note within the chord. In most strict baroque manner such dissonances would in fact need to be prepared, so the dissonance is a note that hangs over from the previous chord.
With the late romantic period we start to see more and more dissonances that are not resolved but rather used as coloring. The term "sus n" in typical Jazz chord notation is a reminiscence to that. sus4 would actually mean that (usually) the third is approached from the 4th. sus2 would mean that the third is approached from the 2nd (or in a more traditional mindset with dissonances always resolving downward the root being approached be the second). But in modern manner these dissonances are not resolved, thus effectively implying a replacement of the chord tone in question.
The term retardation basically means the same thing, just approaching the note from the other side (as strictly we'd want to resolve the suspensions downward). (I think the most typical way to have a retardation would be retarding the resolution of a leading tone.)
In this manner the typical Jazz chord interpretation of a "sus2", that is replacing the third, (1+2+5) would resolve upward. In this sense you are right, and this thing should rather be considered a retardation.
But still that would not be the way to go for multiple reasons:

The terminology suspension has long lost any link to resolution in Jazz harmony, but the resolution is essential for this classification.
Retardation is not really a commonly found term compared to suspension. Many players might barely have heard the term before, so you'd need to argue why it makes sense to use different symbols for essentially the same thing. Introducing a single term for this (you replace the third by the given note) is far more understandable than trying to explain that in this case you need to use this symbol and in this case that one, because of the way things would resolve if thing would resolve.
Having retarded 2nds would invite humorous rascals to have too much fun for their own good.
The type of musical context where terms like "suspension" and "retardation" are used is usually not the same one that uses Jazz chord symbols. So there is no real use to project a naming convention from one onto the other. A convention being "correct" is a bold statement in itself.
I don't like sus2 chords anyway, so let's not call them anything, let's just ignore them (this is a MP reference). For me personally a sus2 chord usually sound like a suspended 4th of the dominant over a tonica as pedal point. But, well, that's a personal reason.

A "sus3" would be particularly weird, for what should that mean in the first place? Are you suspending the third by the third?
Comment: @ToddWilcox - I'm not, at any time, trying to use the word 'retarded' in any sense other than its proper meaning of held back. There's not any, absolutely any subtle implication of the later take on the meaning of the term, which, actually, is still accurate, no matter how it's taken. I don't do PC - it's well overrated, and usually inappropriate.
Comment: I feel like your third bullet point would be more accurate if it were worded to mention how the term in question could be (mis)construed as offensive, especially if used around anyone who isn't familiar with the term. The fact that the most common sense of that word outside of music is offensive is one of the best reasons to all sus2 chords "sus2" or "suspension" - it avoids accidental offense and awkward explanations to non-musicians.
Comment: @ToddWilcox - I can well understand that directed at a *person* it may be deemed offensive, by a lot of folk. But directed at a *chord*? Even I'm not that sensitive! Just using 'ret' should be o.k., like a lot of folk use 'sus' without knowing what it's an abbreviation for.
Comment: "For me personally a sus2 chord usually sound like a suspended 4th of the dominant over a tonic as pedal point. "    You don't listen to a lot of country music then?  :-)
Comment: @Laurence Even in country music, I feel like sus2 and sus4 have similar functions - or really identical functions in most cases, just slightly different sounds.
Comment: @Tim I don't understand your comment. Maybe mine is also not clear. Some people will be offended if they hear or read that word **regardless of the intention of the speaker/writer**. Such people might be paying you for your time or other music professionals whose respect you would like to earn or maintain. Therefore it makes sense to at least consider whether you want to use that word for any reason if there's a chance it might affect your earning potential to use it. Perhaps that's unfair, overrated, or inappropriate, but it's also reality.
Comment: @Tim   That OUGHT to be true.  But some words just trigger, regardless of meaning and context.
Comment: @Laurence - like old age pensioner, which I describe myself as. Apposite, and to the point. We've become soooo sensitive, it seems...
Answer: Usage trumps derivation every time!   The word 'decimate' derives from the practice of taking out one in ten, now it means nine out of ten.   We know what 'crescendo' means musically, but in common parlance 'rise to a crescendo' is so commonly used as to make complaint futile!
Yes, there's a term 'retardation' for an upward suspension.  No, it isn't used in chord symbols.
Answer: If you want to get technical about the naming of chord symbols - suspension versus retardation, passing tone, etc. - then giving just two events...

We are often seeing 'sus4', where the ^3 is replaced by ^4, which then usually resolves to said ^3.

...is not enough information. That two factor description could be the last two stages of a suspension or it could be an appoggiatura or a neighbor tone, etc.
And this gets to the main problem, if it's a problem at all, of the chord symbol labels: the symbols only apply to the vertical stack of tones, not to the movement of those tones. Ex. sus4 is applied when there is a root and a P4 and P5 (and if it's sensible, no third) above the root, regardless of how you approached or departed the P4.
I agree, it would make sense to use ret2 instead of sus2, if the movement of the tones was an actual retardation. But that is only one particular example of how the sus label, in actual use, doesn't fit the technical definition of a suspension.
You could say something similar to add chord labels and various 7, 9, 11, and 13 extension labels. Songbooks frequently use those labels on chords where the tones in question are clearly not chord extensions, but instead are various non-chord tones.

...maybe even sus3 might be more accurate - after all, it's that ^3 that's suspended.

This part seems beside the point, but it's so wrong that it should be addressed.

A suspension has three stages and the actual suspension is the middle event when a tone which had been a chord tone is held, meaning suspended from moving to a chord tone in the next chord.
In the example, it isn't the third of I being suspended, but rather the seventh of V7 is suspended.
Comment: Interesting last point. What I was trying to say was - when something (or someone, for that matter) is suspended, it's not there any more, but in music, has been replaced by something else. Calling it sus4 could be translated as the ^4 moved out, which in fact is just the opposite, particularly from a pedantic's pov. I knw calling it sus3 is useless, but technically, it seems inaccurate. Just something to consider...

Sus chords? Or Ret chords?


How to redirect all node aliases to ?

Question: I created a module with a hook_menu() to redirect every $items[%node] to drupal_goto('<front>'). Is it possible to do the same for every alias path and how would I do that?
The background is that it's a one-pager with all nodes displayed only on the <front> page. No single node should be viewed. Nevertheless every single node has a Facebook Like Button and so has to be like-able/share-able with Facebook. But that's another story, on the whole.
Comment: Might I suggest a different approach? Install [Rabbit Hole](http://drupal.org/project/rabbit_hole) to return a 404 on the full node pages, and set the path of the custom 404 to the front page. That should have exactly the same effect, with a lot less mess
Comment: Yep @koivo Disability Discrimination Act/Section 504/other applicable local law...They're extraordinarily rare in my experience, but it's _your_ head on the block if you fail to advise. Crazy world we live in.
Comment: What @Clive says, plus if you plan to ever be able to cooperate with any kind of government (even at local level) in European Union, you have to have AA accessibility level as defined by w3c. If you will get any income from cooperating with tax-funded institutions it opens a whole new law requirements labyrinth for you. I believe in other areas it's similar now. Side effect: good SEO required by law ;)
Comment: Sounds like you're about to commit SEO-suicide...I'm probably just not getting it but could you explain what you're trying to do in a bit more detail? If you're forwarding all node pages onto the front page, the individual Facebook like buttons will never be available to anyone...
Comment: The individual Facebook Like Button is made available through the view by adding a field for `content: path`and rewrite the result with the Facebook div and inserting a path token as URL.
Comment: I thought that would be too much detail here, but in the end the shared event URL should be called and the caller shall land on the `` with the event toggled by JS.
Comment: Google bot and other robots does not interpret javascript. Not all humans have it turned on in their browsers. It could seriously handicap blind, for example. @Clive is right, it is a SEO suicide, but depending on jurisdiction you are risking discrimination lawsuits too.
Comment: The client doesn't care about SEO and unfortunatley neither about barrier-free internet. The people with JS turned off will simply land on the `` and can read the teasers, that's okay.
Comment: @Clive - Do you mean the alias path by 'full node'?
Comment: @Mołot - Discrimination lawsuits???
Comment: Yep exactly. Be wary that whatever you end up doing here you're going to be fighting with Drupal to some degree, it's not really set up for that sort of workflow without customisation
Answer: Using the Rules module you can implement a rule that looks like so:
{ "rules_redirect_all_node_aliases" : {
    "LABEL" : "Redirect all node aliases",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "my_homepage" } }
    ]
  }
}

It will redirect any path starting with node/ to a path named my_homepage (adapt that path to fit your homepage path).
To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function.
Note: A variation of this rule could be to replace the Rules Condition with something like "if the current path is not my_homepage" (in which case the same Rules Action will redirect to my_homepage.

How to redirect all node aliases to ?


Are weak - strong relations a valid consideration when writing harmony for a given soprano line?

Question: When writing chord progressions for a given soprano line my textbook says that rhythmic considerations will often determine whether one harmony is better or less good than another. Think of a soprano line ^3^2^7^1. You might harmonize it with I V V I or with I ii6 V I. If the ^2 ^7 is in a weak-strong relation however only the second possibility is good. Repeating dominant Harmony will contradict the meter.
Can anyone else tell me if they agree with this? Why does ^7 have to fall on the strong beat and not ^2?
Comment: I'm struggling to imagine how the strong or weak position would make a difference, and much of that is having trouble imagining how that four-note cadence might fit into a meter one way or the other.  Do you have examples you could add?
Answer: While you can harmonize ^3^2^7^1 as both I-V-V-I and I-ii6-V-I and still fit common practice period harmony, using I-V-V-I in any rhythm where the beat ^2 is on is weaker than the beat ^7 is on makes the harmonic rhythm syncopated, which is often not preferred in classical music.
Comment: why? They are both part of V and they are both active tones...
Comment: It's more that I tried imagining a 4-voice chorale measure with Beats 1-4 as ^3^2^7^1, then tried imagining that harmonized with Beats 1-4 as I-V-V-I, and was then struck at how abnormal that sounded.


How can we prove $(a - b)/(c - d) = (b - a)/(d - c)$?

Question: I happened upon a problem where the proposed solution involved switching the order of two subtractions, one in the numerator of a fraction, and one in the denominator of that fraction. That is, it was assumed that $\dfrac{a - b}{c - d} = \dfrac{b - a}{d - c}$, with I suppose the implicit assumption that $c \neq d$.
I don't recall ever seeing a proof of that statement, and when I attempted to search for someone else's proof of it, I couldn't find anything. Although maybe there's a name for this property of subtraction and division that would have produced some better results. I was also unable to quickly prove this on my own.
So I'm wondering how, given $ a, b, c, d \in \Bbb{R}, c \neq d$, how $\dfrac{a - b}{c - d} = \dfrac{b - a}{d - c}$ can be proved. I would also be interested in whether there is a name for this property, and/or a name for the procedure of swapping the order of subtractions like this.
Comment: $(a-b)=-(b-a)$.
Comment: You could also just cross-multiply
Answer: In general we have
$$\frac{\alpha}{\beta}=\frac{k\alpha}{k\beta}$$
where $k \ne 0$ and $\beta \ne 0$, since we just multiply the numerator and the denominator by the same constant.
Here $k=-1, \alpha = a-b, \beta = c-d$.


Conexão HTTP com servidor não retorna os dados JSON

Question: Olá, estou tentando pegar os dados de uma query via HTTP, mas está me retornando esse erro:
org.json.JSONException: End of input at character 0 of

O Código que tenho é esse:
private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(BuscaCAActivity.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tFazendo a busca...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL(minha_url);

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("codigo", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }
    }

    @Override
    protected void onPostExecute(String result) {

        pdLoading.dismiss();
        if(result.equals("no result")) {
            Toast.makeText(BuscaCAActivity.this, getString(R.string.nenhum_resultado), Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);

                    tvTeste.setText(json_data.getString("NRRegistro"));
                    tvTeste2.setText(json_data.getString("DataValidade"));
                    tvTeste3.setText(json_data.getString("Situacao"));
                    tvTeste4.setText(json_data.getString("NRProcesso"));
                }

            } catch (JSONException e) {

                e.printStackTrace();
            }

        }

    }

}

O PHP está assim:
if(isset($_POST['codigo']))
{
      require_once('config.inc.php');
      $search_query=$_POST['codigo'];

      $sql = 'SELECT NRRegistro, DataValidade, Situacao, NRProcesso  FROM tab_cadastro WHERE NRRegistro = :search_query';

      $statement = $connection->prepare($sql);
      $statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
      $statement->execute();
      if($statement->rowCount())
      {
            $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
            header('Content-type: application/json');
            echo json_encode($row_all);

      }
      elseif(!$statement->rowCount())
      {
          echo "no result";
      }
}

Estou há horas tentando achar o erro e não consegui avançar.
O que está errado nesses códigos?
Comment: no doInBackground após todo o processo result tem valor?
Comment: @EdsonReis, na parte de conexão está tudo ok. O problema é na leitura do JSon no servidor. Já testei a instrução sql no phpmyadmin e está certa, então não sei onde está o erro.
Comment: leia o json dentro do doInBackground
Comment: Voce está dando "POST" sendo que você esta esperando um resultado pra montar o seu objeto... não seria "GET"?
Comment: Já tentei com Get também e nada. A codificação, tipo de campo no banco de dados e tabela influencia algo?
Comment: O erro que está acontecendo  diz que nenhum dado esta chegando para montar sua array, seu result é 0 quando monta no onPostExecute().
Comment: Vou postar uma resposta e você diz se funcionou.
Comment: Postei uma resposta, para voce passar para view terá que criar um adapter passando sua lista para a view
Answer: Pode ser que o request não está retornando valor, ou o resultado do seu json não esta passando no método onPostExecute()
Tente separar responsabilidades é boas praticas de programação, fica mais fácil de interpretar código e consertar erros.

Crie uma classe que tem a responsabilidade de fazer o request da sua url e trazer seu json

HttpHandlerHelper
        public class HttpHandlerHelper {

    private static final String TAG = HttpHandlerHelper.class.getSimpleName();
    private static Context context;
    public HttpHandlerHelper(Context context) {
        this.context = context;
    }

    public String Request(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response

            if (200 <= conn.getResponseCode() && conn.getResponseCode() <= 299) {
                InputStream in = new BufferedInputStream(conn.getInputStream());
                response = convertStreamToString(in);
                return response;
            } else {
                InputStream in = new BufferedInputStream(conn.getErrorStream());
                response = convertStreamToString(in);
                return response;
            }

        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }
}

public static  String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

Crie o modelo de data

ModelObjeto
public class ModelObjeto {

public String registro;
public String data_validade;
public String situacao;
public String processo;

public ModelObjeto() {
}

public Atleta(String registro,
              String data_validade,
              String situacao,
              String processo

)
{
    this.registro = registro;
    this.data_validade = data_validade;
    this.situacao = situacao;
    this.processo = processo;

}

public String getRegistro() {
    return registro;
}

public void setRegistro(String registro) {
    this.registro = registro;
}

public String getDataValidade() {
    return data_validade;
}

public void setDataValidade(String data_validade) {
    this.data_validade = data_validade;
}

public String getSituacao() {
    return situacao;
}

public void setSituacao(String situacao) {
    this.situacao = situacao;
}

public String getProcesso() {
    return processo;
}

public void setProcesso(String processo) {
    this.processo = processo;
}

}

Passe a parte que monta seu json em objeto para o doInBackground().
public static class AsyncFetch extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pdLoading.setMessage("\tFazendo a busca...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {

        objetos = new ArrayList<>();

        HttpHandlerHelper handler = new HttpHandlerHelper();
        String json = handler.Request(minha_url);

        if(json != null && json.equals("no result")) {

            try {

                JSONArray jArray = new JSONArray(json);
                for (int i = 0; i < jArray.length(); i++) {

                    JSONObject json_data = jArray.getJSONObject(i);
                    ModelObjeto objeto = new ModelObjeto();

                    objeto.registro = json_data.getString("NRRegistro");
                    objeto.data_validade = json_data.getString("DataValidade");
                    objeto.situacao = json_data.getString("Situacao");
                    objeto.processo = json_data.getString("NRProcesso");

                    objetos.add(objeto);
                }

            } catch (JSONException e) {

                e.printStackTrace();
            }

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        pdLoading.dismiss();

    }

}

Comment: Desculpa a demora. De semana é corrido pra mim. Estou fazendo testes, assim que tiver algum resultado eu volto para postar. Desde já eu agradeço pela ajuda.
Comment: Voltei para agradecer novamente pela ajuda e informar que o problema apresentado neste post estava no arquivo php mesmo. Refiz o código de outra forma e resolveu o problema, tanto por GET quanto por POST. Em relação à sugestão do código acima, tentei utilizá-lo no meu caso mas tenho que fazer alguns ajustes. Creio que se fizer os ajustes necessários ele funcione bem também e de forma até mais correta. De qualquer forma eu agradeço pela atenção.


Probability of getting trump in a card game

Question: I have spent some time playing a 3 person card game called "12" with my family. There are 36 cards in the deck and each player is dealt 12 cards. If you get the queen and the king in the same suit (clubs, hearts, diamonds or spade) you get extra points (I do believe it is called trump?). Let's denote the event "being dealt a king and a queen in the same suit" as $T$. I tried to calculate $P(T>0)$, thinking that it would be an easy thing to do. However, it wasn't. I resolved it by doing $10^7$ Monte-Carlo simulations, resulting in $P(T>0)\approx 0.37$. There must be a more satisfying way of solving this (satisfying in the meaning that I won't be needing Monte-Carlo to solve it). Can you help me?
Do I really have to use the multivariate hypergeometric distribution with five classes (four classes for the suited pairs and one class for the rest of the cards) and go through all combinations that will yield $P(T>0)$ or is there an easier solution?
Comment: Inb4 president joke. This does hint at hypergeometric or multinomial, but I'm not entirely sure.
Answer: You are correct that to use multi-hypergeometric distribution to count. Let $S, H, D, C$ be the event that having KQ in the suits respectively. Then by inclusion-exclusion principle,
$$ \begin{align}
&~ \Pr\{S \cup H \cup D \cup C\} \\
= &~ \binom {4} {1} \frac {\displaystyle \binom {2} {2} \binom {34} {10}} {\displaystyle \binom {36} {12} }
- \binom {4} {2} \frac {\displaystyle \binom {2} {2} \binom {2} {2} \binom {32} {8}} {\displaystyle \binom {36} {12} }
+\binom {4} {3} \frac {\displaystyle \binom {2} {2} \binom {2} {2}\binom {2} {2}\binom {30} {6}} {\displaystyle \binom {36} {12} } \\
&~- \binom {4} {4} \frac {\displaystyle \binom {2} {2} \binom {2} {2}\binom {2} {2}\binom {2} {2}\binom {28} {4}} {\displaystyle \binom {36} {12} } \\
= &~ \frac {339749} {916980} \\
 \approx &~ 0.3705
\end{align}$$
Each term corresponding to the generic case with $1, 2, 3, 4$ pairs of KQ in particular suit, where the leading combinatoric coefficient is counting the number of particular suit combinations for each generic case.
Comment: Great! Thank you very much! Now I will be unbeatable in "12" :-)


Breaking substitution cipher with language model

Question: Frequency analysis is a common tool used to break substitution ciphers, but often relies on intuition and guesswork of a human. Since language models can objectively calculate perplexity (how surprising a piece of language seems), they seem like a good way to formalize this process.
If I could run the calculate the perplexity of the ciphertext under each substitution, I would just pick the one with the lower perplexity. Since this is the least surprising out of the possibilities of the original text, it is likely to be the real original text. However since there are 26^26 different options, doing this with brute force is not possible.
Is there any more efficient way to find the best substitution? In particular, the substitution of letters that minimizes perplexity? This seems to be the same task that gradient descent tries to solve, but the problem here is that I don't think I can calculate the gradient.
Answer: Your question is a good one—and one that cryptographers have thought about a lot. The answer is yes!
First things first: the number of options isn't quite $26^{26}$, because some of those ciphers wouldn't be invertible. For instance, you could map every letter to Q, but how do you decode that? So the number is only(!) $26!$ possibilities.
That's still astronomically large, but human cryptographers can break these codes from just a few examples. What's the trick? They look at relative frequencies of letters and what makes for natural plaintext.

This seems to be the same task that gradient descent tries to solve…

Well, you've got a point that we'd like to optimize something. We can use some form of local search to improve the goodness of our mapping.
One method proposed for this is described in Hasinoff (2003); I think the paper is pretty approachable compared to a lot of the neural LM based papers coming out for this problem. To optimize, they use a popular technique called hill-climbing. (More specifically, stochastic hill climbing with random restarts—they never mention hill climbing in the paper, though.) The idea is to start with some initial (arbitrary) mapping and measure its perplexity as you suggested. Then loop to improve the perplexity. Pick some pair of letters and swap their mapping. Did this version reduce perplexity? If so, keep it. If not, don't. Now make another swap, and so on, and so on.


Selecting more then one column when groupBy is present (db_select) - Drupal 8 added 'ONLY_FULL_GROUP_BY'

Question: In my custom Drupal 8 plug-in I perform such query:
$select = db_select('my_table', 'e');
$select->addField('e', 'field1');

$select->condition('field3', 'NULL', '!=');
$select->condition('field4', array(11, 12, 31, 32, 33), 'IN');

$select->groupBy("e.field1");
$select->orderBy("e.field1");
$select->orderBy("e.field5");
$entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC);

And it works fine. It returns me all records grouped by field1 that meets the condition, orderered. But it returns only field1 column.
I wanted to get more columns, so I have added another $select->addField('e', 'field2'); just after first one:
$select = db_select('my_table', 'e');
$select->addField('e', 'field1');
$select->addField('e', 'field2');

$select->condition('field3', 'NULL', '!=');
$select->condition('field4', array(11, 12, 31, 32, 33), 'IN');

$select->groupBy("e.field1");
$select->orderBy("e.field1");
$select->orderBy("e.field5");
$entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC);

This time I get error:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42000]: Syntax error or access violation: 1055 Użyto 'my_database.e.field2' bez umieszczenia w group by:

Which means "my_database.e.field2 has been used without putting in into group by". But I don't want to group by every column I select.
Unfortunatelly Drupal 8 added ONLY_FULL_GROUP_BY :(
Then, how can I use groupBy and select more then one column at the same time?
Answer: I had a similar issue just a few days ago, and the only way to solve it was to add another groupBY query for the extra addField for the e, field2 column:
$select->groupBy("e.field2");

But, both of my groupBY where similar datas, in my case, in one field it was a date in word format (11th July 2016) and the other field group, the data was in epoch time, to help ascend or descend my table.
Comment: It's kind of workaround, but it changes the result. In my case I get 15k rows instead of 500, most of them are redundant for me (same `e.field1`, different `e.field2`).
Answer: This is pretty annoying, but it is to provide cross database compatibility for Drupal.  You can get around it by adding the following to your database connection array if you only ever intend to live in MySQL compatible land:
'init_commands' => [
  'sql_mode' => "SET sql_mode = 'ANSI,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER'",
],

But I haven't yet figured out how to disable in my Kernel tests.  Still getting something like "PDOException: SQLSTATE[42000]: Syntax error or access violation: 1055 'local.nfd.title' isn't in GROUP BY"
Answer:
Which means "my_database.e.field2 has been used without putting in into group by". But I don't want to group by every column I select.

Whether or not you want it is not relevant in this case. Drupal enforces a stricter SQL mode in MySQL which requires exactly this. Every selected column must either be part of groupBy or you must use a function like count(), max(), group_concat() or similar to define what value you want.
MySQL out of the box tries to be nice and just returns an arbitrary field2 value for each group but there is no guarantee that it is actually the value you want, other database backends do not.
Comment: one calls it "feature", another one "limit". Personally, I don't like "forced help" in "only good direction" - I want to choose it or not depending on my situation - and the way Drupal "helps" caused many D7 queries to fail suddenly on D8. Anyway, thank you for the link to `ANY_VALUE()`! :)
Comment: In other words, Drupal limits my possibilities by forcing strict SQL mode (I am aware that returned data will be arbitrary / belongs to one of grouped entities, without guarantee from which one it has been taken -  and I am more then ok with that in my plugin). Is there a way to turn it of and still use Drupal? Maybe turn it off for single query?
Comment: No, Drupal doesn't limit your possibilities, it just forces you to write correct SQL. This new settings is enabled by default in newer MySQL versions, Drupal makes sure that code you write with one version doesn't suddenly fail on another server. And the documentation on all this is very good https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html, for example mentiones an ANY_VALUE() function that you can use with addExpression() .


Update a sprite's height in cocos2d

Question: I need to scale a sprite's height exactly to a fixed value. I don't think the function scaleBy() or scaleTo() could help. Please help me to figure it out.
Answer: Each CCSprite object has properties for the scale, scaleX and scaleY. In your case, you should use the scaleY property and do some simple maths :
sprite.scaleY = DESIRED_HEIGHT/sprite.contentSize.height;

But you have to make sure that your desired height is in float, otherwise you might get some issues, like always having 0 or 1 as a result!
If you want to animate it, you can also use the CCScaleTo action like this :
float scaleY = DESIRED_HEIGHT/sprite.contentSize.height;
[sprite runAction:[CCScaleTo actionWithDuration:duration scaleX:sprite.scaleX scaleY:scaleY]];

Hope this helps!

Update a sprite's height in cocos2d


How to use Google Photos API Method: mediaItems.search in Google apps script for a spreadsheet

Question: I really tried to figure this out on my own...
I am trying to load photo metadata from google photos into a sheet using the Google Photos API and google apps script.
I was able to make some progress after a lot of help on a previous question
Is it possible to load google photos metadata into google sheets?
I now have two functions.
function photoAPI_ListPhotos() - Uses Method: mediaItems.list and gives me all my photos that are not archived
function photoAPI_ListAlbums() - Uses Method: albums.list and gives me all my albums
What I want to do is retrieve all photos from a specific album. Method: mediaItems.search should do this but it uses the POST protocol and the previous working examples I found only use GET. Looking at the examples available on that page, there is a javascript portion but it does not work in apps script.
The documentation for UrlFetchApp tells me how to format a POST request but not how to add the parameters for authentication.
The external APIs also is not giving me the examples I am looking for.
I feel like I'm missing some essential tiny piece of info and I hope I'm not wasting everyone's time asking it here. Just a solid example of how to use POST with oauth in apps script should get me where I need to go.
Here is my working function for listing all non-archived photos.
function photoAPI_ListPhotos() {
  /*
  This function retrieves all photos from your personal google photos account and lists each one with the Filename, Caption, Create time (formatted for Sheet), Width, Height, and URL in a new sheet.
  it will not include archived photos which can be confusing if you happen to have a large chunk of archived photos some pages may return only a next page token with no media items.

  Requires Oauth scopes. Add the below line to appsscript.json
  "oauthScopes": ["https://www.googleapis.com/auth/spreadsheets.currentonly", "https://www.googleapis.com/auth/photoslibrary", "https://www.googleapis.com/auth/photoslibrary.readonly", "https://www.googleapis.com/auth/script.external_request"]

  Also requires a standard GCP project with the appropriate Photo APIs enabled.
  https://developers.google.com/apps-script/guides/cloud-platform-projects
  */

  //Get the spreadsheet object
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  //Check for presence of target sheet, if it does not exist, create one.
  var photos_sh = ss.getSheetByName("photos") || ss.insertSheet("photos", ss.getSheets().length);
  //Make sure the target sheet is empty
  photos_sh.clear();
  var narray = [];

  //Build the request string. Max page size is 100. set to max for speed.
  var api = "https://photoslibrary.googleapis.com/v1/mediaItems?pageSize=100";
  var headers = { "Authorization": "Bearer " +  ScriptApp.getOAuthToken() };
  var options = { "headers": headers, "method" : "GET", "muteHttpExceptions": true };

  //This variable is used if you want to resume the scrape at some page other than the start. This is needed if you have more than 40,000 photos.
  //Uncomment the line below and add the next page token for where you want to start in the quotes.
  //var nexttoken="";

  var param= "", nexttoken;
  //Start counting how many pages have been processed.
  var pagecount=0;

  //Make the first row a title row
  var data = [
    "Filename",
    "description",
    "Create Time",
    "Width",
    "Height",
    "ID",
    "URL",
    "NextPage"
  ];
  narray.push(data);

  //Loop through JSON results until a nextPageToken is not returned indicating end of data
  do {
    //If there is a nextpagetoken, add it to the end of the request string
    if (nexttoken)
      param = "&pageToken=" + nexttoken;

    //Get data and load it into a JSON object
    var response = UrlFetchApp.fetch(api + param, options);
    var json = JSON.parse(response.getContentText());

    //Check if there are mediaItems to process.
    if (typeof json.mediaItems === 'undefined') {
      //If there are no mediaItems, Add a blank line in the sheet with the returned nextpagetoken

      //var data = ["","","","","","","",json.nextPageToken];
      //narray.push(data);
    } else {
      //Loop through the JSON object adding desired data to the spreadsheet.
      json.mediaItems.forEach(function (MediaItem) {

        //Check if the mediaitem has a description (caption) and make that cell blank if it is not present.
        if(typeof MediaItem.description === 'undefined') {
            var description = "";
          } else {
            var description = MediaItem.description;
          }

        //Format the create date as appropriate for spreadsheets.
        var d = new Date(MediaItem.mediaMetadata.creationTime);

        var data = [
          MediaItem.filename,
          "'"+description, //The prepended apostrophe makes captions that are dates or numbers save in the sheet as a string.
          d,
          MediaItem.mediaMetadata.width,
          MediaItem.mediaMetadata.height,
          MediaItem.id,
          MediaItem.productUrl,
          json.nextPageToken
        ];
        narray.push(data);
      });
    }

    //Get the nextPageToken
    nexttoken = json.nextPageToken;

    pagecount++;
    //Continue if the nextPageToaken is not null
    //Also stop if you reach 400 pages processed, this prevents the script from timing out. You will need to resume manually using the nexttoken variable above.
  } while (pagecount<4 && nexttoken);

    //Continue if the nextPageToaken is not null (This is commented out as an alternative and can be used if you have a small enough collection it will not time out.)
  //} while (nexttoken);

  //Save all the data to the spreadsheet.
  photos_sh.getRange(1, 1, narray.length, narray[0].length).setValues(narray);
}

Answer:
You want to retrieve all photos of the specific album using Google Photo API.
You want to know how to use the method of mediaItems.search using Google Apps Script.
You have already been able to retrieve the data using Google Photo API.

If my understanding is correct, how about this sample script? Please think of this as just one of several answers.
Sample script 1:
var albumId = "###"; // Please set the album ID.

var headers = {"Authorization": "Bearer " + ScriptApp.getOAuthToken()};
var url = "https://photoslibrary.googleapis.com/v1/mediaItems:search";
var mediaItems = [];
var pageToken = "";
do {
  var params = {
    method: "post",
    headers: headers,
    contentType: "application/json",
    payload: JSON.stringify({albumId: albumId, pageSize: 100, pageToken: pageToken}),
  }
  var res = UrlFetchApp.fetch(url, params);
  var obj = JSON.parse(res.getContentText());
  Array.prototype.push.apply(mediaItems, obj.mediaItems);
  pageToken = obj.nextPageToken || "";
} while (pageToken);
Logger.log(mediaItems)

At the method of mediaItems.search, albumId, pageSize and pageToken are included in the payload, and the values are sent as the content type of application/json.

Sample script 2:
When your script is modified, how about the following modified script?
function photoAPI_ListPhotos() {
  var albumId = "###"; // Please set the album ID.

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var photos_sh = ss.getSheetByName("photos") || ss.insertSheet("photos", ss.getSheets().length);
  photos_sh.clear();
  var narray = [];
  var api = "https://photoslibrary.googleapis.com/v1/mediaItems:search";
  var headers = { "Authorization": "Bearer " +  ScriptApp.getOAuthToken() };
  var nexttoken = "";
  var pagecount = 0;
  var data = ["Filename","description","Create Time","Width","Height","ID","URL","NextPage"];
  narray.push(data);
  do {
    var options = {
      method: "post",
      headers: headers,
      contentType: "application/json",
      payload: JSON.stringify({albumId: albumId, pageSize: 100, pageToken: nexttoken}),
    }
    var response = UrlFetchApp.fetch(api, options);
    var json = JSON.parse(response.getContentText());
    if (typeof json.mediaItems === 'undefined') {
      //If there are no mediaItems, Add a blank line in the sheet with the returned nextpagetoken

      //var data = ["","","","","","","",json.nextPageToken];
      //narray.push(data);
    } else {
      json.mediaItems.forEach(function (MediaItem) {
        if(typeof MediaItem.description === 'undefined') {
            var description = "";
          } else {
            var description = MediaItem.description;
          }
        var d = new Date(MediaItem.mediaMetadata.creationTime);
        var data = [
          MediaItem.filename,
          "'"+description,
          d,
          MediaItem.mediaMetadata.width,
          MediaItem.mediaMetadata.height,
          MediaItem.id,
          MediaItem.productUrl,
          json.nextPageToken
        ];
        narray.push(data);
      });
    }
    nexttoken = json.nextPageToken || "";
    pagecount++;
  } while (pagecount<4 && nexttoken);
  photos_sh.getRange(1, 1, narray.length, narray[0].length).setValues(narray);
}

Note:

This script supposes as follows.

Google Photo API is enabed.
The scope of https://www.googleapis.com/auth/photoslibrary.readonly or https://www.googleapis.com/auth/photoslibrary are included in the scopes.

Reference:

Method: mediaItems.search

If I misunderstood your question and this was not the result you want, I apologize.
Comment: Thank you!! that is exactly what I needed. I was stuck on how to format the `var options` my project is working perfectly now.
Comment: @Isaac Guerrero Thank you for replying. I'm glad your issue was resolved.


Proof regarding homogeneous functions of degree $n$

Question: If $f$ is homogeneous of degree $n$, show that $f_{x}(tx,ty) = t^{n-1}f_{x}(x,y)$.
My attempt at a solution:
Let $u = tx$ and $v = ty$.$$\frac{\partial f(u,v)}{\partial x} = \frac{\partial f(u,v)}{\partial u}\frac{\partial u}{\partial x} + \frac{\partial f(u,v)}{\partial v}\frac{\partial v}{\partial x}.$$ But $\frac{\partial u}{\partial x} = t$ and $\frac{\partial v}{\partial x} = 0.$ Hence,
        $$t\frac{\partial f(u,v)}{\partial u} = t^{n}f_{x}(x,y)$$ or $$\frac{\partial f(u,v)}{\partial u} = t^{n-1}f_{x}(x,y).$$ How do I get from the term on the left hand side to $\frac{\partial f(u,v)}{\partial x}$? Thank you in advance.
Comment: https://math.stackexchange.com/questions/977677/property-of-homogeneous-functions-in-two-variables
Answer: $\frac {\partial f(u,v)}{\partial u}$ means partial derivative with respect to the first variable, which is also denoted by $f_x(u,v)$. Here the subscript $x$ denotes that the partial derivative is with respect to the first variable $u=tx$ and not $x$ itself. So in our case $\frac {\partial f(u,v)}{\partial u}=f_x(u,v)=f_x(tx,ty)=t^{n-1}f_x(x,y)$ and you are already done.


Keras model accuracy is not improving - Image Classification

Question: I have 4 classes and building a Keras model for image classification problem. I have tried a couple of adjustments but accuracy is not going beyond 75% and still loss is 64%.
I have 90,400 images as a training set and 20,000 images for testing.
Here is my model.
model = Sequential()
model.add(Conv2D(32, kernel_size = (3, 3),input_shape=(100,100,3),activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(64, activation = 'relu'))
model.add(Dropout(0.5))
model.add(Dense(4, activation = 'softmax'))
model.compile(loss = 'sparse_categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])

batch_size = 64

train_datagen = ImageDataGenerator (rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
test_datagen=ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory('/dir/training_set', target_size=(100,100),batch_size=batch_size,class_mode='binary')

test_set = test_datagen.flow_from_directory('/dir/test_set',target_size=(100,100), batch_size=batch_size, class_mode='binary')

# 90,400 images I have under the training_set directory and 20,000 under the test directory.

model.fit(training_set, steps_per_epoch=90400//batch_size, epochs=1,validation_data=test_set, validation_steps= 20000//batch_size)

I tried adjusting layers and dropouts but no luck. Any ideas?
Comment: Did you increase the number of epochs?
Comment: see my answer to similar question at https://stackoverflow.com/questions/66908216/low-accuracy-on-convolutional-neural-network-with-tensorflow-and-keras/66909868#66909868
Comment: @gtancev Yes, I tried that already, same results.
Answer: If I encounter something like this, I would do following:

Split my data into training-validation and test. Improve model by validation and use test to see final result.

Removing Dropout layers since I don't have a proof that model is overfitted.

If model is underfitted (your case),
3.a. Try different / bigger architecture and searching better hyperparameters
3.b. Training longer and try different optimization algorithms

If model is overfitted,
4.a. Try to get more data
4.b. Regularization (L2, dropout etc.)
4.c. Data augmentation
4.d. Searching better hyperparameters

Note: You can always consider transfer learning. Basically, transfer leaning is using gained information from a successful model for your model.
Comment: I may have to try a different algorithm, removing dropouts didn't help. The same model I am using for the binary problem with sigmoid and getting 90% accuracy. I am wondering why it's not working for multiple classe problem.
Comment: This is what I have for binary problem.

model = Sequential()
model.add(Conv2D(32, kernel_size = (3, 3),input_shape=(64,64,3),activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())

model.add(Dense(128, activation = 'relu'))
model.add(Dropout(0.5))
model.add(Dense(4, activation = 'sigmoid'))
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
Comment: Classifying two image group is going to be much easier. I'd expect that result. One reason of low accuracy could be imbalanced data. Or two or more classes of your data have strong commonality. So your model get confused. Did you check the confusion matrix of the result? Sometimes the problem is not the model itself.
Comment: No, I haven't check the confusion matrix, good suggestion let me check.
Comment: As I said the reason could be imbalanced data too
Answer: You could try using one of the existing models in Keras and train it from scratch.
I have used MobileNetV2 in the past and have gotten very good results.
When you initialize the model you can load pre-trained weights or None, and start traning from scratch with your images.
Answer: Consider

Adding multiple convolutional layers (with Max pooling in between) enables the model to learn "low level" and "higher level" features
Adding more epochs to enable the model to learn from the input pictures. Neural Networks only learn "a little bit" along the gradient each time, it often takes multiple up to many epochs to have a sufficiently trained model.

Maybe start with less pictures but increase the epochs (and add a second conv/max pool pair) to keep calculation time under control!
Comment: Thanks for your time, let me try that.
Answer: I was able to achieve accuracy with transfer learning using the pre-trained MobileNet model.
Attaching my code and confusion metrix here so it may be helpful to someone.
import pandas as pd
import numpy as np
import os
import keras
import matplotlib.pyplot as plt
from keras.layers import Dense,GlobalAveragePooling2D
from keras.applications import MobileNet
from keras.preprocessing import image
from keras.applications.mobilenet import preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.optimizers import Adam

base_model=MobileNet(weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(3,activation='softmax')(x) #final layer with softmax activation

model=Model(inputs=base_model.input,outputs=preds)

for layer in model.layers[:20]:
    layer.trainable=False
for layer in model.layers[20:]:
    layer.trainable=True

train_data_path = '../train_dataset_path'

train_datagen=ImageDataGenerator(preprocessing_function=preprocess_input, validation_split=0.2) #included in our dependencies

train_generator=train_datagen.flow_from_directory(train_data_path,
                                                 target_size=(224,224),
                                                 color_mode='rgb',
                                                 batch_size=32,
                                                 class_mode='categorical',
                                                 shuffle=True,
                                                 subset='training')

test_generator=train_datagen.flow_from_directory(train_data_path,
                                                 target_size=(224,224),
                                                 color_mode='rgb',
                                                 batch_size=32,
                                                 class_mode='categorical',
                                                 shuffle=False,
                                                 subset='validation')

model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])

step_size_train = train_generator.n//train_generator.batch_size
step_size_test  = test_generator.n//test_generator.batch_size

model_history = model.fit(train_generator,
                          steps_per_epoch=step_size_train,
                          epochs=5,
                          validation_data=test_generator,
                          validation_steps=step_size_test)

model.save('tl_interior_model_2')

#Load the model
model = keras.models.load_model('tl_interior_model_2')


What factors decide the number of executors in a stand alone mode?

Question: Given a Spark application

What factors decide the number of executors in a stand alone mode? In the Mesos and YARN according to this documents, we can specify the number of executers/cores and memory.
Once a number of executors are started. Does Spark start the tasks in a round robin fashion or is it smart enough to see if some of the executors are idle/busy and then schedule the tasks accordingly.
Also, how does Spark decide on the number of tasks? I did write a simple max temperature program with small dataset and Spark spawned two tasks in a single executor. This is in the Spark stand alone mode.
Answer: Answering your questions:

The standalone mode uses the same configuration variable as Mesos and Yarn modes to set the number of executors. The variable spark.cores.max defines the maximun number of cores used in the spark Context. The default value is infinity so Spark will use all the cores in the cluster. The spark.task.cpus variable defines how many CPUs Spark will allocate for a single task, the default value is 1. With these two variables you can define the maximun number of parallel tasks in your cluster.
When you create an RDD subClass you can define in which machines to run your task. This is defined in the getPreferredLocations method. But as the method signatures suggest this is only a preference so if Spark detects that one machine is not busy, it will launch the task in this idle machine. However I don't know the mechanism used by Spark to know what machines are idle. To achieve locality, we (Stratio) decided to make each Partions smaller so the task takes less time and achieve locality.
The number of tasks of each Spark's operation is defined according to the length of the RDD's partitions. This vector is the result of the getPartitions method that you have to override if you want to develop a new RDD subClass. This method returns how a RDD is split, where the information is and the partitions. When you join two or more RDDs using, for example, union or join operations, the number of tasks of the resulting RDD is the maximum number of tasks of the RDDs involved in the operation. For example: if you join RDD1 that has 100 tasks and RDD2 that has 1000 tasks, the next operation of the resulting RDD will have 1000 tasks. Note that a high number of partitions is not necessarily synonym of more data.

I hope this will help.
Comment: Inspite of setting the num-executors parameter, the standalone mode always used one executor.
Comment: Apparently spark standalone ignores the spark.cores.max setting
Answer: I agree with @jlopezmat about how Spark chooses its configuration. With respect to your test code, your are seeing two task due to the way textFile is implemented. From SparkContext.scala:
  /**
   * Read a text file from HDFS, a local file system (available on all nodes), or any
   * Hadoop-supported file system URI, and return it as an RDD of Strings.
   */
  def textFile(path: String, minPartitions: Int = defaultMinPartitions): RDD[String] = {
    hadoopFile(path, classOf[TextInputFormat], classOf[LongWritable], classOf[Text],
      minPartitions).map(pair => pair._2.toString)
  }

and if we check what is the value of defaultMinPartitions:
  /** Default min number of partitions for Hadoop RDDs when not given by user */
  def defaultMinPartitions: Int = math.min(defaultParallelism, 2)

Comment: Thanks Daniel - When I loaded the small file from HDFS, the number of partitions were default two (RDD.getNumPartitions()) as you mentioned. So, two tasks were started one for each partition and so two files in HDFS. I did a coalesce(1) and the number of files in the output was 1.
Answer: Spark chooses the number of tasks based on the number of partitions in the original data set.  If you are using HDFS as your data source, then the number of partitions with be equal to the number of HDFS blocks, by default.  You can change the number of partitions in a number of different ways.  The top two: as an extra argument to the SparkContext.textFile method; by calling the RDD.repartion method.
Comment: I have put a file of 5 blocks and see 5 tasks is Spark. Looks like for one block two partitions are created. For more than one block, the same number of partitions are created.
Answer: Answering some points that were not addressed in previous answers:

in Standalone mode, you need to play with --executor-cores and --max-executor-cores to set the number of executors that will be launched (granted that you have enough memory to fit that number if you specify --executor-memory)
Spark does not allocate task in a round-robin manner, it uses a mechanism called "Delay Scheduling", which is a pull-based technique allowing each executor to offer it's availability to the master, which will decide whether or not to send a task on it.


how to get array of sentences and words passing as parameter to a function in javascript?

Question: I have a function say
 var init = function(data){
     all sentences: " I have to get all the sentences and return an array containing all sentences"
     all words : "this method should return an array of words in 'Data' when there is no parameter passed in. Optionally, when there is a parameter passed in that is a number, return the words in the sentence indicated by the input parameter"

     all reverse sentences: "this method is the same as all Sentences, except it should return the sentences in reverse order"

     reverse words :" same as all words but in reverse order"
     countWordsBeginningWith:" this method should return the amount of words that begin with an inputted string. The optional second parameter should determine what sentence the words come from when present."

thanks
Comment: @paul: Please do not tell people not to speak, jnpcl was asking a valid question. -1 for lip, and for a question that differs from your comment clarification entirely.
Comment: What exactly are you asking to do here?
Comment: I have a similar kind of situation where I have to pass a complex object to my function ....I have a working code with me ...just want to see if I can optimize it.....@jnpcl this is not a homework (if you don't have any advice , please don't speak) ...in my situation i have to get a JSON object coming from the server and I have to access particular key from it and have to manipulate ..not worried about the JSON object but manipulating it efficiently is a problem...
Comment: @Paul - Your question sounds nothing like your comment. Just for the record.
Comment: @Orbling - i agre with you the OP was not asking the question properly. that's all. +1
Comment: Great! instead of providing suggestion you guys argue on  how to ask question...anyways thanks for your valuable comments....@Orbling thanks for negative vote
Comment: @paul: No problem.  I do not down vote lightly, your conduct was not what we expect in the community - especially rolling back an edit that purely fixed layout to a broken variant.  If you have a sensible question then by all means state it, try not to withhold context and details otherwise it does not help answerers.
Comment: @Orbling I have used the community for long and never faced that kind of arguments. Its not what I expect instead of providing suggestion..for your record any question is relevant and instead of asking whether its your homework kind of things is not at all relevant in this context ...instead of wasting time I prefer should provide suggestion and if not shouldn't ask some irrelevant question which doesn't belongs to the context of the problem...
Comment: @paul: [Homework questions have a slightly different policy](http://meta.stackexchange.com/questions/10811/how-to-ask-and-answer-homework-questions) to regular questions, and are supposed to be marked as such.  Answerers are expected to answer the questions slightly differently, guiding the student in the right direction rather than just answering the question fully.  For obvious reasons.  When questions look contrived, as in they are most likely exercises, it is standard practice to query that, in order that appropriate steps can be taken.
Comment: @paul: Also, what you prefer in the way of answers and comments is not entirely relevant either.  People choose to answer or comment as they see fit, providing they are polite you should respect that and act equally politely, answering their queries if possible.  After all, they are taking the time to assist your question.  Telling them to be quiet is bad form.  If you answered questions as much as asking them, you would probably respect that.
Comment: @Orbling ...thanks for letting me know about the policies...not aware of that...anyways lesson learned..
Comment: @paul: Good, I'm glad.  Apologies for any annoyance caused.
Comment: @Orbling...I should be the one apologies for my words...keep up the good work ...
Answer: I think what you need to do is decompose your argument (assuming it's a string) into an array. For instance:
function getAllWords(sentences) {
    var result = sentences.split(' ');
    return result;
}

var init = function(data){
    var result = [];
    result['words'] = getAllWords(data.text);
    // result['sentences'] = getAllSentences(data.text);
    // result['sentencesreversed'] = getReverseSentences(data.text);
    // result['sentencewords'] = getReverseWords(data.text);
    // result['beginswith'] = getWordsBeginningWith(data.text, data.beginswith);
    return result;
}

var getIt = {
    'beginswith': 't',
    'text': 'This is stuff. I am a sentence. Stuff happens now.'
};

console.log(init(getIt));

This is a very simplistic answer, not taking into account for periods, commas, and other bits. But that's the general answer. Some for loops and/or RegEx's may occur after this point, buyer beware.
Comment: @Paul - You might read here: http://www.quirksmode.org/js/associative.html Objects and arrays are the same in Javascript, which is probably unusual. The notation used to reference them are interchangeable, and if not, I hope someone corrects me.
Comment: thanks for the link...for information objects and arrays are not same ...they are different primitives in JS...though you can loop through for in in array too like object literal..
Comment: **primitive, primitive value** - "JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined"; **object** - "All objects are derived from Object, *including arrays*, and Object itself is also an object." - https://developer.mozilla.org/En/JS/Glossary
Answer: In Javascript you can pass any data structure as a function parameter.
First learn how to construct an array of strings to contain you word or sentences. Once you have accomplished this it will be straightforward.


How to run an ".exe" file from "C:\Program Files (x86)" using python?

Question: Context: Basically I want to create a python program that asks me what Software I want to run, as soon as I start my computer.
Usefull code: os.chdir(r'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'). And that's the error I got :

FileNotFoundError                         Traceback (most recent call last)
   in ()
  ----> 1 os.chdir(r"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'")

FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden: "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'"
The translation for "Das System kann die angegebene Datei nicht finden:" is the system was unable to find the file.
Problem: My problem is that I can't run any ".exe", or any type of files, because of the white spaces in "C:\Program Files (x86) ", so my question would be how can I bypass that? / What could I use to make it work?
PS: I searched, on various forums, but this problem doesn't seem to be very common... Or I didn't search enough.
Answer: Use os.system() or give a folder path to change dir in os.chdir() not an executable file (why would you want to change into an executable? You can't do that)
Comment: ok thanks for the quick answer. I'm going to try this, I fund the `os.chdir()` on the internet, and quickly checked what it did, actually it opened files, so I thought that's what I need :,)
Comment: It does not open files, some other code did. It changes working dir only.