android sqlite no such table error (code 1)

Question: when I press the button for list database items I get this error. where is my fault? ( when I look DDMS I see exDB file in device storage ??)

VT_baglanti3 class
public class VT_baglanti3 extends SQLiteOpenHelper {

  // DataBase oluşturma
  private static final String VT="exDB"; // veri tabanı adi
  private static final Integer SURUM=1;  // veri tabanı sürümü

  public VT_baglanti3(Context c) {
    super(c, VT, null, SURUM); // yukarıda tanımlanan değişkenleri parametre olarak verdik.

  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    // tablo ekleme
      db.execSQL("CREATE TABLE IF NOT EXISTS EMP_TABLE(_id integer primary key,E_NAME text,E_AGE text,E_DEPT text)");
  }

  @Override
  public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

  }
}

F_tarif_yaz class
public class F_tarif_yaz extends Fragment {

  private View root;

  Context con;

  private VT_baglanti3 db;
  private TextView txt;
  Button bt;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    root = inflater.inflate(R.layout.tarif_yaz, container, false);
    con=inflater.getContext();

    db=new VT_baglanti3(con);
    txt=(TextView)root.findViewById(R.id.txt);
    bt=(Button)root.findViewById(R.id.bt);

    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Listele2();
        }
    });

    return root;
  }

  private void Listele2(){
    String sutunlar[]={"E_NAME","E_AGE","E_DEPT"};
    SQLiteDatabase sldb2=db.getReadableDatabase();

    Cursor cursor1=sldb2.query("exDB",sutunlar,null,null,null,null,null);

    String tumbilgi="";

    while (cursor1.moveToNext()){
        String adbilgi=cursor1.getString(cursor1.getColumnIndex("E_NAME"));

       String soyadbilgi=cursor1.getString(cursor1.getColumnIndex("E_AGE"));
        String nobilgi=cursor1.getString(cursor1.getColumnIndex("E_DEPT"));

        tumbilgi += adbilgi + " " + soyadbilgi + " " + nobilgi + " " + "\n";

    }
    txt.setText(tumbilgi);
  }
}

Error log
/com.yeni E/AndroidRuntime: FATAL EXCEPTION: main
                                                    Process: com.yeni, PID: 1442
                                                    android.database.sqlite.SQLiteException: no such table: exDB (code 1): , while compiling: SELECT E_NAME, E_AGE, E_DEPT FROM exDB
                                                        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                        at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                                                        at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                        at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
                                                        at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
                                                        at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
                                                        at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
                                                        at com.yeni.F_tarif_yaz.Listele2(F_tarif_yaz.java:50)
                                                        at com.yeni.F_tarif_yaz.access$000(F_tarif_yaz.java:15)
                                                        at com.yeni.F_tarif_yaz$1.onClick(F_tarif_yaz.java:39)
                                                        at android.view.View.performClick(View.java:4438)
                                                        at android.view.View$PerformClick.run(View.java:18422)
                                                        at android.os.Handler.handleCallback(Handler.java:733)
                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                        at android.os.Looper.loop(Looper.java:136)
                                                        at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                        at java.lang.reflect.Method.invokeNative(Native Method)
                                                        at java.lang.reflect.Method.invoke(Method.java:515)
                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                        at dalvik.system.NativeStart.main(Native Method)

Error lines
com.yeni.F_tarif_yaz.Listele2(F_tarif_yaz.java:50)   at                        Cursor cursor1=sldb2.query("exDB",sutunlar,null,null,null,null,null);

Comment: "table" and "database" are two different things. The error message is very clear about it.
Comment: `CREATE TABLE IF NOT EXISTS EMP_TABLE` and `SELECT E_NAME, E_AGE, E_DEPT FROM exDB`. Those query do not match. `"exDB"` will be the database ( file in SQlite) name
Answer:
DDMS i see exDB file in device storage

There's no TABLE named exDB in your database. File name of your sqlite database is completely irrelevant.
See: https://sqlite.org/lang_createtable.html


Multitenant grails plugin - grails.plugin.multitenant.core.exception.NoCurrentTenantException

Question: Grails giving this error when i saved an instance which is associated with @multitenant annotation but no tenant is present there. So i explicitly try to put tenant id by using
objInstance.setTenantId(tenantId)

throws this exception :
grails.plugin.multitenant.core.exception.NoCurrentTenantException: Tried to save multi-tenant domain class 'objInstance', but no tenant is set

When i use
Customer.withTenantId(tenantId){ objInstance.save(flush:true) }

then it throws this exception :
org.springframework.orm.hibernate3.HibernateSystemException: illegally attempted to associate a proxy with two open Sessions; nested exception is org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions

CONTROLLER CODE :
def myservice
def myAction(MOrder objInstance1){
 objInstance1.properties = params;
 objInstance1?.save(flush:true)
 myservice.callingMyserviceMEthod(objInstance1)
}

Service Code:
def callingMyserviceMEthod(MOrder objInstance1){
   objInstance1.setOrderProcess(true);
   objInstance1?.save(flush:true);

if(objInstance1.getOrderProcess()){
    // creating new object object of POrder as objInstance1
    POrder objInstance = new POrder();
    objInstance?.setName("ABC");
    objInstance?.setOrderStatus("process");
    objInstance?.setTenantId(objInstance1?.getTenantId());
    objInstance?.save(flush:true);

    // I also tried this code with Customer.withTenantId()
    /*
    Customer.withTenantId(){
        POrder objInstance = new POrder();
        objInstance?.setName("ABC");
        objInstance?.setOrderStatus("process");

        objInstance?.save(flush:true);

      } */

   }
}

Do not understand how to save that objInsatance ?????
Comment: yes i have paste sample code with question now
Comment: `withTenantId` working fine at my end. If your domain have other domains then create your object inside `withTenantId` closure.
Comment: flow is like that my controller's action gets call and in this controller we are saving a domain say "objIntance1" now i want to create and save a new instace of other domain class say "objInstance" with same tenant id of objInstace1 and when i mark save objInstace it gives error. org.springframework.orm.hibernate3.HibernateSystemException: illegally attempted to associate a proxy with two open Sessions; nested exception is org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions
Comment: Can you post your code?
Answer: use merge instead of save. objInstance?.merge();
Comment: solved my problem by using merge() instead using save()


Is Exchange 2010 compliant with RFC 3848

Question: I have looked up
Exchange 2010 Support for RFC Standards
but do not see RFC 3848 amongst the supported standards. I do see RFC 4954 listed, which 'recommends use of RFC 3848 transmission types', though I cannot tell if this means any mail server compliant with 4954 must also be compliant with 3848.
Specifically, I am trying to find out whether Exchange is capable of adding 'ESMTPA' or 'ESMTPSA' extensions to email headers to indicate SMTP authentication. It would seem peculiar if Exchange did not support this standard...
Thank you.
Comment: Has [this](http://arstechnica.com/civis/viewtopic.php?f=17&t=1264731) helped in any way? :-)
Answer: RFC 3848 transmission types included commands such as EHLO and a few others that you might see today. ESMTPA introduced EHLO as a command that it was an SMTP server that could handle additional commands compared to standard SMTP, this command is now required per RFC 5321.
The ESMTP format was restated in RFC 2821 (superseding RFC 821) and updated to the latest definition in RFC 5321 in 2008. Support for the EHLO command in servers became mandatory. Exchange does support part of the RFC that you referenced at the beginning, but apparently not all of it.
I would check to see how Exchange supports RFC 4954. That would answer your SMTP AUTH question more in-depth.


Intuitive proof that $U(n)$ isn't isomorphic to $SU(n) \times S^1$

Question: One way to prove this is by comparing their centers. However, I do not feel that this proof gives me much insight into the structures of the groups. (It would make me very happy if I were to be corrected though!)
Is there a more intuitive proof? My intuition is that the second group is "larger", but I haven't been able to turn this into a proof.
Comment: Well, the two groups have the same dimension, so it's unclear what you mean by "larger" here.
Comment: The "larger" was because there are multiple obvious copies of $U(n)$ in $SU(n) \times S^1$. I haven't been able to get anywhere with that intuition though, so it may well be that there isn't any useful sense in which the second group is larger.
Comment: I don't know what you mean by that.
Answer: $n \ge 2$ throughout. Taking determinants gives a short exact sequence
$$1 \to SU(n) \to U(n) \xrightarrow{\det} U(1) \to 1$$
and what you'd really like is for an isomorphism $U(n) \cong SU(n) \times U(1)$ to respect the structure of this short exact sequence. (If there were some random isomorphism that didn't have this property that would be less interesting.)
For starters, this requires that $det : U(n) \to U(1)$ have a section, or equivalently that the short exact sequence above splits, which it does: for example, we can send $z \in U(1)$ to the diagonal matrix with entries $z, 1, 1, \dots$. This section allows us to write $U(n)$ as a semidirect product
$$U(n) \cong SU(n) \rtimes U(1)$$
and this cannot be improved to a direct product. This is possible if and only if it is possible to choose a section of $\det : U(n) \to U(1)$ whose image is central. Now, the center of $U(n)$ is the diagonal copy of $U(1)$. When restricted to the center, the determinant map is the map
$$U(1) \ni z \mapsto z^n \in U(1)$$
and this map doesn't have a section for the same reason that $\sqrt[n]{z}$ is not a holomorphic function of $z$.
Answer: This is a sort of addendum to Qiaochu's answer, the purpose of which is to tie up the loose end it leaves in the sense that it only considers isomorphisms compatible with the short exact sequence associated to the surjective $\det\colon \mathrm{U}(n) \to S^1$.
Claim: Any group homorphism $\psi\colon \mathrm{SU}(n)\times S^1\to \mathrm{U}(n)$ must form part of a commutative diagram
$$\require{AMScd}
\begin{CD}
1 @>>> \mathrm{SU}(n)@>{\iota_1}>>  \mathrm{SU}(n)\times S^1 @>{\pi_2}>> S^1 @>>> 1\\
& @V{\theta}VV @V{\psi}VV @V{\bar{\psi}}VV\\
1 @>>> \mathrm{SU}(n) @>>> \mathrm{U}(n) @>{\det}>> S^1 @>>> 1
\end{CD}$$
where $\theta \colon \mathrm{SU}(n) \to \mathrm{SU}(n)$ and $\bar{\psi}\colon S^1 \to S^1$ are group homomorphisms, and $\iota_1(s) = (s,1)$, $\pi_2(s,t)=t$.
To show this we need the following definition and lemma:
Definition: If $G$ is a group then $G'\leq G$, the derived subgroup of $G$ is the subgroup generated by $\{g_1g_2g_1^{-1}g_2^{-1}: g_1,g_2 \in G\}$. It is a normal subgroup, and if $q\colon G \to  G/G'$ is the corresponding quotient map then $G/G'$ is abelian and moreover if $\theta\colon G \to H$ is a group homomorphism from $G$ to an abelian group $H$, then $\theta$ factors through $q$, that is, $G'\subseteq \ker(\theta)$ and hence $\theta$ induces a homomorphism $\bar{\theta}\colon G/G' \to H$ such that $\theta = \bar{\theta}\circ q$.
Note that it follows immediately from the definition that if $\eta \colon G \to H$ is any group homomorphism then $\eta(G') = \eta(G)'\subseteq H'$. The following Lemma is standard, but we include a proof at the end of this answer for the sake of completeness.
Lemma: For any $n>1$, $\mathrm{U}(n)' = \mathrm{SU}(n)$ and $\mathrm{SU}(n)' = \mathrm{SU}(n)$.
Proof of claim:
Note first that by the Lemma we have
$$
(\mathrm{SU}(n)\times S^1)' = \mathrm{SU}(n)'\times (S^1)'= \mathrm{SU}(n)\times \{1\} = \ker(\pi_2)
$$
Now $\det\circ \psi\colon \mathrm{SU}(n)\times S^1\to S^1$ and $S^1$ is abelian, it follows that $\ker(\pi_2)\subseteq \ker(\det\circ \psi)$, and hence there is a unique homomorphism $\bar{\psi}\colon S^1 \to S^1$ such that $\det\circ \psi = \bar{\psi}\circ \pi_2$. Moreover, since $\mathrm{SU}(n)\times \{1\}$ is the derived subgroup of $\mathrm{SU}(n)\times S^1$, its image under $\psi$ must lie in $\mathrm{U}(n)' = \mathrm{SU}(n)$, and hence $\psi_{|\mathrm{SU}(n)}$ induces a homomorphism $\theta\colon \mathrm{SU}(n) \to \mathrm{SU}(n)$, establishing the required commutative diagram.
Now suppose that $\psi\colon \mathrm{SU}(n)\times S^1 \to \mathrm{U}(n)$ is an isomorphism. Then $\theta$ and $\bar{\psi}$ must be isomorphisms, and hence replacing $\psi$ with $(\theta^{-1}\times \bar{\psi}^{-1})\circ \psi$ we may assume that $\theta=\text{id}_{\mathrm{SU}(n)}$ and $\bar{\psi} = \text{id}_{S^1}$.
$$\require{AMScd}
\begin{CD}
\mathrm{SU}(n) @<{\pi_1}<< \mathrm{SU}(n)\times S^1 @>{\pi_2}>> S^1 \\
@| @V{\psi}VV  @|\\
\mathrm{SU}(n) @>>> \mathrm{U}(n) @>{\det}>> S^1
\end{CD}$$
It follows that $\nu(t)= \psi(1,t)$ is a homomorphism $\nu\colon S^1 \to \mathrm{U}(n)$ satisfying $\nu(t)g= g\nu(t)$ for all $g \in \mathrm{U}(n)$  (since $(1,t)\in Z(\mathrm{SU}(n)\times S^1)$) and $\det(\nu(t))= t$. Since $Z(\mathrm{U}(n)) = S^1.I_n$ it follows that $\nu(t) = \lambda(t).I_n$ for a unique homomorphism $\lambda \colon S^1 \to S^1$.
But now the restriction of $\det$ to $S^1.I_n$ is just the homomorphism $m_n\colon S^1 \to S^1$ given by $m_n(t)=t^n$, and for any homomorphism $\eta \colon S^1 \to S^1$ we have $m_n \circ \eta = \eta \circ m_n$, hence if there exists $\lambda \colon S^1 \to S^1$ satisfying $t= \det(\lambda(t).I_n)$ then  $m_n\circ \lambda = \lambda \circ m_n = \text{id}_{S^1}$, so that $\lambda$ and $m_n$ must therefore be isomorphisms, which is impossible since $\ker(m_n) = \{t \in S^1: t^n=1\} \neq \{1\}$.
Proof of Lemma: Since any commutator has determinant $1$, the derived subgroup of $\mathrm{U}(n)$ is certainly contained in $\mathrm{SU}(n)$, thus it suffices to show that $\mathrm{SU}(n)$ is perfect, that is, $\mathrm{SU}(n)' = \mathrm{SU}(n)$. In fact, any element of $\mathrm{SU}(n)$ is equal to a commutator in $\mathrm{SU}(n)$. To see this, note that any unitary transformation is diagonalizable, so we may assume
$$
g \in \mathrm{SU}(n) = \text{diag}(e^{i\theta_1},\ldots,e^{i\theta_n}), \textit{ where } \sum_{i=1}^n \theta_j \in 2 \pi i\mathbb Z.
$$
Now let $P_n$ be the matrix with entries $(P_n)_{ij} = (-1)^{(n-1)\delta_{i,n}}\delta_{\overline{i+1},\bar{j}}$ where for $m\in \mathbb Z$, $\overline{m}\in \{1,2,\ldots,n\}$ and $m-\overline{m} \in n\mathbb Z$).  Thus $P_n$ cycles the standard basis vectors, sending $e_i\mapsto e_{i+1}$ for $1\leq i \leq n-1$ and $e_n \mapsto (-1)^{(n-1)} e_1$, where the sign ensures that $\det(P_n)=1$. Then if $h = \text{diag}(e^{ia_1},\ldots,e^{ia_n})$, we have
$$
hP_nh^{-1}P_n^{-1} = \text{diag}(e^{i(a_1-a_2)},\ldots, e^{i(a_n-a_1)})
$$
so that if we set $a_i = t+\sum_{j=i}^n \theta_j$, where $t$ is chosen so that $h \in \mathrm{SU}(n)$, then since $-\sum_{i=1}^{n-1} \theta_n \in \theta_1 +2\pi\mathbb Z$ it follows that $hw_nh^{-1}w_n^{-1}=g$.


Which GLM(M) to use for proportional data?

Question: I have proportional data that takes any value from 0 and 1. However, there are certainly an over-abundance of 0's, and the rest of the values (there are few) tend to be close to zero.
I'm wondering with this knowledge what is the appropriate GLM to use?
Thanks in advance.
Comment: Do you know the denominators, i.e. how many 'trials' for each observation?
Comment: Yes I believe so. To be more specific. the rate that I'm looking at is: # of a certain type of hatches / # of pupae.

This made me think of doing a Poisson regression model with offset or I've also heard that its possible to use proportional data in a Binomial logistic regression.

What do you think?

Thanks for your help!
Answer: If you know proportions and their denominators (in your case, "number of a certain type of hatches per number of pupae"), then a binomial response is (in my opinion) the most principled/sensible thing to do.

Lots of zeros are expected when the mean proportion is low; it's still possible that you need a zero-inflated binomial model, but unlikely (Warton 2005).
When the mean of a binomial is low, a Poisson model with an offset gives nearly identical results (see here; more precisely, the probability should be low everywhere (e.g. if you have a few combinations of covariates that lead to higher probabilities, that could mess things up).
As always you should check for overdispersion after fitting the model and if necessary do something appropriate (quasi-likelihood, observation-level random effects, beta-binomial model ...)

Warton, David I. "Many Zeros Do Not Mean Zero Inflation: Comparing the Goodness-of-FIt of Parametric Models to Multivariate Abundance Data." Environmetrics 16 (2005): 275–89. https://doi.org/10.1002/env.702.
Comment: +1. To clarify something, if we use a logit we are primarily looking at a fractional logit model.


Does $\frac{\langle a_k,b_k\rangle}{\|a_k\|}$ converge, if $(a_k)_k$ and $(b_k)_k$ tend to $0$ and $b\neq 0$ respectively?

Question: If $(a_k)_k$ and $(b_k)_k$ both convergent sequences in $\mathbb{R}^2$ such that their limits are $0$ and $b\neq0$ respectively. Does the sequence.
$$\frac{\langle a_k,b_k \rangle}{\|a_k\|}$$ converge? (where $\langle a_k,b_k \rangle$ is the scalar product).
I'm not really sure how to go about this, since the numerator and the denominator both go to $0$( all norms are equivalent so it doesn't matter which norm we choose for the denominator).
I figured I might try using the sandwich theorem to approximate this but I'm not sure how, since the numerator is basically $a^1_kb^1_k * a^2_kb^2_k$ and if $(a_k)_k$ goes to $(0,0)$ obviously the component sequences both tend to $0$ and i can't separate them from the component sequences of $b_k$. So I'm not sure how to go about this!
Any hints at all would be appreciated
Thanks in advance!
Comment: No need to feel sorry, most people use it as a short version of $(a_k)_{k \in \mathbb N} $
Comment: What do you intend by $(a_k)_k$?  You say it is a convergent sequence in $\Bbb R^2$.  Is it a diagonalization of some sort because of the double indices?  Or is it just a sequence of points, which should just be indexed once.
Comment: I'm sorry , that's the kind of notation we use at uni, double indices.
It's just a sequence in $R$. $a_k$ would be the notation you prefer I assume, sorry if I was unclear.
Comment: @RossMillikan Some people use $(a_k)_k$ in the same sense as $(a_k)_{k=1}^\infty$.
Answer: The answer is no.
Let $$a_n = \left((-1)^n\cdot\frac1n, \frac1n\right), \text{ for } n\in \mathbb{N}$$
and $b_n = (1, 1)$ for $n \in \mathbb{N}$, the constant sequence $(1,1)$.
We have:
$$\frac{\langle a_n, b_n\rangle}{\|a_n\|} = \frac{(-1)^n\cdot\frac1n + \frac1n}{\frac{\sqrt{2}}{n}} = \frac{(-1)^n + 1}{\sqrt{2}}$$
This sequence does not converge.
Comment: According to the question, $b_n \not \to 0$.
Answer: In general, no.
Note we have
$\dfrac{\langle a_n, b_n \rangle}{\Vert a_n \Vert} = \langle \dfrac{a_n}{\Vert a_n \Vert }, b_n \rangle; \tag 1$
since
$\Vert \dfrac{a_n}{\Vert a_n \Vert} \Vert = \dfrac{\Vert a_n \Vert}{\Vert a_n \Vert} = 1, \tag 2$
we have
$e_n = \dfrac{a_n}{\Vert a_n \Vert} \in S^1, \tag 3$
where $S^1$ is the unit circle, is a sequence of unit vectors in $\Bbb R^2$; furthermore, for any sequence of unit vectors $e_n \in S^1$, we can find $a_n \to 0$ such that (3) binds; as a simple example, set
$a_n = \dfrac{e_n}{n}; \tag 4$
then
$a_n \to 0. \tag 5$
The question then really hinges on finding $\langle e_n, b \rangle$; but if we take
$e_n = \dfrac{(-1)^n b_n}{ \Vert b_n \Vert}, \tag 6$
which we can always do once $n$ becomes big enough, since $b_n \to b$ implies $\Vert b_n \Vert \to \Vert b \Vert \ne 0$,
we have
$\langle e_n, b \rangle =\langle \dfrac{(-1)^n b_n}{ \Vert b_n \Vert}, b \rangle = (-1)^n \langle \dfrac{b_n}{\Vert b_n \Vert}, b \rangle = \dfrac{(-1)^n}{\Vert b_n \Vert} \langle b_n, b \rangle; \tag 7$
but
$\dfrac{1}{\Vert b_n \Vert} \langle b_n, b \rangle \to \dfrac{1}{\Vert b \Vert} \langle b, b \rangle = \dfrac{\Vert b \Vert^2}{\Vert b \Vert} = \Vert b \Vert; \tag 8$
we then have
$\langle e_n, b \rangle \to \Vert b \Vert, \; n \; \text{even}, \tag 9$
and
$\langle e_n, b \rangle \to -\Vert b \Vert, \; n \; \text{odd}, \tag{10}$
so the sequece $\langle e_n, b \rangle$ fails to converge.  Thus the sequence (1) fails to converge as well.


Create new gmail programmatically

Question: I develop an android application and this app uses to send emails so I need create new email in android; Can I create email using android code?
I need create new email from android activity like this:
username: [__________]
password: [__________]
SMTP: [__________]
Port: [__________]
SSL/TLS: Dropdown box with 3 options, No, SSL, and TLS

Comment: You want to create an e-mail using available gmail account or you want to create a new gmail account?
Answer: Perhaps using javamail:
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Mail extends javax.mail.Authenticator {
  private String _user;
  private String _pass;

  private String[] _to;
  private String _from;

  private String _port;
  private String _sport;

  private String _host;

  private String _subject;
  private String _body;

  private boolean _auth;

  private boolean _debuggable;

  private Multipart _multipart;

  public Mail() {
    _host = "smtp.gmail.com"; // default smtp server
    _port = "465"; // default smtp port
    _sport = "465"; // default socketfactory port

    _user = ""; // username
    _pass = ""; // password
    _from = ""; // email sent from
    _subject = ""; // email subject
    _body = ""; // email body

    _debuggable = false; // debug mode on or off - default off
    _auth = true; // smtp authentication - default on

    _multipart = new MimeMultipart();

    // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
    MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    CommandMap.setDefaultCommandMap(mc);
  }

  public Mail(String user, String pass) {
    this();

    _user = user;
    _pass = pass;
  }

  public boolean send() throws Exception {
    Properties props = _setProperties();

    if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
      Session session = Session.getInstance(props, this);

      MimeMessage msg = new MimeMessage(session);

      msg.setFrom(new InternetAddress(_from));

      InternetAddress[] addressTo = new InternetAddress[_to.length];
      for (int i = 0; i < _to.length; i++) {
        addressTo[i] = new InternetAddress(_to[i]);
      }
        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

      msg.setSubject(_subject);
      msg.setSentDate(new Date());

      // setup message body
      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(_body);
      _multipart.addBodyPart(messageBodyPart);

      // Put parts in message
      msg.setContent(_multipart);

      // send email
      Transport.send(msg);

      return true;
    } else {
      return false;
    }
  }

  public void addAttachment(String filename) throws Exception {
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);

    _multipart.addBodyPart(messageBodyPart);
  }

  @Override
  public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(_user, _pass);
  }

  private Properties _setProperties() {
    Properties props = new Properties();

    props.put("mail.smtp.host", _host);

    if(_debuggable) {
      props.put("mail.debug", "true");
    }

    if(_auth) {
      props.put("mail.smtp.auth", "true");
    }

    props.put("mail.smtp.port", _port);
    props.put("mail.smtp.socketFactory.port", _sport);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    return props;
  }

  // the getters and setters
  public String getBody() {
    return _body;
  }

  public void setBody(String _body) {
    this._body = _body;
  }

  // more of the getters and setters …..
}

The chap who wrote the code above (not hd1) has it on his github account. Look there or leave a comment if you have further problems.
UPDATE
To merely launch gmail, do:
Intent mailClient = new Intent(Intent.ACTION_VIEW);
mailClient.setClassName("com.google.android.gm", "com.google.android.gm.ConversationListActivity");
startActivity(mailClient);

Create new gmail programmatically


VBA não aparece as opções e Métodos automaticamente

Question: Sou novo aqui, e já peço desculpas pela dúvida "banal", mas estou pesquisando há um bom tempo isso.
Uso o VBA pelo EXCEL, e não consigo ativar a opção do texto se autopreencher ao escrever uma função ou método conhecido.
Assim, tenho tido muita dificuldade em saber os métodos que certo objeto possui.
Já ativei o Autoverificar Sintaxe e demais opções:

Assim, minha dúvida é: Eu preciso adicionar alguma extensão específica para isso, ou apenas habilitar algo que não estou achando?
Obrigado pela atenção.
Comment: Qual é o objeto em que não aparece a lista de propriedades e métodos?
Answer: A opção é essa Autolistar membros, que está marcada no print que você mandou.
Uma opção de fazer isso manualmente é clicar com o botão direito e selecionar Listar propriedades/métodos, mas é um porre fazer isso à mão:

Mas tem um detalhe: se você estiver tentando usar isso com um objeto que faz parte de uma biblioteca não referenciada, não vai aparecer mesmo. Tente com ThisWorkbook., que integra a biblioteca do próprio Excel, e veja se aparece.
Se não aparecer, há alguma configuração profunda perdida aí, além da minha resposta.


Apparent logical flaw in statement: ∀x∀yP(x,y)⊢∀x∀yP(y,x)

Question: I was able to prove the statement $\forall{x} \forall{y} P(x,y) \vdash \forall{x} \forall{y} P(y,x)$:

This implies order does not matter within predicates. However, this confuses me because depending on what the predicate represents, order can be crucial.
Take, for example $P(x,y)$ representing $x < y$ with the universe of discourse for $x$ being all negative integers and the UOD for y being all positive integers.
In this case, $\forall{x} \forall{y} P(x,y)$ holds since all negative integers are smaller than all positive integers.
However, $\forall{x} \forall{y} P(y,x)$ would not hold since all positive integers are not smaller than all negative integers.
Clearly, I am misunderstanding something or making incorrect assumptions about the nature of predicate logic. Any clarification would be greatly appreciated.
Comment: The predicate you chose, $P(x,y) \leftrightarrow x < y$, does not satisfy the premise $\forall x.\forall y. P(x,y)$ of your proof. There is always only one domain of discourse, and all your variables range over that same domain. And your proof does not show that order of arguments never matters. Only that it does not matter *if* your predicate is always true, i.e. if it holds for all $x,y$.
Comment: But the premise simply says that everything is P-connected.
Comment: Hint: $\forall x$ commutes with $\forall y$.
Comment: The error seems to be in your statement that "this implies order does not matter within predicates." That's true in some (very limited) contexts, like the one in your proof, where both variables are universally quantified over the same domain. But it's false in a lot of other contexts..
Answer: It is a general principle that $\forall x \forall y \ P(x,y)$ is logically equivalent to $\forall x \forall y \ P(y,x)$, and that is what you proved (well, technically, you showed that $\forall x \forall y \ P(x,y)$ logically implies $\forall x \forall y \ P(y,x)$, but a completlely analogous proof will show that it goes the other way around as well)
However, it is understood here that $x$ and $y$ come from the same domain. Indeed, the very use of $\forall x \forall y$ ... implies that $x$ and $y$ come from the same domain.
Now, if you want $x$ and $y$ to be from different domains, then there are a few options.
First, if you are allowed the use of restricted quantifiers, then you can do $\forall x \in X \forall y \in Y ....$, ... but there is no general principle that says that $\forall x \in X \forall y \in Y \ P(x,y)$ is equivalent to $\forall x \in X \forall y \in Y \ P(y,x)$ (indeed, as your example demonstrates, we better not make this an euivelence principle)
Second, if you are not allowed the use of restricted quantifiers, you can do: $\forall x \forall y ((x \in X \land y \in Y) \to P(x,y))$, but now note that with the general principle that would be equivalent to $\forall x \forall y ((y \in X \land x \in Y) \to P(y,x))$ ... and that is not the same as $\forall x \forall y ((x \in X \land y \in Y) \to P(y,x))$
Finally, maybe you have learned logic in a way where you can just stipulate that 'variable $x$ comes from this domain, and variable $y$ from this other'.  Well, you might get away with that in some informal setting, but given the hard principles of formal logic, the use of $\forall x \forall y ...$ still means that $x$ and $y$ must be from the same domain.
So no, your example with positive and negative numbers does not provide an exception to the equivalence principle or to your proof.


Right hand descending scale F# key finger 3 vs. 4

Question:
When playing the descending scale in the images shown, I always use finger 3 (orange) on the black F# key (3214321) because it's easier than finger 4 (printed) as it's far from the center and the hand needs to turn inward. I noticed almost all the printed fingerings suggest finger 4 (4321321). Is it just because it's the same fingering when playing the scale in ascending direction? Anyone agree my fingering is better(only for descending)? (I know it's no big deal, but asking because I haven't seen anyone using my orange fingering).

Just to add (learning Clementi Op 36 No. 4, 3rd movement now): This Measure 3, all the fingerings I've seen are as printed: 2-5. I find it much easier and more natural to use fingers 2-4 (see green). At this point I have to think of two tricky parts at the same time: left hand locating the four keys for the chord, right hand squeezing finger 5 to where finger 4 would naturally be. Using finger 2-4 saves me from having to think of the right hand at that moment and concentrate on left hand. (It also sounds better with 2-4 than 2-5, the little thumb). However, because everyone else uses 2-5, I feel guilty to use my different fingering. Thoughts/comments? Anyone agree mine is better?
Comment: Ant fingering in any piece is merely a *suggested* fingering. It's often a good start point, but seasoned players may not even notice it, or pay attention to it. We should all (as you have) try out alternative fingerings, to find our own optimum, whatever the piece and its printed fingering. If your fingers feel better suited to what you decided, that's great for you - may not work at all for another player. Longer/shorter fingers, more/less mobility, more/less experience all contribute.
Comment: Thanks. I thought of asking this question to see if I practised that 'theory' too freely. I was wondering why no one else used my preferred fingerings for this scale. If only I could find a famous pianist using my uncommon fingering I'd be thrilled :)
Comment: I found one person using my fingering: @1:22 https://www.youtube.com/watch?v=feK9jK7-p0A
Answer: Fingerings are personal, and what you've suggested is perfectly reasonable, so if that's what you prefer, then go for it.
There's a slight tendency to come down a little harder when crossing over the thumb, so placing that cross on the downbeat plays into that tendency. It's also just nice from a mental organization standpoint to have that more significant moment happen on the beat. It helps you cluster your actions into the most logical groups. But, of course you should learn to be adept at crossing whenever is necessary and doing so smoothly and transparently, and fingerings like you suggest should work just as well for a skilled player. It's just a tiny bit harder to phrase it correctly.
Comment: Thanks. I have almost never considered the beat, logical grouping and phrasing factors when choosing best fingerings. I see now why all the suggestions for this particular scale use that same fingering. Perhaps another advantage is when sight reading, not knowing what's coming up: using finger 4 instead of 3 the first time encountering finger crossing will ensure there will be one more finger available later if needed.
Answer: Narrowing the choices to two:

Finger 4 on F#; Finger 3 on C vs.
Finger 3 on F#; Finger 4 on C

I would most likely choose the former. G and F# are closer together than D and C, so finger 4 doesn't have to reach as far across the thumb; and the F# being raised places it at a natural height for the finger as my hand passes over the thumb.
However, it's entirely possible I would just use finger 3 the entire way. In the Clementi case it doesn't substantially affect things, and the in Beethoven has, though it means an additional crossover, it still gets me to finger 2 on F# at the end of the measure. The advantage in both cases is consistency of fingering — not needing to be concerned which note gets 4 and which gets 3.
Comment: @GrandAdagio You shouldn't be turning your hand — very bad for your wrist — or forcing your hand to stay in the center of the keys. Instead, as the music dictates, shift your hand toward and away from the fall board. That puts your thumb closer to the F# after which you can adjust back toward your body.
Comment: What affected my comfort was that G, F# are way farther away from the center than D, C are, so it takes more turning of the hand if using finger 4 on F#. If it was the lower octave then I would use finger 4 on F#.
Comment: @GrandAdagio An example of the technique can be seen in [Piano: Left handed Gmaj7 chord](https://music.stackexchange.com/a/104907/70803). It deals with a chord rather than a scale — and left hand rather than right — but the images might provide some guidance.
Comment: thanks, I will pay attention to that. When I use finger 4 on F#, the next finger 3 tends to touch the white F key rather than E. Maybe it has to do with small hand.
Comment: @GrandAdagio That's a separate issue. Sounds like you're best off staying with the fingering you're already using.
Answer: It's a G major scale.  Your hand is (or should be) very accustomed to playing it  both up and down with the standard fingering, 4 on F♯.  So the idea is that you use this familiarity when a G major scale occurs in a piece.
This 'turn inwards' worries me.  Do you turn your hand at this point when practicing the scale?  Get your teacher to show you how not to!
Comment: Thanks, I'm working on correcting that turning inwards. (I don't have a teacher :))


Is there GC in latest iphone OS?

Question: If we use  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; then what method is used, either drain or release for lates iOS.
Answer: no garbage collection on iOS.
I do what apple suggests in the documentation:

In a garbage-collected environment,
  release is a no-op, so unless you do
  not want to give the collector a hint
  it is important to use drain in any
  code that may be compiled for a
  garbage-collected environment.
Answer: On iOS NSAutoreleasePool will drain when it goes out of the scope where it is defined (as long as no other reference is held). During the drain, it will release all objects held by it.
Thus, calling release might result in a drain, as long as it's the last reference to the pool.
This is different from the traditional GC where the collector is not scope bound and in general works independently of the main app code flow.

Is there GC in latest iphone OS?


Drupal Hook_Mail_Alter Custom Template fields

Question: We have a Drupal 6 contact us Webform with e-mail.  There is a custom template with the following fields:
Facility: %value[facility]
First Name: %value[first_name]
Last Name: %value[last_name]
Email: %value[email_address]
Phone: %value[phone_number]
I wish to be contacted: %value[contact_user]
Subject: %value[subject]
Comments: %value[comments]
The results of this submission may be viewed at:
%submission_url
I want to access both the subject and the facility field.  I'm not sure my keys are correct using "headers".  Is this the correct way to access both the subject and facility fields?
Here is my code in the custom module test:
<code>test_mail_alter(&$message)
{

    if (($message['id'] == 'contact_us'))
    {
        $mail_listing = array();

        // pick up subject e-mails
        $subject = str_replace(' ','',$message['headers']['subject']);
        $subject_listing = explode(',',$subject);
        foreach ($subject_listing as $s){

            if (preg_match('/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/',$s)){
                array_push($mail_listing,$s);
            }

        }

        // pick up facility if it exists and combine it with the subject listing
        $facility = str_replace(' ','',$message['headers']['facility']);
        $facility_listing = explode(',',$facility);
        foreach ($facility_listing as $f){

            if (preg_match('/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/',$f)){
                array_push($mail_listing,$f);
            }

        }

        $message['headers']['to'] = implode(',',$mail_listing);
    }
}
</code>
Answer: In Drupal 6, you can specify further settings:

Navigate to the Contact Form settings page (http://example.com/admin/build/contact/settings)
In the "Additional Information" section, enter the text to display with the contact form.
In the "Hourly Threshold" list, select the maximum number of submissions that a user can make per hour.


3-4-3-4 fingering in BMV994

Question: I was recently looking through Bach sheet music to find something new for training and I found BMV994 which made me a bit confused:

This does not look like any "modern" fingerings I have seen. I have following questions:

How exactly am I supposed to play such fingering with legato? Should third finger go over the fourth or under it?
Is such fingering still used or the piano technique evolved since then? Should I focus on learning proper 3-4-3 fingering or it's relic of the past? Is it often used nowadays?
Does playing with such fingering has any advantage over playing it like 1-2-3-1-2-3-4 or similar "normal" fingerings?
BMV994 on YouTube
Answer: Your mistake of thinking is, that in Baroque music (and in classical music, and mostly even in romantic music), the standard articulation is non-legato.
You only shall play legato if there is a legato-bow or some strong indication.
E.g. In this example the fingering indicates the articulation. Every two notes with fingering 3-4 are played legato, then you articulate a bit the next note. How much you articulate is personal flavour, but they must not be tied together - which is anyway impossible with this fingering.
A second benefit from this fingering is the following. In French Baroque music, there is something called: notes inégales. Roughly speaking, all melodic notes, which come across in pairs, are played rhythmised - the first note is longer then the second. The fingering in this example also helps you to play such a rhyhtm.
Do not forget that, there are also some piano-technical aspects:

old claviers had a key-drop which was far less then todays piano key-drop,
the keys were not so heavy,
the keys often had rounded edges, which allowed to slide with one finger from one key to another (most people forget that point).
According to Alexander Woo, players sat in an angle to the keyboard. This may also influence the fingering.

All this together made it much easier to play such a fingering then it is nowadays.
Now to your questions:

Usually the third finger goes a little bit below the fourth finger, but this depends on everybodys hand.
Some people still use this fingering. If you want to learn it, learn it.
This fingering has the advantage that you automatically play the correct articulation. If you play a good articulation with your favourite fingering, it is also ok.

A side-note: All of the ornaments start on-beat. That is, the first note of the ornaments is played on the beat. In particular for the first three ornaments: together with the chord in the left hand.
Comment: I think it should also be noted that, in the Baroque period, harpsicordists sat an angle to the keyboard, not parallel to it.
Answer: This isn't "modern" fingering. It was a relic of the finger technique for the first keyboard instruments, where the "white" keys were physically too short to make "passing the thumb over or under" a convenient way to play scales.
It's not too difficult to play this type of fingering evenly, especially on a harpsichord which has a "hair-trigger" touch compared with a modern piano, the note sounds during the top 25% of the key depression, not at the bottom of the key stroke like a piano, and the loudness of each note is not affected (at least to any significant degree) by the speed at which the key is depressed.
But even does not mean legato in the sense that later piano technique uses the term.
On instruments like the harpsichord and organ, with no dynamics, articulation is the most important tool the performer has to define rhythm. Playing everything "legato" on a harpsichord (or even worse, on an organ in a building with a very resonant acoustic) simply produces a shapeless mush of sound.
It is certainly valuable to research such original fingerings and understand how they "work" on the original instruments, but since the piano is very different mechanically from the instruments that Bach was using, there is little point in trying to slavishly use the same fingering IMO. What matters is that you produce the same effect, so far as that is possible on a piano.
This is played on organ not harpsichord, but the reason for including it here is that it clearly shows just how NON-legato the fingering technique is, compared with the sound it produces.

3-4-3-4 fingering in BMV994


Ajax to ActionResult, getting Model

Question: I have an action (Index) that return a View with a concrete model.
Inside that view (Is a calendar) I have two buttons to change months.
When I click one of those I call back Index action to that will return the same view with a modified model.
$("#right").live("click", function () {
    $.post($(this).attr("href"), function (response) {
        $("#wrapper").replaceWith($(response).filter("div#wrapper"));
    });
    return false;
});

So, I click #right and it call /Home/Index and Index return something like:
return View(new DateViewModel(dt, _bDays.GetDaysFromMonth(dt)));

So as you see, I replace div#wrapper with the new one. Perfect but...
Is there a way to get the model of the response? I mean, that action return a view with a model and apart from getting the concrete div I want the model.
Any idea?
Answer: I don't know why you would need the model in the AJAX callback, and thus there is probably a better solution than the one I am about to propose. So you could have your controller action render the partial view into a string and then return a JSON object containing both the HTML and the model:
[HttpPost]
public ActionResult MyAction()
{
    MyViewModel model = new DateViewModel(dt, _bDays.GetDaysFromMonth(dt));
    string html = RenderPartialToString("partialName", model);
    return Json(new { Model = model, Html = html });
}

and in your AJAX callback:
$.post($(this).attr("href"), function (response) {
    var model = response.Model;
    var html = response.Html;
    $("#wrapper").replaceWith($(html).filter("div#wrapper"));
});

Comment: Work like a charm. Thanks, my app is a little more faster and I learnt something new.
Answer: One possible approach would be to call a separate controller action and return a JsonResult:
[HttpPost]
public ActionResult MyAction()
{
    return Json(new DateViewModel(dt, _bDays.GetDaysFromMonth(dt)));
}

This action will return a JSON representation of your ViewModel that you can reference in your AJAX response.
Comment: Yeah, I know that way but it's an extra ajax call, one for changing month and one to get the days. I prefer 1 if possible. Thanks anyway.

Ajax to ActionResult, getting Model


using __init__ method with and without parameters

Question: I am new in python and please excuse me if my question is a basic question or is not clear.
I have a class in python and I want to set some attributes for my objects whenever I generate my objects from this class. I know, I must use __init__ method for this purpose.
The problem is that I want to have this ability that I can set my attributes in two ways. For some of my objects, I want to pass some values to __init__ method and set the attributes with those values. In addition, for some objects, I want to set some default values for attributes of my objects in __init__ method.
My question: How can I have an __init__ method that for some objects uses passed values for setting its attributes, and for some other objects, that are not passed, use default values?
Comment: Have a look at [default argument values](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values)
Comment: It is also a good idea to know the behavior of [mutable objects as default arguments](http://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument).
Comment: thanks @elena for editing my question!
Answer: Simply equate the the parameters that you would want to be defaulted to their default value.
For instance, __init__(a,b,c=0) would give 0 as the default value to c which you can override by passing another value when object is created.
Answer: def __init__(a,b,c='your default value')


How to get a specific string pattern from a continous buffer/byte array in Netty JAVA?

Question: I am currently using Netty. Now the problem is, I want retrieve a specific string from the buffer. For example, if the buffer data is as follows :
8=FIX.4.2|9=00815|35=W|49=TT_PRICE|56=SAP0094X|10=134|8=FIX.4.2|9=00816|35=W49=TT_PRICE|56=SAP0094X|10=121

Now I want the strings starting with "8=xxx" and ending with "10=xxx". You can clearly see that we have two strings appended in the buffer. Note that the above data is in a byte array. So,sometimes I get the exact string and some time I get the string and another half of the full string appended. All I want is , how can I get the exact String starting from "8=xxx" to "10=xxx". I have seen DelimiterBasedFrameDecoder class in Netty that simply checks delimiter specified and gives us the strings. In the same way how can I do this ?
Answer: My suggestion would be to translate the buffer and use a regex to match your target substrings:
ByteBuffer bb = /* byte buffer */
String text = new String(bb.array(), 0, bb.position(), bb.remaing(), Charset.defaultCharset());

// I assume that this is the string: "8=FIX.4.2|9=00815|35=W|49=TT_PRICE|56=SAP0094X|10=134|8=FIX.4.2|9=00816|35=W49=TT_PRICE|56=SAP0094X|10=121"

// If you need info on the regex just ask for it
Pattern r = Pattern.compile("(8=\\w\\w\\w)[\\s\\S]*?(10=\\w\\w\\w)");
Matcher m = r.matcher(text);

while (m.find()) {
     System.out.println(m.group());
}

Note that Charset.defaultCharset() could be changed base on which encoding your ByteArray is using
Comment: please note that using `bb.array()` is only save when `bb.hasArray()` returns true. and you also need to take `bb.arrayOffset()` into account.
Comment: Thank you. But as I am using Netty here, I will be getting ByteBuf instead of ByteBuffer here.
Comment: to get a String out of the ByteBuf in netty use: ByteBuf.toString(Charset).
Comment: Yeah, thank you very much.Can you help me with this [link](https://stackoverflow.com/questions/45637198/how-to-get-the-remaining-not-matched-string-when-using-pattern-matcher-in-regex) please.


Forcing Javascript Redirection

Question: I am trying to implement what seems to be very simple JavaScript redirection, via the following rudimentary command:
window.location.href = "http://www.somesite.com";

So far so good, it works.  I also can do it via the following method:
location.replace("http://www.somesite.com");

No problem here, it works again! The problem comes when I loose the protocol out of the string:
window.location.href = "www.somesite.com";

OR:
location.replace("www.somesite.com");

It just appends the new location to the current url:
www.currentsite.com/www.somesite.com
Of cause, that's not what I want.  Is there any way to force the redirect?
Comment: Why do you need to lose the protocol part? Maybe a leading '//' works (protocol-relative URL)?
Comment: Without the protocol its treated as a relative url
Comment: You need the protocol part as it instructs the browser how to handle with it, as there are many protocols relating to different things.
Comment: because typing "www.something.com" in the address bar will work the way expected, it will redirect. I just want to know if it's possible for JavaScript to do the same.
Comment: The difference is that addresses in the URL bar are never treated as relative URLs - when you type in there you're doing 2 things: 1) *Removing the current URL* and 2) Typing in a new one.
Answer: One way is to use protocol-relative url like this:
window.location = "//www.somesite.com";

Or
window.location = "//somesite.com";

This way, it would redirect and browser itself will take care of figuring out protocol part eg http or https
Working Example
Comment: Yep that's very useful bit of information!  I can check for protocol presence and then append protocol-relative as needed!
Answer: The protocol is required.
How else would the browser know whether
location.replace("mysite.pl");

was going to a Polish website or a Perl script on the current website?
Comment: Ok, I guess now I know that I have to live with it. Thanks)) Just thought there might be a way
Answer: You could do something like this to add http:// to the URL if it's not already there... although I can't think of a reason for not just including it yourself. Why complicate things?
function redirect(url) {
    if(url.substr(4) != "http")
        url = "http://" + url;
    window.location.href = url;
}
redirect("www.google.com")

Forcing Javascript Redirection


Small detail in proof of Lemma 1.2 in Frieze and Karoński's 'Introduction to Random Graphs'

Question: In the text Introduction to Random Graphs by Karoński and Frieze, the authors claim that
$$
(1+o(1))\sqrt{\frac{N}{2\pi m(N-m)}} \geq \frac{1}{10\sqrt{m}}
$$
in the proof of Lemma 1.2 where

$m = m(n) \to \infty$
$N = \binom{n}{2}$
$N - m \to \infty$.

I have been trying to figure how they made this simplification for some time now and am not confident with my reasoning. Here is my attempt at a proof:
Since the $o(1)$ term comes from Stirling's formula, it must be positive. Hence
\begin{align*}
  (1+o(1))\sqrt{\frac{N}{2\pi m(N-m)}} &\geq \sqrt{\frac{N}{2\pi m(N-m)}} \\
&\geq  \sqrt{\frac{N-m}{2\pi m(N-m)}} \\
&= \frac{1}{\sqrt{2\pi m}} \\
&\geq \frac{1}{10\sqrt{m}}.
\end{align*}
For some reason this doesn't feel right to me. Any feedback or insight would be greatly appreciated.
Also, it's a bit confusing why they chose the constant $10$. Couldn't they have chosen a smaller constant so long as it was bigger than $\sqrt{2\pi}$ (for instance $3$)? Or was the reason they chose $10$ just because it's "nice".
EDIT: As was nicely pointed out by Calvin Khor below, I don't think I can claim that the $o(1)$ term that comes from Stirling's formula is positive. That is, it was not sound to say that the $o(1)$ term is positive just because it came from Stirling's formula. Apologies for the error there.
Comment: I'm not so familiar with the fact that Stirling without the $o(1)$ is an under-approximation. But you are correct that $10$ could have been a different number. I think its natural to use say, $1+o(1) \ge \frac12$ for large $n$, and $\sqrt{2\pi}\le 3$, which would give $6$.
Answer: This is almost right, but (as pointed out by Calvin Khor in the comments) we should add the step that for large enough $n$, $1+o(1)$ is at least $\frac12$ (or any constant less than $1$) rather than say it is at least $1$.
More interesting (though not often useful) is the fact that the lemma actually holds for all $n \ge 2$ and $1 \le m \le \binom n2 - 1$, but this requires a slightly more careful approach than the proof in the textbook. (It is also not enough to say that $n! > \sqrt{2\pi n} (\frac ne)^n$, since we want lower bounds in the numerator but upper bounds in the denominator.)
According to Wikipedia (citing Robbins, A remark on Stirling's formula), we have $$\sqrt{2\pi n} \left(\frac ne\right)^n e^{\frac1{12n+1}} < n! < \sqrt{2\pi n} \left(\frac ne\right)^n e^{\frac1{12n}}$$ for all $n \ge 1$. Therefore in $\binom rs$ with $1 \le s \le r-1$, we get
$$
   \binom rs \ge e^{\frac1{12r+1} - \frac1{12s} - \frac1{12(r-s)}} \sqrt{\frac{r}{2\pi s(r-s)}} \frac{r^r}{s^s (r-s)^{r-s}}.
$$
(We'd have the same expression with $e^{\frac1{12r} - \frac1{12s+1} - \frac1{12(r-s)+1}}$in the upper bound, which we don't need here.)
The probability that a $\text{Binomial}(r, \frac sr)$ random variable is exactly $s$ is $\binom rs (\frac sr)^s (\frac{r-s}{r})^{r-s}$, which is at least $e^{\frac1{12r+1} - \frac1{12s} - \frac1{12(r-s)}} \sqrt{\frac{r}{2\pi s(r-s)}}$. The square root is bigger than $\frac1{\sqrt{2\pi s}}$ and the worst case for the exponent is $r=2$, $s=1$, which gives $e^{-19/150}$ and a lingering sense that perhaps we didn't need to be quite this careful. For all practical purposes, it is  enough that $e^{-19/150} \frac1{\sqrt{2\pi}} > \frac13$, giving us a lower bound of $\frac1{3\sqrt s}$ for this probability.
In the specific application, we get
$$
\mathbb P(\mathbb G_{n,m} \in \mathscr P) \le \frac{\mathbb P(\mathbb G_{n,p} \in \mathscr P)}{\mathbb P(|E_{n,p}|=m)} \le 3 m^{1/2}\, \mathbb P(\mathbb G_{n,p} \in \mathscr P)
$$
whenever $1 \le m \le \binom n2 - 1$. (Actually, when $m = \binom n2$ as well, trivially.)
We can also show $\mathbb P(\mathbb G_{n,m} \in \mathscr P) \le n\, \mathbb P(\mathbb G_{n,p} \in \mathscr P)$ whenever $n \ge 2$. This requires bounding $\frac{N}{m(N-m)} \ge \frac{N}{(N/2)^2} \ge \frac 8{n^2}$, and arguing $n=2$ separately to get the right constant; also, it's only better for dense random graphs, and only slightly. But it is simpler.


How to find out if the key value is existed in an array using PHP?

Question: I have a question
I need to find if the value of key in an array is existed in PHP and get the index value of it.
Example I have this array:
<code>Array
(
    [0] => Array
        (
            [restaurant_id] => 1519
            [new_lat] => 14.63807
            [new_long] => 121.03158
            [date_updated] => 2013-11-14 16:40:34
        )

    [1] => Array
        (
            [restaurant_id] => 1247
            [new_lat] => 14.63877
            [new_long] => 121.03265
            [date_updated] => 2013-11-14 16:48:41
        )

)
</code>
I also used this code also:
<code>$key = array_search($data_add['restaurant_id'],$data);
</code>
But it doesn't display the searched value
Now I need to fint if restaurant_id '1247' is existed in array? If existed get that index. Meaning get the index 1 because ID 1247 is in index 1.
I used the array_key_exists() but it will find the key not the key value. I hope you can help me thanks.
Answer: Try this:
<code>$myArray = []; // Array as above
$target = '1247';

for ($i=0; $i<count($myArray);$i++) {
    if ($myArray[$i]['restaurant_id'] == $target) {
        break;
    }
}
// $i contains index of target
</code>


Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket'

Question:
Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.(index):29 (anonymous function)

Código:
function smConnect() {
    ws = new WebSocket('ws://127.0.0.1:1805/');
    delete ws.URL;

    ws.onopen = function(response) {
    };

    ws.onmessage = function(response) {
    };

    ws.onclose = function(response) {
    };

    ws.onerror = function(error) {
    };
}

smConnect();
ws.send('message', 'hi');

O que pode ser?
Answer: Segundo a mensagem retornada, você está tentando executar o método send antes mesmo de ter sido estabelecida a conexão.
Segundo a página do w3.org sobre WebSockets:

O método de send(data) transmite dados usando a conexão. Se o
  atributo readyState está se conectando, deve lançar uma exceção
  InvalidStateError.

O que você deve fazer é esperar que seja feita a conexão para então executar o método send.
Você pode implementar isto do seguinte modo (créditos):
function waitForSocketConnection(socket, callback){
        setTimeout(
            function(){
                if (socket.readyState === 1) {
                    if(callback !== undefined){
                        callback();
                    }
                    return;
                } else {
                    waitForSocketConnection(socket,callback);
                }
            }, 5);
    };

E utilizá-lo assim:
waitForSocketConnection(ws, function() {
    ws.send('message', 'hi');
});

Ou simplesmente fazer isso no evento onOpen:
ws.onopen = function(response) {
    ws.send('message', 'hi');
};

Comment: O método do timer cheira a gambiarra, prefiro o `onopen`.


fetch 2d array in php

Question: I have an array that looks like :
'Item1' =>
     array (size=5)
     0 => 'under Item1 1'
     1 => 'under Item1 2'
     2 => 'under Item1 3'
     3 => 'under Item1 4'
'Item2' =>
    array (size=4)
    0 => 'under Item2 1'
    1 => 'under Item2 2'
    2 => 'under Item2 3'
    3 => 'under Item2 4'

And I want to fetch that array and show a menu : so the final result must be so :
        Item 1
             . under Item1 1
             . under Item1 2
             . under Item1 3
             . under Item1 4
        Item 2
             . under Item2 1
             . under Item2 2
             . under Item2 3
             . under Item2 4

Comment: You didn't mention which language you use.
Comment: php , it's mentioned in the title above ;)
Comment: Whoops my bad, I'm always looking the tags.
Answer: Use array iteration:

    <?php
    foreach ($yourarray as $menu_name => $submenu) {
        echo '
'.$menu_name;
        echo '
';

        foreach ($submenu as $submenu_name) {
            echo '
'.$submenu_name.'
';
        }

        echo '
';
        echo '
';
    }
    ?>

fetch 2d array in php


Proving that $\lim\limits_{t \rightarrow \infty}B_t/t=0$ a.s. without using the law of iterated logarighm.

Question: I want to prove that  $\lim\limits_{t \rightarrow \infty}B_t/t=0$ a.s directly, without using the law of iterated logarithm.
I have read a hint that one can use the law of large numbers. If I look at the sequence $B_n/n, n\in \mathbb{N}$ I can write it as
$$\sum\limits_{i=1}^n\frac{B_i-B_{i-1}}{n},$$
this converges to zero by the strong law of large numbers.
So if I write
$$\frac{B_t}{t}=\frac{B_{\lfloor t\rfloor}}{\lfloor t \rfloor}\cdot\frac{\lfloor t \rfloor}{t}+\frac{B_t-B_{\lfloor t \rfloor }}{t},$$
I have that the first term converges a.s. to zero. So I only need to show that
$$\frac{B_t-B_{\lfloor t \rfloor }}{t}$$ converges a.s. to zero. Do you see how to prove this directly?
Answer: We want to show that $\frac{\sup_{s \in [0,1)} \lvert B_{n+s}-B_n\rvert}n$ tends to zero almost surely as $n$ goes to $\infty$.
We have that
$$ \mathbb P\Big(\sup_{s \in [0,1)} \lvert B_{n+s}-B_n\rvert \geq n^{2/3}\Big) = \mathbb P\Big(\sup_{s \in [0,1)} \lvert B_s\rvert \geq n^{2/3}\Big) \leq 2\mathbb P\Big(\sup_{s \in [0,1)} B_s\geq n^{2/3}\Big) = 2\mathbb P\Big(\lvert B_1 \rvert \geq n^{2/3}\Big) \leq \frac{2 \mathbb E\big[B_1^2\big]}{n^{4/3}}.$$
Borel-Cantelli implies that almost surely there is $\bar n = \bar n(\omega)$ such that for any $n\geq \bar n$ it holds that $\sup_{s \in [0,1)} \lvert B_{n+s}-B_n\rvert \leq n^{2/3}$, and thus $$\frac{\sup_{s \in [0,1)} \lvert B_{n+s}-B_n\rvert}n \leq n^{-1/3}.$$
Answer: Essentially what you need is the following (general) result: suppose you have a continuous-in-time stochastic processes $(X_t)_{t\geq 0}$ such that $\mathbb{E}(X_t) = 0$ and $\lim_{t\to \infty} \mathrm{Var}(X_t) = 0$, then $X_t \to 0 $ almost surely.
Comment: Thank you, do you know how to prove that? Using your assumptions I am only able to show that if $t_j$ is a sequence that converges to infinity, then we have a subsequence $t_{j_k}$ such that $X_{t_{j_k}}$ converges to zero a.s. But that is a lot weaker than what we need.
Comment: I think this is fairly standard result... so I need to find a reference for that
Comment: I don't think this is true. There are examples of an infite sequence $Y_n$ of random variables, where $E[Y_n]=0$, $V(Y_n)\rightarrow 0$, so the sequence converges to zero in probability, but there are examples where it does not converge a.s. If we define the function $Z_t$ to be $Y_{n+s}$ where $n \in \mathbb{N}$ and $s \in [0,1)$, $t=n+s$, we have a counterexample.
Comment: @user394334 thank you for pointing this out!


What's the difference between "feat", "artist1 X artist 2", "artist1 Vs. artist2" and "artist1 & artist 2"?

Question: In songs with multiple artists, I've seen 4 different ways to credit the other artists. 'Feat.', '&', 'X' and 'Vs'. How are they used?
(I have no example of 'V', but I've seen it used.)

Comment: Not sure if there's really a convention. I feel most of these are used interchangeably. For what it's worth, though: 'Feat' implies a short cameo, like a guest solo or a rapped bridge. '&' implies more of a 50/50 collaboration, or at least a joint effort. I've never seen 'X', but 'Vs.' is (to my knowledge) used to imply a contest. Examples are rap-battles, DJ-faceoffs and the like. All in my opinion, of course.
Comment: This discussion from Sound Design.SE also answers your question: https://sound.stackexchange.com/questions/27409/meaning-of-feat-pres-vs
Answer: Feat: means 'featuring', its when some artist appear on another's song providing some of the music or vocals.(one has the song, the other is a guest)
&: means a collaboration between the two artists to produce a song by both(like equals and not a guest)
Vs: means 'versus', is mostly used when mashing up or mixing two songs together, or when a studio has two artists work on heir own parts but into a single song(this is in a competitive manner)
x: could have the same meaning as 'vs' but maybe as '&', it is not widely used so am not sure how they define it.
Comment: I've also seen "vs." indicating that two artists are just collaborating.


How to export color changing animation from Blender to three.js

Question: I tried with gltf. My model changes color with changes in frames. So hope to get a positive response. Thanks in advance [from grey color1 to [Red color][2]
Comment: It may also be helpful to have Blender scene file, pls upload somewhere to make it available.
Comment: @AlexKhoroshylov where should i upload ?
Answer: As mentioned at the three.js forum, it's currently not possible to export animation of materials to glTF. Might be possible in the future though.
https://discourse.threejs.org/t/how-to-animate-alpha-in-blender-and-export-gltf-to-three-js/5428/2?u=mugen87


Probabilidade em lançamentos de dados

Question: Olá, galera! Estou aprendendo a programar java e me deparei com dois exercícios: no primeiro, eu deveria criar um script que simulasse um lançamento de um dado ; no segundo, um script que lançasse o dado 1 milhão de vezes e mostrasse quantas vezes cada número foi sorteado. Segue o script abaixo:
package dado;
import java.util.Scanner;
import java.util.Random;

public class Dado
{
    public static int dado()
    {
        Random rand = new Random();
        return rand.nextInt(6)+1;
    }
    public static void main(String[] args)
    {
        Scanner entrada = new Scanner(System.in);

        System.out.println("Bem vindo ao cassino! Deseja rolar o dado? [y/n]");
        char resp = entrada.nextLine().charAt(0);
        if (resp == 'y')
        {
            System.out.println("Resultado: " + dado());
            do
            {
                System.out.println("Deseja rolar o dado novamente? [y/n]");
                resp = entrada.nextLine().charAt(0);
                switch (resp)
                {
                    case 'y':
                        System.out.println("Resultado: " + dado());
                        break;
                    case 'n':
                        System.out.println("Finalizando...");
                        break;
                    default:
                        System.out.println("Resposta inválida. Responda apenas sim (y) ou não (n)");
                }
            }while(resp == 'y');
        }
        else if(resp == 'r')
        {
            int count1 = 0,
                count2 = 0,
                count3 = 0,
                count4 = 0,
                count5 = 0,
                count6 = 0;
            for(int i = 1; i <= 1000000; i++)
            {
                int num = dado();
                if (num == 1)
                {
                    count1++;
                }
                if (num == 2)
                {
                    count2++;
                }
                if (num == 3)
                {
                    count3++;
                }
                if (num == 4)
                {
                    count4++;
                }
                if (num == 5)
                {
                    count5++;
                }
                else
                {
                    count6++;
                }
            }
            System.out.printf("O dado rolou o número 1 %d vezes.\n", count1);
            System.out.printf("O dado rolou o número 2 %d vezes.\n", count2);
            System.out.printf("O dado rolou o número 3 %d vezes.\n", count3);
            System.out.printf("O dado rolou o número 4 %d vezes.\n", count4);
            System.out.printf("O dado rolou o número 5 %d vezes.\n", count5);
            System.out.printf("O dado rolou o número 6 %d vezes.\n", count6);
        }
        else
        {
            System.out.println("Finalizando...");
        }
    }
}

O código funcionou corretamente. Contudo, me supreendi com o resultado dos lançamentos sucessivos: o número 6 sempre é sorteado aproximadamente metade das vezes que os outros.
EX:
O dado rolou o número 1 166914 vezes.
O dado rolou o número 2 166765 vezes.
O dado rolou o número 3 167124 vezes.
O dado rolou o número 4 165377 vezes.
O dado rolou o número 5 166884 vezes.
O dado rolou o número 6 833116 vezes.

Por que isso acontece? Grato desde já!
Abraço!
Answer: Na realidade, o número 6 não foi sorteado 833116 vezes, é apenas um erro na contabilização das informações: repare que o elsese refere apenas à condicional if (num == 5), ou seja, caso num seja 1, 2, 3, 4 ou 6, o programa irá acrescer 1 ao count6, resultando em um número muito maior.
A propósito, no seu exemplo, o valor correto de count6 seria 1000000 - 166914 - 166765 - 167124 - 165377 - 166884 = 166936, um valor normal.
Para solucionar isso, você pode simplesmente substituir o else por if (num == 6) ou você pode trocar cada um dos if e else depois do if (num == 1) por else if (num == x), em que x vai de 2 a 6.
Comment: Nossa, cara, não me toquei nisso! Muito obrigado pela ajuda, vou corrigir o código. Abraço!

Probabilidade em lançamentos de dados


Unit Test JPA/Hibernate : No Persistence provider for EntityManager

Question: I want to enable Unit Test for my project. I have created the structure as follows.
Directory Structure
.
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   └── resources
│   │       ├── META-INF
│   │       │   ├── beans.xml        <-- Works fine in live
│   │       │   └── persistence.xml  <-- Works fine in live
│   └── test
│       ├── java
│       │   ├── com
│       │   │   └── test
│       │   │       └── model
│       │   │           ├── TestEntityManagerUtil.java
│       │   │           └── TestHibernate.java
│       └── resources
│           ├── META-INF
│           │   ├── beans.xml
│           │   └── persistence.xml

CODE
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="test" transaction-type="RESOURCE_LOCAL">

        <description>TEST Persistence Unit</description>
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <properties>

            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
            <property name="hibernate.connection.url" value="jdbc:mysql://XXX:3306/X" />
            <property name="hibernate.connection.username" value="X" />
            <property name="hibernate.connection.password" value="X" />

            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.transaction.flush_before_completion" value="true" />
        </properties>
    </persistence-unit>
</persistence>

TestEntityManagerUtil.java
public class TestEntityManagerUtil {
    public static EntityManagerFactory getEntityManagerFactory(){
        return Persistence.createEntityManagerFactory("test");
    }
}

TestHibernate.java
public class TestHibernate {

    private EntityManager em;

    @Before
    public void beforeEach(){
        // Exception occurs here
        em = TestEntityManagerUtil.getEntityManagerFactory().createEntityManager();
    }

    @After
    ....

    @Test
    ....
}

Exception
javax.persistence.PersistenceException: No Persistence provider for EntityManager named test
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:69)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
    at com.wellclub.model.TestEntityManagerUtil.getEntityManagerFactory(TestEntityManagerUtil.java:12)
    at com.wellclub.model.TestHibernate.beforeEach(TestHibernate.java:24)

The test persistence.xml is exploded in target/test-clases directory as it is.
Can anyone help me what i would be doing wrong.
Comment: After a second look, you are not developing an EE application. So I take my previous suggestion back.
Comment: You did not include your application server jars properly. I can tell you the steps to follow if you are using GlassFish, are you?
Answer: Please review your JPA implementation library (Hibernate) dependencies in your Maven POM.
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-entitymanager</artifactId>
  <version>${hibernate-core-version}</version>
</dependency>'

Otherwise add hibernate-entityManager.jar in a non Maven project
Edit:
Be aware that the JBoss example you are using is an EE application which uses CDI injection to obtain an EntityManager. A major misconception is to assume that a JUnit tests are operational in EE applications.... No, JUnit tests can neither run the JBoss container nor deploy your project. Yet you can refer to http://arquillian.org/invasion/ and also notice the JBoss example for an arquillian test
In other words, your JUnit is the SE way of testing an EntityManager and it in not operational in an application server like JBoss.
Comment: I have the same structure like the one used in [Jboss JDF for Hibernate4](https://github.com/jboss-jdf/jboss-as-quickstart/tree/master/hibernate4). I do not have enititymanager in the build but have `hibernate-core`, `hibernate-validator` and `hibernate-jpa-api`.
Comment: Yes, got the clue from you and already referring `arquillian`, Thanks.


Navegar pelas linhas de um arquivo txt com java

Question: Olá, tenho um arquivo txt com notas de alunos, onde cada linha representa um aluno e cada nota é separada por um ";", dessa forma:
5.6;9.7;1.3;8.6
9.6;8.9;8.8;7.3
3.5;1.2;6.3;4.4

Tenho que calcular a média de cada um por um programa em Java.
Fiz um método que lê esses dados e retorna uma única string com eles.
public static String Read(String path){
        String content = "";
        try {
            BufferedReader readArq = new BufferedReader(new FileReader(path));
            String line = "";

            try {
                line = readArq.readLine();
                while(line!=null){
                    content += line + "\n";
                    line = readArq.readLine();
                }

                readArq.close();
                return content;

            } catch (IOException ex) {
                return "Erro: Não foi possível ler o arquivo!";
            }

        } catch (FileNotFoundException ex) {
            return "Erro: Arquivo não encontrado!";
        }
    }

Porém não estou sabendo como pegar cada linha para poder calcular. Alguém poderia me ajudar?
Como separar cada valor na linha e converté-los para float, também sei fazer. Só não estou conseguido pegar as linhas
Answer: Depois que lemos cada linha, precisamos usar o String#split para separar as notas.
Eu fiz um exemplo comentado com código compatível com Java 8, veja:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

class Program {
  public static void main(String... args) throws IOException {
    Path path = Paths.get("notas.txt");

    // Pega todas as linhas
    List<String> lines = Files.readAllLines(path);

    for (String line : lines) {
      // Quebra a linha pelo ponto e virgula
      String[] notes = line.split(";");

      double total = 0;

      // Soma cada nota na linha
      for (String note : notes) {
        total += Double.parseDouble(note);
      }

      // Pega a média
      double average = total / notes.length;

      // Mostra o resultado
      System.out.println("Média: " + average);
    }
  }
}

Comment: Com esse Files.readAllLines eu não preciso dessa classe que criei para ler o arquivo, certo? Aí armazenando as linhas do arquivo na lista, basta fazer um loop para interagir com elas. A parte do split eu tenho noção, o restante que estava um pouco confuso, pq não pensei em armazenar em lista. Muito obrigada mesmo, me ajudou bastante
Comment: Isso mesmo, o Files.readAllLines nos economiza várias linhas, é muito bom quando vc quer ler arquivos não muito grandes.


Update Recyclerview with new SMS

Question: I'm working on an SMS app which is almost completed but I'm having problem updating the Recyclerview with new SMS, The new SMS isn't showing on list until I close and open my app
I've tried many solutions but I'm not able to make it work, Please Help
Thanks In Advance
My ConverstaionDetailsItemAdapter.java class where I'm extending Recyvlerview.Adapter
<code>    public class ConverstaionDetailsItemAdapter extends
    RecyclerView.Adapter<ConversationDetailsItemViewHolder> {
    Conversation conversation;
    List<Message> messages;
    Context mContext;

    public List<Message> getMessages() {
    return messages;
    }

    public void setMessages(List<Message> messages) {
    this.messages = messages;
    }

    public ConverstaionDetailsItemAdapter(List<Message> pMessages, Context context, Conversation
 pConversation) {
    this.messages = pMessages;
    mContext = context;
    this.conversation = pConversation;

}

@Override
public ConversationDetailsItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new ConversationDetailsItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_conversations_details_item, parent, false), mContext,conversation);
}

@Override
public void onBindViewHolder(final ConversationDetailsItemViewHolder holder, final int position) {
    Message message = messages.get(position);
    if (message != null) {
        holder.setConversationItem(message, position);
    }
}

@Override

public int getItemCount() {
    return (messages == null) ? 0 : messages.size();
}

@Override
public int getItemViewType(int position) {
    return position;
}
    }
</code>
My ViewHolder class
<code>    public class ConversationDetailsItemViewHolder extends RecyclerView.ViewHolder {

Context mContext;
Conversation conversation;
ImageView imageView;
public static TextView txtContactName, txtMessage, txtMessageTime;
private RelativeLayout rltRoot;

public ConversationDetailsItemViewHolder(View view, Context context, Conversation pConversation) {
    super(view);
    mContext = context;
    conversation = pConversation;
    rltRoot = view.findViewById(R.id.rlt_conversation_details_item_root);
    txtContactName = view.findViewById(R.id.txt_contact_name);
    txtMessageTime = view.findViewById(R.id.text_message_time);
    txtMessage = view.findViewById(R.id.text_message);
}

public void setConversationItem(Message item, final int position) {
    if(item.getType().equals("1")) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        txtMessage.setLayoutParams(params);
        txtMessage.setBackgroundResource(R.drawable.rounded_rectangle_incoming);

    } else {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        txtMessage.setLayoutParams(params);

        txtMessage.setBackgroundResource(R.drawable.rounded_rectangle);
    }
    txtMessage.setText(item.getBody()+"\n");

}
}
</code>
Answer: I have the similar project, check out my code
<code>package com.example.crimerigestration;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.MenuView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class CrimeListFragment extends Fragment {

private boolean mSubtitleVisible;

private RecyclerView mCrimeRecyclerView;
private CrimeAdapter crimeAdapter;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
    View v= inflater.inflate(R.layout.fragment_list_crime,container,false);

    mCrimeRecyclerView=(RecyclerView)v.findViewById(R.id.crime_recycler_view);
    mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    setHasOptionsMenu(true);
    updateUI();
    return v;
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.fragment_crime_list,menu);
    MenuItem menuItem=menu.findItem(R.id.show_subtitle);
    if(mSubtitleVisible){
        menuItem.setTitle(R.string.hide_subtitle);
    }
    else {
        menuItem.setTitle(R.string.show_subtitle);
    }

}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    //return super.onOptionsItemSelected(item);
    switch (item.getItemId()){
        case R.id.new_crime:
            Crime crime=new Crime();
            CrimeLab.get(getActivity()).addCrime(crime);
            Intent intent=CrimePagerActivity.newIntent(getActivity(),crime.getmID());
            startActivity(intent);
            return true;
        case R.id.show_subtitle:
            mSubtitleVisible=!mSubtitleVisible;
            getActivity().invalidateOptionsMenu();
            updateSubtitle();
            return true;
        default:
                return super.onOptionsItemSelected(item);

    }
}

private void updateSubtitle() {
    String subtitle=null;
    if(mSubtitleVisible){
        CrimeLab crimeLab=CrimeLab.get(getActivity());
        int count=crimeLab.getsCrimes().size();
        subtitle=getString(R.string.subtitle_formate,count);
    }
    AppCompatActivity appCompatActivity=(AppCompatActivity)getActivity();
    appCompatActivity.getSupportActionBar().setSubtitle(subtitle);
}

@Override
public void onResume() {
    super.onResume();
    updateUI();
}

private void updateUI() {
    CrimeLab crimeLab=CrimeLab.get(getActivity());
    ArrayList<Crime> crimes=crimeLab.getsCrimes();
    if (crimeAdapter==null){
        crimeAdapter =new CrimeAdapter(crimes);
        mCrimeRecyclerView.setAdapter(crimeAdapter);
    }
    else {
        crimeAdapter.setCrimes(crimes);
        crimeAdapter.notifyDataSetChanged();
    }

}

private class CrimeHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {

    private TextView mTitleTextView, mDateTextView;
    private ImageView mSolvedImageView;
    private Crime mCrime;

    public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
        super(inflater.inflate(R.layout.list_item_crime,parent,false));
        mTitleTextView=(TextView) itemView.findViewById(R.id.crime_title);
        mDateTextView=(TextView)itemView.findViewById(R.id.crime_date);
        mSolvedImageView=(ImageView)itemView.findViewById(R.id.imageView);

        itemView.setOnClickListener(this);
    }
    public void bind(Crime crime){
        this.mCrime=crime;
        mTitleTextView.setText(mCrime.getmTitle());
        mDateTextView.setText(mCrime.getmDate().toString());
        mSolvedImageView.setVisibility(mCrime.ismSolved()?View.VISIBLE:View.GONE);
    }

    @Override
    public void onClick(View v) {

        Intent intent=CrimePagerActivity.newIntent(getActivity(),mCrime.getmID());
        startActivity(intent);
    }
}

private class RequireCrimeHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {

    private TextView mTitleTextView, mDateTextView;
    private ImageView mSolvedImageView;
    private Button mRequireButton;
    private Crime mCrime;

    public RequireCrimeHolder(LayoutInflater inflater, ViewGroup parent) {
        super(inflater.inflate(R.layout.requried_to_police,parent,false));
        mTitleTextView=(TextView) itemView.findViewById(R.id.crime_title);
        mDateTextView=(TextView)itemView.findViewById(R.id.crime_date);
        mSolvedImageView=(ImageView)itemView.findViewById(R.id.imageView);
        mRequireButton=(Button)itemView.findViewById(R.id.button);
        Factory();
        itemView.setOnClickListener(this);
    }
    protected void Factory(){
        mRequireButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(),"No functionality
available",Toast.LENGTH_LONG).show();
            }
        });
    }
    public void bind(Crime crime){
        this.mCrime=crime;
        mTitleTextView.setText(mCrime.getmTitle());
        mDateTextView.setText(mCrime.getmDate().toString());
        mSolvedImageView.setVisibility(mCrime.ismSolved()?View.VISIBLE:View.GONE);
    }

    @Override
    public void onClick(View v) {
        Intent intent=CrimePagerActivity.newIntent(getActivity(),mCrime.getmID());
        startActivity(intent);        }
}

private class CrimeAdapter extends RecyclerView.Adapter{

    private ArrayList<Crime> mCrime;

    public CrimeAdapter(ArrayList<Crime> mCrime) {
        this.mCrime = mCrime;
    }

    @Override
    public int getItemViewType(int position) {
        if (mCrime.get(position).ismRequire() ){
            return 0;
        }
        else{
            return 1;
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
        LayoutInflater layoutInflater=LayoutInflater.from(getActivity());
        if (viewType==0){
            return new RequireCrimeHolder(layoutInflater,parent);
        }
        else{
            return new CrimeHolder(layoutInflater,parent);
        }

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int
position) {
        Crime crime=mCrime.get(position);
        if (crime.ismRequire() ){
            RequireCrimeHolder requireCrimeHolder= (RequireCrimeHolder) holder;
            requireCrimeHolder.bind(crime);
        }
        else{
            CrimeHolder crimeHolder= (CrimeHolder) holder;
            crimeHolder.bind(crime);
        }
    }

    @Override
    public int getItemCount() {
        return mCrime.size();
    }
    public void setCrimes(ArrayList<Crime> crime){
        this.mCrime=crime;
    }
}
}
</code>
Answer: You should call notifyItemInsert(0) (or size - 1, instead of 0, depending on sort asc/desc). If it doesn't work, try notifyDataSetChanged(), but don't keep it, cause it will kill performance.

Update Recyclerview with new SMS


Can't conditionally add script to Azure Devops Yaml pipeline

Question: I'm trying to make use of Container Job template in a pipeline which runs on both Microsoft Hosted and Self-Hosted (Containerized) build agents.
ContainerJob template works well when run in Microsoft Hosted but fails in Self-Hosted agent saying cannot run container inside a containerized build agent. Error makes sense though.
I figured that if below section can be added/removed conditionally then same Container Job template works in both agents.
${{ if not(parameters.isSelfHosted) }}:
  container:
    image: ${{ parameters.generalImage}}
    endpoint: ${{ parameters.endpoint}}
  environment: ${{ parameters.environment }}

But the condition is always true and container section is added always and failed in self-hosted agent always. I think expressions are not allowed randomly inside a template.
I can separate out this template into 2 templates and load them in respective build agent but that's the last resort. Any help in dynamically creating/altering a template is highly appreciated.
Answer: Are you looking for conditional container job? See my script:
parameters:
- name: isSelfHosted
  displayName: isSelfHosted
  type: boolean
  default: true
  values:
  - false
  - true

stages:
- stage: Build
  displayName: Build stage

  jobs:
  - job: Build
    displayName: Build
    ${{ if not(parameters.isSelfHosted) }}:
      container: mcr.microsoft.com/dotnet/core/sdk:2.2
      steps:
        - task: CmdLine@2
          inputs:
            script: |
                echo 2.2 SDK

    ${{ if eq(parameters.isSelfHosted, 'true') }}:
      container: mcr.microsoft.com/dotnet/core/sdk:2.1
      steps:
        - task: CmdLine@2
          inputs:
            script: |
                echo 2.1 SDK

I can choose which container (.net core 2.1 or .net core 2.2) via the value of isSelfHosted parameter.
It uses Runtime parameters, so I can manage the condition(check or uncheck the box) when running the pipeline:

Update:
See Job, stage, and step templates with parameters

Move the content below into a template file:
stages:
- stage: Build
  displayName: Build stage

  jobs:
  - job: Build
    displayName: Build
    ${{ if not(parameters.isSelfHosted) }}:
      container: mcr.microsoft.com/dotnet/core/sdk:2.2
      steps:
        - task: CmdLine@2
          inputs:
            script: |
                echo 2.2 SDK

    ${{ if eq(parameters.isSelfHosted, 'true') }}:
      container: mcr.microsoft.com/dotnet/core/sdk:2.1
      steps:
        - task: CmdLine@2
          inputs:
            script: |
                echo 2.1 SDK

Then the main azure-pipelines.yml should be
parameters:
- name: isSelfHosted
  displayName: isSelfHosted
  type: boolean
  default: true
  values:
  - false
  - true

stages:
- template: templates/xxx.yml  # Template reference
  parameters:
    isSelfHosted: xxx (Value of isSelfHosted parameter)

Comment: Thanks. But i'm trying to use it in  `template`. So i will be passing the parameter into the template and put the condition inside the template.
Comment: Thanks. But the the problem is accessing it inside the `xxx.yml` template and adding `container` script based on that condition.  The snippet i provided in my question should be in `xxx.yml` and should be adding only when `isSelfHosted` is false.


What's the difference between dissonance and beats?

Question: Are dissonance and beats (at a difference frequency) in music pretty much the same thing?
Answer: They're somewhat related, but not exactly the same thing - from https://en.wikipedia.org/wiki/Beat_(acoustics):

In acoustics, a beat is an interference pattern between two sounds of slightly different frequencies, perceived as a periodic variation in volume whose rate is the difference of the two frequencies.

If the difference in frequency between two notes is very slight (such that the two sounds would be perceived as the same note), you might get an audible beat frequency without there being a dissonance - it might just sound like a variation in volume, or a chorusing effect.
Once the difference becomes a little greater, you will get an audible beat frequency along with a sensation of roughness or dissonance.
As the frequency difference increases past the point that the ear can clearly distinguish two notes, we will move through intervals where there is a consonance (where the frequency difference is a simple ratio) and intervals where there is a relative dissonance, but because the notes are now far enough apart for the ear to distinguish, there may not be an obvious beat frequency even at the intervals where there is a perceived musical dissonance, unless the timbres and relative frequencies of the notes cause two or more strong partials to be close to one another in frequency.
So - it's possible to have a (slow) beat frequency without there being a dissonance, and it's possible to hear a musical dissonance without an obvious beat frequency.
Answer: (This answer is based on a previous version of the question. One of our well informed users has edited the question, making this answer somewhat irrelevant)

Are dissonance and beats (frequency) in music pretty much the same
  thing?

No, they are not the same at all, although the concept of dissonance is connected to frequencies in the mathematic sense. ( Musical terminology discusses dissonance in terms of intervals and harmonies, not frequencies.)
A frequency is a single value: For example 440hz.
Dissonance is something else entirely: It means how two piches at different frequencies sound and interact when heard together, either simultaneously or one quickly following the other, for example pitches of 440hz and 570hz played together. We call such relationships between pitches dissonant when their sound is "tense" or disharmonious - perhaps "unpleasant" to most ears.
The opposite of Dissonance is Consonance - more Dissonance = less Consonance. We call relationships between pitches consonant when their sound is "relaxing" or "harmonious" - perhaps "pleasant" to most ears.
Dissonance/Consonance can ostensibly be measured empirically, by examining different intervals on an oscilloscope, but like everything musical, the essence of dissonance and consonance remains subjective, dependent on listeners' taste, and musical context as explained here:
Quite a good discussion about consonance vs dissonance, that explains better than I could - Consonance and Dissonance

Intervals are traditionally considered either consonant or dissonant. Consonant intervals are usually described as pleasant and
  agreeable. Dissonant intervals are those that cause tension and desire
  to be resolved to consonant intervals. These descriptions relate to
  harmonious intervals.
In music theory, consonances are traditionally divided into two
  groups: perfect and imperfect. Perfect intervals (1, 4, 5, 8) are
  perfect consonances, as seen in the polyphonic music of the Middle
  Ages. Imperfect consonances (3 and 6) are either major or minor.
Dissonances can be divided into sharp and soft dissonances. This
  division relates mainly to atonal music. Minor second and major
  seventh are sharp dissonances. In tonal music, non-diatonic intervals
  (diminished and augmented) are usually dissonances, but in jazz and
  other African-American music, the tritone is "neutral", in other words
  it does not require resolution to a consonance.
All the divisions mentioned above are based on a shared understanding of their meaning; in the course of history, there have
  been different views about the concord of simultaneous tones. These
  definitions mainly relate to individual intervals in notation. For
  example, an augmented second and a minor third are identical as sounds
  in equal temperament, but in the Western notation tradition, the
  former is considered a dissonance, the latter a consonance.
It should also be noted that the concepts "consonance" and "dissonance" are highly context-related. How sonance (consonance or
  dissonance) is perceived depends on several music-psychological
  factors: temperament (other than equal temperament is perceived as
  dissonance); genre (in atonal music, consonances are scarce); timbre;
  the extent of the interval (can be several octaves); harmonic
  environments before and after the interval; and so on.*

It is clear is that dissonance is only possible with two contrasting frequencies or pitches.
Here are two interesting graphic representations of perceived dissonance, moving through the entire chromatic octave, in order of intervals. I'd call these representations "quasi-empirical".

Higher values/more red - represent greater dissonance of the interval in question.
Answer: I'd say no: dissonance is a psychoacoustic phenomenon, it is intimately tied to how people perceive sounds.  Beats are a physical characteristic of the amplitude envelope of a sound.  When the rate of variation in the amplitude variation is low enough (and deep enough) we can perceive this as amplitude variations, i.e. we can hear the beating.  If the rate of amplitude variation is fast enough, basically up into the audible range above say 20Hz or so, we no longer hear the beats as amplitude variations but instead hear it as part of the timbre of the sound, often described as roughness.
Answer: Dissonance is perceived as two notes (pitches) that do not sit well in each other's company, while consonance is generally two notes which 'sound well' together.
Beats are the phenomenon of two notes sounding together, and being very close in pitch. The closer they are, the slower the beats heard. When they are identical, the beats disappear. It's a recognised way to check tuning on some instruments. And, it's not necessarily dissonant - otherwise the chorus and flange effects wouldn't be so widely accepted! By the time they are less than a semitone apart, beats generally disappear to the naked ear. So, dissonance and beats are separate things, with no real relationship, as both dissonance and consonance require the two notes to be at least a semitone apart.
The other answers already go into more technical detail, so this is a simplified answer.