Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Question: Until today, I thought that for example:
i += j;

Was just a shortcut for:
i = i + j;

But if we try this:
int i = 5;
long j = 8;

Then i = i + j; will not compile but i += j; will compile fine.
Does it mean that in fact i += j; is a shortcut for something like this
i = (type of i) (i + j)?
Comment: I'm surprised Java allows this, being a stricter language than its predecessors.  Errors in casting can lead to critical failure, as was the case with Ariane5 Flight 501 where a 64-bit float cast to a 16-bit integer resulted in the crash.
Comment: In a flight control system written in Java, this would be the least of your worries @SQLDiver
Comment: Actually `i+=(long)j;` even will compile fine.
Comment: if it did require casting, where would you put it? `i += (int) f;` casts f before addition, so it's not equivalent. `(int) i += f;` casts the result after assignment, not equivalent either. there would be no place to put a cast that would signify that you want to cast the value after adding, but before assignment.
Comment: The constant push by one set of developers for accuracy and another for ease of use is really interesting.   We almost need two versions of the language, one that is amazingly precise and one that is easy to use.  Pushing Java from both directions moves it towards being unsuitable for either group.
Comment: @Tharindu What did you excpect? You are casting `j` to `long`, but `j` is already a `long`, so your casting doesn't do anything.
Comment: @RossDrew Why is that not a good idea?
Comment: @Tharindu that's consistent though, since the whole expression gets casted, so it's the same as as `i = (int)(i + (long)j);`
Comment: @BillK no, we do not need two versions. We only need the one version for accuracy. The "ease of use" is an illusion.  If you opt for features that provide "ease of use" you invariably end up paying for them hundredfold in maintenance costs.  Let me point you to good old edsgar: https://www.cs.utexas.edu/users/EWD/transcriptions/EWD06xx/EWD667.html (search for "ease of programming" in the text.)
Comment: I think Douglas Crockford wins the argument after all... This behavior is terrible and lots of languages have similar problems around conversions.
Comment: "it's floating point is not precise" let's correct that-> "floating point is not precise" (Java follows IEEE floating point standard). If you use floating point when calculations and you haven't analysed whether the error is within the bounds required for your application, and your application is critical, you are the one to blame - not the language.
Comment: @RossDrew The Ariane5 was a space rocket.
Comment: This is a huge source of bugs in Java.
Comment: @MikeNakis The lack of paying attention to ease of use has lead to people not being interested in or even hating java--especially new users.  This has lead to quite a few easy to use & inaccurate languages along the line of ruby/groovy.  Kotlin seems to be a good balance of a usable static language, but it's yet another response to Java not moving towards usability.  (Don't get me wrong, I LOVE Java and they have made inroads towards usability such as not requiring two wrapper classes to read a text file, it just may be too late).
Comment: As already mentionned, there is no good place to put a cast so the only other option would be to make it error and then you would have to use the long expression `i = (int)(i + j)`. Probably the best option would be to have a compiler option to generate a warning or error...
Comment: @LukeHutchison Is it? Evidence?. I've been programming in Java since 1997 and I've never seen such a bug.
Comment: @user207421 yes, this is quite obviously a source of loss-of-precision bugs, since it allows implicit narrowing casts without any sort of warning to the user. There's a reason you can't do `i = j;` using the example in the question. If that were allowed without warning, you'd be throwing away half of `j` without even knowing it. The problem is compounded because implicit widening casts are allowed. So for example, consider: `double x = 0.0; int y = 1; double z = 1.5; y += z; x += y;` : there are no warnings anywhere, but if you don't realize `y` is an `int`, you lose `.5` with no warning.
Answer: As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

An example cited from §15.26.2

[...] the following code is correct:
short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);

In other words, your assumption is correct.
Comment: @ronnieaka: I'm guessing that the language designers felt that in one case (`i += j`), it is safer to assume that the loss of precision is desired as opposed to the other case (`i = i + j`)
Comment: So `i+=j` compiles as I checked myself, but it would result in loss of precision right? If that's the case, why doesn't it allow it to happen in i=i+j also? Why bug us there?
Answer: A good example of this casting is using *= or /=
byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57

or
byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40

or
char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'

or
char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'

Comment: @DavidWallace Any character as long as it is `A` ;)
Comment: Yeah, but I can just see some beginner coming here, reading this, and going away thinking that you can convert any character from upper case to lower case by multiplying it by 1.5.
Comment: @PeterLawrey & @DavidWallace I will reveal your **secret**- `ch += 32`  =D
Comment: @AkshatAgarwal ch is a char. 65 * 1.5 = 97.5 -> Got it?
Answer: Very good question. The Java Language specification confirms your suggestion.

For example, the following code is correct:
short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);

Comment: Or more fun: "int x=33333333; x+=1.0f;".
Comment: @supercat , what trickery is this? A widening conversion that is incorrectly rounded, followed by an addition that doesn't actually change the result, casting to int again to produce a result that is most unexpected for normal human minds.
Comment: @neXus: IMHO, the conversion rules should have treated `double->float` as widening, on the basis that values of type `float` identify real numbers less specifically than those of type `double`.  If one views `double` as a complete postal address and `float` as a 5-digit postal code, it's possible to satisfy a request for a postal code given a complete address, but it's not possible to accurately specify a request for a complete address given just a postal code.  Converting a street address to a postal code is a lossy operation, *but*...
Comment: ...someone who needs a complete address wouldn't generally be asking for just a postal code.  Conversion from `float->double` is equivalent to converting US postal code 90210 with "US Post Office, Beverly Hills CA 90210".
Answer: Yes,
basically when we write
i += l;

the compiler converts this to
i = (int) (i + l);

I just checked the .class file code.
Really a good thing to know.
Comment: @hexafraction: what you mean by class file? if you asking about the class file i mentioned in my post than it's the complied version of your java class
Comment: @glglgl I disagree that one should rely on font to distinguish in those cases... but everybody has the freedom to choose what thinks is best.
Comment: Oh, you mentioned "the" class file code, which led me to believe a specific classfile was involved. I understand what you mean now.
Comment: Can you tell me which classfile this is?
Comment: @Bogdan That shouldn't be a problem with properly used fonts. A programmer which chooses whe wrong font for programming should clearly think about how to proceed...
Comment: On some old MATLAB version, the default font size was one which made O and 0 look the same in Times New Roman, as well as 1 and l. It was always the first step that I did to change the font sie to something useful...
Answer: you need to cast from long to int explicitly in case of i = i + l  then it will compile and give correct output. like
i = i + (int)l;

or
i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.

but in case of += it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.
Comment: In this case, the "implicit cast" could be lossy. In reality, as @LukasEder states in his answer, the cast to `int` is performed *after* the `+`. The compiler would (should?) throw a warning if it really did cast the `long` to `int`.
Answer: The problem here involves type casting.
When you add int and long,

The int object is cast to long & both are added and you get a long object.
But the long object cannot be implicitly cast to int. So, you have to do that explicitly.

But += is coded in such a way that it does type casting. i = (int) (i + m)
Answer: In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
 byte -> short -> int -> long -> float -> double.
The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion
Comment: A `float` can't hold every possible `int` value, and a `double` can't hold every possible `long` value.
Comment: Hey, but `long` is 2 times larger than `float`.
Comment: What do you mean by "safely converted" ? From latter part of the answer I can deduce that you  meant automatic conversion ( implicit cast ) which is of course not true in case of float -> long.
float pi = 3.14f; long b = pi; will result in compiler error.
Comment: You'd be better off differentiating floating point primitive types with integer primitive types. They're not the same thing.
Comment: Java has simplistic conversion rules that require the use of casts in many patterns where behavior without casts would otherwise match expectations, but doesn't require casts in many patterns that are usually erroneous.  For example, a compiler will accept `double d=33333333+1.0f;` without complaint, even though the result 33333332.0 would likely not be what was intended (incidentally, the arithmetically-correct answer of 33333334.0f would be representable as either `float` or `int`).
Answer: Sometimes, such a question can be asked at an interview.
For example, when you write:
int a = 2;
long b = 3;
a = a + b;

there is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception.
So to avoid it, you must write your code like this:
int a = 2;
long b = 3;
a += b;// No compilation error or any exception due to the auto typecasting

Comment: Thanks for the insight regarding the comparison of the `op` use in C++ to its use in Java. I always like seeing these bits of trivia and I do think they contribute something to the conversation that may often be left out.
Comment: However the question itself *is* interesting, asking this *in an interview* is stupid. It does not prove that the person can produce a good quality code - it just proves that he had enough patience to prepare for an Oracle certificate exam. And "avoiding" the incompatible types by using a dangerous auto-conversion and thus hiding the possible overflow error, probably even *proves* that the person is not able to produce probable a good quality code. Damn the Java authors for all these auto-conversions and auto-boxing and all!
Answer: The main difference is that with a = a + b, there is no typecasting going on, and so the compiler gets angry at you for not typecasting. But with a += b, what it's really doing is typecasting b to a type compatible with a. So if you do
    int a = 5;
    long b = 10;
    a += b;
    System.out.println(a);

What you're really doing is:
    int a = 5;
    long b = 10;
    a = a + (int) b;
    System.out.println(a);

Comment: Compound assignment operators perform a narrowing conversion of the result of the binary operation, not the right-hand operand. So in your example, 'a += b' is not equivalent to 'a = a + (int) b' but, as explained by other answers here, to 'a = (int)(a + b)'.
Answer: Subtle point here...
There is an implicit typecast for i+j when j is a double and i is an int.
Java ALWAYS converts an integer into a double when there is an operation between them.
To clarify i+=j where i is an integer and j is a double can be described as
i = <int>(<double>i + j)

See: this description of implicit casting
You might want to typecast j to (int) in this case for clarity.
Comment: I think a more interesting case might be `int someInt = 16777217; float someFloat = 0.0f; someInt += someFloat;`.  Adding zero to `someInt` shouldn't affect its value, but promoting `someInt` to `float` may change its value.
Answer: Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.
That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.
public class PlusEquals {
    public static void main(String[] args) {
        byte a = 1;
        byte b = 2;
        a = a + b;
        System.out.println(a);
    }
}

What does this program print?
Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.
But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.
Answer: As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
An example cited from §15.26.2
[...] the following code is correct:
short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);

In other words, your assumption is correct.


How to set a field's 'translatable' property

Question: When I create a new field type in Drupal it seems to be automatically assigned a 'translatable' property and it's not always right. For example, I would expect a Long Text field type to be marked as translatable = TRUE, but for some reason it's coming in as FALSE sometimes. However, body is TRUE.
Is there a place where this property is exposed in the UI and changeable?
I have the i18n module installed and enabled.
Answer: Entity translation exposes a checkbox which allows to set the translatable property.
It also provides a user interface to actually use field translation, there isn't much you can do with translatable fields without that module anyway.
Answer: Try the following code:
<code>function mymodule_field_available_languages_alter(&$languages, $context) {
  $languages = array();
}
</code>
The hook is documented in Multilingual Field API, and hook_field_available_languages_alter().
somehow i18n does not respect that ..
Comment: A bit late, but i18n is not supposed to respect this. I18n doesn't care about field level translatability, it translates complete nodes. What it provides as an alternative is i18n_sync, which allows to keep certain fields in sync between node translations.


In how many ways can $n$ toys be distributed to $n$ children so that exactly one child does not receive a toy?

Question: $n$ toys are to be distributed amongst $n$ children. The total number of ways in which these toys can be distributed so that exactly one child gets no toy is equal to?
I tried it with the concept that if one child gets no toy, then we are left with $n$ toys to be distributed amongst $n-1$ children. But this does not help and the answer is not coming.
Please somebody,can you give the detailed explanation how to solve this sum. Thanks
Comment: That is a really mean way to distribute toys to children.
Comment: That means the toys must be distinct, which should be stated in the problem.
Comment: One child gets no toy. Every other child gets a toy. There is one more toy left, give it to one child. Total ways: $n(n-1)$. The $n$ is to choose which child gets no toy. The $n-1$ is to choose which other child gets $2$ toys.
Comment: Thanks , but what will be the exact answer?
Comment: The exact answer is in Zach Teitler's comment.  It assumes the toys are identical.
Comment: But the answer guven is n!*nC2
Answer: The question is stated as follows:

If $n$ $\color{red}{different}$ toys have to be distributed among $n$ children, then the total number of ways in which these toys can be distributed so that exactly one child gets no toy is equal to?

Source: link
Step 1: There are $n$ ways to choose the unlucky child.
Step 2: There are ${n\choose 2}$ ways to choose $2$ toys. Note: only 1 child can get maximum $2$ toys, otherwise more than $1$ child will get no toy.
Step 3: There are $n-1$ ways to choose the luckiest child, who will get the $2$ toys.
Step 4: There are $(n-2)!$ ways to distribute the rest $n-2$ toys to the rest $n-2$ children.
Hence:
$$n\cdot {n\choose 2}\cdot (n-1)\cdot (n-2)!=n!{n\choose 2}.$$
Answer: Judging by the answer you provided in the comments, the toys must be distinct.  Therefore, we wish to count the number of ways $n$ different toys can be distributed to $n$ children if exactly one child does not receive a toy.
Strategy:

Choose which of the $n$ children receives no toy.
If the $n$ toys are distributed to the remaining $n - 1$ children, exactly one of those $n - 1$ children will receive two toys.  Choose that child.
Choose which two of the $n$ toys that child receives.
Give each of the remaining $n - 2$ children one of the remaining $n - 2$ toys.
Comment: Tausig's answer is correct. It can be simplified slightly as follows:  For 2, 3, and 4 substitute 2': Choose 2 of the $n$ toys and tie them together as if they were $1$ toy, creating $n-1$ newtoys, and 3' Distribute the $n-1$ newtoys to the remaining $n-1$ children.
Answer: $1$ child gets $0$ toys, $(n-1)$ children get $1$ toy each, any of the $(n-1)$ children can get a $2$nd toy.
$1$ child can be left without a toy in $n$ ways. The 'extra' toy can be chosen in $n$ ways and so can be distributed among the remaining $(n-1)$ children in $n(n-1)$ ways. The remaining $(n-1)$ toys can be distributed among the remaining $(n-1)$ children (one toy each) in $(n-1)$! ways.
However, if the child getting $2$ toys gets toy $A$ as the 'extra' toy and toy $B$ as the 'ordinary' toy, this is the same as if this child gets toy B as the extra toy and toy $A$ as the ordinary toy. So we have counted $2\times$ as many combinations as we need.
So the number of distributions is
$$  \frac{n  n(n-1)(n-1)! }{ 2}
= n!  \frac{n(n-1)}{2}
= n! \frac{ n!}{2!(n-2)!}
= n!  C(n,2). $$
Comment: @Leucippus Why delete? [Wrong answers](//math.meta.stackexchange.com/q/27423/290189) are to be downvoted instead of deleted.


javax.mail.MessagingException: Could not convert socket to TLS

Question: I have enother convert socket exception. Stackoverflow linked me to related answer and i have done everything people suggest there.
Here we have exception description :

Exception in thread "main" javax.mail.MessagingException: Could not convert socket to TLS;
    nested exception is:
      java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing
           implementation (algorithm: Default, provider: SunJSSE, class:
          sun.security.ssl.SSLContextImpl$DefaultSSLContext)
      at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1880)
      at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:648)
      at javax.mail.Service.connect(Service.java:295)
      at XMailMessenger.MailMessenger.sendMail(MailMessenger.java:414)
      at alfa.runner.main(runner.java:38)
          Caused by: java.net.SocketException: java.security.NoSuchAlgorithmException: Error
           constructing implementation (algorithm: Default, provider: SunJSSE, class:
          sun.security.ssl.SSLContextImpl$DefaultSSLContext)
      at javax.net.ssl.DefaultSSLSocketFactory.throwException(Unknown Source)
      at javax.net.ssl.DefaultSSLSocketFactory.createSocket(Unknown Source)
      at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:432)
      at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1875)
      ... 4 more
          Caused by: java.security.NoSuchAlgorithmException: Error constructing implementation
          (algorithm: Default, provider: SunJSSE, class:
          sun.security.ssl.SSLContextImpl$DefaultSSLContext)
      at java.security.Provider$Service.newInstance(Unknown Source)
      at sun.security.jca.GetInstance.getInstance(Unknown Source)
      at sun.security.jca.GetInstance.getInstance(Unknown Source)
      at javax.net.ssl.SSLContext.getInstance(Unknown Source)
      at javax.net.ssl.SSLContext.getDefault(Unknown Source)
      at javax.net.ssl.SSLSocketFactory.getDefault(Unknown Source)
      at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:427)
      ... 5 more
         Caused by: java.lang.NullPointerException
      at sun.security.ssl.KeyManagerFactoryImpl$SunX509.engineInit(Unknown Source)
      at javax.net.ssl.KeyManagerFactory.init(Unknown Source)
      at sun.security.ssl.SSLContextImpl$DefaultSSLContext.getDefaultKeyManager(Unknown
          Source)
      at sun.security.ssl.SSLContextImpl$DefaultSSLContext.(Unknown Source)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
      at java.lang.reflect.Constructor.newInstance(Unknown Source)
      at java.lang.Class.newInstance(Unknown Source)
      ... 12 more

So i decide to write 2 additional classes:
<code>      package XMailMessenger;

     import javax.net.ssl.X509TrustManager;
     import java.security.cert.X509Certificate;
     /**
      * @author Raminderjeet Singh
      */
      public class DummyTrustManager implements X509TrustManager {

      public void checkClientTrusted(X509Certificate[] cert, String authType) {
    // everything is trusted

   }

    public void checkServerTrusted(X509Certificate[] cert, String authType) {
   // everything is trusted
   }

   public X509Certificate[] getAcceptedIssuers() {
      return new X509Certificate[0];
   }
   }
</code>
and the second one:
<code> package XMailMessenger;

  import java.io.IOException;
  import java.net.InetAddress;
  import java.net.Socket;

  import javax.net.SocketFactory;
   import javax.net.ssl.*;

  /**
  * @author Raminderjeet Singh
 */
  public class DummySSLSocketFactory extends SSLSocketFactory {
   private SSLSocketFactory factory;

    public DummySSLSocketFactory() {
try {
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null,
             new TrustManager[] { new DummyTrustManager()},
             null);
    factory = (SSLSocketFactory)sslcontext.getSocketFactory();
} catch(Exception ex) {
    // ignore
}
}

public static SocketFactory getDefault() {
return new DummySSLSocketFactory();
}

public Socket createSocket() throws IOException {
return factory.createSocket();
}

public Socket createSocket(Socket socket, String s, int i, boolean flag)
            throws IOException {
return factory.createSocket(socket, s, i, flag);
}

   public Socket createSocket(InetAddress inaddr, int i,
            InetAddress inaddr1, int j) throws IOException {
return factory.createSocket(inaddr, i, inaddr1, j);
    }

   public Socket createSocket(InetAddress inaddr, int i)
            throws IOException {
 return factory.createSocket(inaddr, i);
   }

  public Socket createSocket(String s, int i, InetAddress inaddr, int j)
            throws IOException {
  return factory.createSocket(s, i, inaddr, j);
   }

  public Socket createSocket(String s, int i) throws IOException {
  return factory.createSocket(s, i);
  }

  public String[] getDefaultCipherSuites() {
  return factory.getDefaultCipherSuites();
  }

    public String[] getSupportedCipherSuites() {
        return factory.getSupportedCipherSuites();
   }
  }
</code>
Finally we have method to send mail:
<code>        Properties props = new Properties();
    props.put("mail.smtp.host", currentSettingsDocument.getSMTPHostServer());
    props.put("mail.smtp.user", currentSettingsDocument.getLogin());
    props.put("mail.smtp.password", currentSettingsDocument.getPassword());
    props.put("mail.smtp.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.timeout" , "3000");
    props.put("mail.smtp.starttls.enable", "false");
    props.put("mail.smtp.socketFactory.port", "465");

    props.put("mail.smtp.socketFactory.fallback", "false");
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    props.put("javax.net.debug","ssl,session");

    // Required to avoid security exception.
        Authenticator authentication = new Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
             return new PasswordAuthentication(currentSettingsDocument.getLogin() ,
            currentSettingsDocument.getPassword());
          }
         };
    Session session = Session.getInstance(props, authentication);
    // create some properties and get the default Session

    // create a message
    MimeMessage msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new

       InternetAddress(currentSettingsDocument.getSenderMail());
   msg.setFrom(addressFrom);

       for(InternetAddress addr: recepients )
        msg.addRecipient(Message.RecipientType.TO, addr );

    // Optional : You can also set your custom headers in the Email if you
    //
    // msg.addHeader("MyHeaderName", "myHeaderValue");

    // Setting the Subject and Content Type
    msg.setContent("1111", "text/plain");
    Transport transport = session.getTransport("smtp");
            Document.getSMTPHostServer(), Document.getPassword());
    transport.connect(currentSettingsDocument.getSMTPHostServer(), 465,
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();
</code>
And after calling sendMessage i get exception :

окт 18, 2013 5:36:18 PM XMailMessenger.MailMessenger sendMail
  SEVERE: null
  javax.mail.MessagingException: Exception reading response;
    nested exception is:
      java.net.SocketTimeoutException: Read timed out

PS Google mail works properly
Answer: The exception is caused by the unsupported TLS on old Windows (XP, Vista) and thrown by the class SocketFetcher (package com.sun.mail.util;) at line
<code>MailSSLSocketFactory msf = new MailSSLSocketFactory();
</code>
and MailSSLSocketFactory (same package) <code>/**
     * Initializes a new MailSSLSocketFactory.
     *
     * @throws  GeneralSecurityException
     */
    public MailSSLSocketFactory() throws GeneralSecurityException {
    this("TLS");
    }
</code>
Comment: what is the solution for this?


Alternative to data binding in Android?

Question: So I'm picking up Android dev again after 5 years break. While I now write my app in Jetpack compose, I learned that I might be going back to a project with Fragment/XML layout soon and I'm trying to do my homework.
I heard that some people aren't a fan of data binding and I can agree - mixing business logic in XML, too much boilerplate code, and slow compile.
In my last project back in 2017, we used ButterKnife (now deprecated) so I've never used data binding personally. My question is, if they're not using data binding, then what do people use to do reactive layout with XML and LiveData/flow? Is there some sort of library? Or is data binding your only option?
Answer: Data Binding is multi-direction way, you can set and get inside and from your view, if you want an unidirectional way you can use view Binding, if you want to learn more about it see the link below.
view binding
Answer: If you want to build UI dynamically I would suggest to look into Compose https://developer.android.com/jetpack/compose.
This is the newest guy in the hood.
Comment: Yes I've built an app using compose and it's great, I'm just wondering what the older XML projects look like as I've been out of the loop for a while
Comment: Compose has great inter-op with XML. You can use `ComposeView` inside your existing XML:s to use both Data/ViewBinding and Compose.

Alternative to data binding in Android?


Get all related sister (same content type) nodes through a view in Drupal 7

Question: On my node detail page, I am hoping to show all the related nodes through a view which have the same taxonomy term(s) selected.
How can I make sure to get the related nodes on the node detail page (Note:- I don't have taxonomy term in the URL )
Thanks.
Answer: To filter nodes with the same taxonomy term, when a node is displayed as main content (/node/???)
View , Display as block
2 contextual filters:

Content: nid -> provide default value: content id from url - more: exclude
Content: Has taxonomy term ID -> provide default value: taxonomy term id from url

It is important to put the contextual filters in this order, the first filter excludes the actual node from display, the exclude-checkbox is at the end under "More"
add additional filters, for example:

Content: your content-type
Content: Published (Yes)

Put the view block right below your Main page content in the Content-Region


Prove that two Cauchy sequences are convergent.

Question: Prove that $$x_n+y_n$$ is Cauchy without using the theorem: A sequence is Cauchy iff it converges to some point.
My attempt:
Assume that $x_n$ and $y_n$ are convergent. That is by definition $$\vert x_n - a \vert \lt \frac{\epsilon}{2}$$ $$\vert y_n - a \vert \lt \frac{\epsilon}{2}$$
$$\vert x_n -a \vert + \vert y_n - a \vert \lt \frac{\epsilon}{2} + \frac{\epsilon}{2} = \epsilon$$ By definition of convergence $$x_n + y_n$$ is Cauchy
Comment: Did you mean  to write $y_n-a$ in the third stage?
Comment: yes my mistake.
Comment: We don't need to assume equal limit for $x_n$ and $y_n$.
Comment: what do you mean?
Comment: @K.Gibson Can you please clarify: are you proving that the sum of two Cauchy sequences is Cauchy, or that the sum of two convergent sequences is convergent? As you say you are not allowed to use the equivalence of those two conditions, for the purpose of the proof we must first know which of those two conditions is at play here.
Comment: the sum of two convergent sequences are cauchy
Comment: @K.Gibson Would you mind stating that precisely in the question? The title says one thing and the text says another, and neither says what we can assume for $(x_n)$ and $(y_n)$.
Comment: Yes the title is the question. I got them mixed up.
Comment: The only assumption is that they are Cauchy
Comment: @K.Gibson I've posted an answer, but there are other answers below, and due to not having the precise question to answer to - all those answers are to different questions. Hope one of them is to *your* question.
Answer: We have that

$\vert x_n - L_1 \vert \lt \frac{\epsilon}{2}$
$\vert y_n - L_2 \vert \lt \frac{\epsilon}{2}$

then by triangle inequality
$$\vert x_n+y_n-(L_1+L_2)\vert\le \vert x_n -L_1 \vert + \vert y_n - L_2 \vert \lt \frac{\epsilon}{2} + \frac{\epsilon}{2} = \epsilon$$
and $x_n+y_n$ converges.
Answer: Let's assume that $(x_n)$ and $(y_n)$ are two Cauchy sequences. We will prove that $(x_n+y_n)$ is Cauchy.
Pick $\varepsilon>0$. For this $\varepsilon$, there is $n_1\in\mathbb N$ such that:
$$|x_m-x_n|<\frac{\varepsilon}{2}\text{ for }m,n\ge n_1$$
and also there is $n_2\in\mathbb N$ such that:
$$|y_m-y_n|<\frac{\varepsilon}{2}\text{ for }m,n\ge n_2$$
Now let $n_0$ be the maximum of $n_1, n_2$. Then, for $m,n\ge n_0$ we obviously have $m,n\ge n_1, n_2$, so the following is valid (using the triangle inequality):
$$\begin{array}{rcl}|(x_m+y_m)-(x_n+y_n)|&=&|(x_m-x_n)+(y_m-y_n)|\\&\le&|x_m-x_n|+|y_m-y_n|\\&\lt&\frac{\varepsilon}{2}+\frac{\varepsilon}{2}\\&=&\varepsilon\end{array}$$
Answer: Take $\varepsilon>0$. There are $N_1,N_2\in\mathbb N$ such that$$n\geqslant N_1\implies\lvert x_n-a\rvert<\frac\varepsilon4\text{ and }n\geqslant N_2\implies\lvert y_n-b\rvert<\frac\varepsilon4.$$Let $N=\max\{N_1,N_2\}$. Then, if $m,n\geqslant N$, you have\begin{align}\bigl\lvert(x_m+y_m)-(x_n+y_n)\bigr\rvert&=\lvert x_m-a+a-x_n+y_m-b+b-y_n\rvert\\&\leqslant\lvert x_m-a\rvert+\lvert x_n-a\rvert+\lvert y_m-b\rvert+\lvert y_n-b\rvert\\&<\frac\varepsilon4+\frac\varepsilon4+\frac\varepsilon4+\frac\varepsilon4\\&=\varepsilon.\end{align}


Como reduzir o espaçamento das TABS com os cantos da view usando CSS - Asp.Net MVC

Question: Quando insiro uma tab na minha view, há um espaçamento muito exagerado com as bordas da page dentro da modal. Estou usando um framework chamado Remark, mas acredito que isso possa se resolver com CSS. Alguém sabe como fazer isso?

            <vc:summary />

                        Dados Gerais

                        Endereços

                        Documentos

                        Contatos

                        Javascript

                        Menu

                            Home
                            Components
                            Css
                            Javascript

                            @await Html.PartialAsync("_Pessoa")

                            @if (Model.PessoaNatureza == PessoaNatureza.Fisica)
                            {

                                    @await Html.PartialAsync("_PessoaFisica")

                            }
                            else if (Model.PessoaNatureza == PessoaNatureza.Juridica)
                            {

                                    @await Html.PartialAsync("_PessoaJuridica")

                            }

                        @*

                                <button type="button" class="btn btn-primary dropdown-toggle" id="exampleColorDropdown2"
                                        data-toggle="dropdown" aria-expanded="false">
                                    Primary
                                </button>

                                    Action
                                    Another action
                                    Something else here
                                    Separated link

*@

                        Negant parvos fructu nostram mutans supplicii ac dissentias, maius tibi licebit
                        ruinae philosophia. Salutatus repellere titillaret expetendum
                        ipsi. Cupiditates intellegam exercitumque privatio concederetur,
                        sempiternum, verbis malint dissensio nullas noctesque earumque.

                        Benivole horrent tantalo fuisset adamare fugiendam tractatos indicaverunt animis
                        chaere, brevi minuendas, ubi angoribus iisque deorsum audita
                        haec dedocendi utilitas. Panaetium erimus platonem varias
                        imperitos animum, iudiciorumque operis multa disputando.

                        Metus subtilius texit consilio fugiendam, opinionum levius amici inertissimae pecuniae
                        tribus ordiamur, alienus artes solitudo, minime praesidia
                        proficiscuntur reiciat detracta involuta veterum. Rutilius
                        quis honestatis hominum, quisquis percussit sibi explicari.

Comment: Provavelmente tem um padding ou margin aplicados. Testa colocando um padding: 0 na tua classe .panel
Comment: Obrigado pela ajuda @Bia Silva. Encontrei agora 4 classes pt-10 pl-15 pr-15 que setam o padding diretamente no html... Funcionou!!!!! Obrigado :)
Comment: Bacana, fico feliz por ter te ajudado! :D
Answer: Se você for no seu css, provavelmente na classe .panel terá um padding, é só setar ele para 0, padding: 0;.
Ou na classe .panel-body ou .container-fluid tem um margin, também é só setar para 0, margin: 0;
Caso você tenha um style.css é só colocar:
.panel{
     padding: 0;
}

ou
.panel-body{
     margin: 0;
}

ou
.container-fluid{
     margin: 0;
}

Observação:
Caso seja a classe .container-fluid recomendo criar uma nova classe e setar a partir dela, pois essa classe pode estar sendo utilizada ou vai ser utilizada em outros pontos so seu projeto, podendo assim "quebrar" algo.


Junk values getting updated to text file

Question: I am trying to update a file with some value. But there are few junk values are also getting updated with the original content while saving. Using the below code.
public class WriteToFile{

    public static void main(String[] args){
        Path path = Paths.get("C:\\someFile.txt");
        String fileContent = new String("someText");
        if (Files.exists(path)) {
            final File filePath = new File("C:\\someFile.txt");
            try {
                FileUtils.writeFile(filePath,fileContent);
            } catch (final Exception e1) {
            // TODO What if writing to the state file fails??
            }
        }
     }

    public class FileUploadUtils {

     public static void writeFile(final File filePath, final Object
     byteFileContent) {
         try (FileOutputStream fileOutputStream = new FileOutputStream(filePath);
              ObjectOutputStream out = new ObjectOutputStream(fileOutputStream)) {
              out.writeObject(byteFileContent);
         } catch (final IOException io) {
             io.printStackTrace();
         }
     }
   }

I am able to write the content to file also, but it is adding some junk characters also. like "' t SomeText"
Comment: Possible duplicate of [writeUTF(String s) vs writeObject(String s)](https://stackoverflow.com/questions/19269688/writeutfstring-s-vs-writeobjectstring-s)
Comment: Have you checked the encoding of your file and of your String you want to write, and if the junk characters are the BOM?
Comment: You shouldn't be using an `ObjectOutputStream`, unless you want to specific Java serialization format used by it. Instead you need to use an `OutputStreamWriter`.
Answer: The ObjectOutputStream seems to add some values while writing the data to the file.
Why won't you directly use the FileOutputStream you created and pass the data as bytes ?
public static void main(String[] args) {

    Path path = Paths.get("C:\\someFile.txt");
    String fileContent = new String("someText");
    if (Files.exists(path)) {
        final File filePath = new File("C:\\someFile.txt");
        try {

            FileUploadUtils.writeFile(
                    filePath, fileContent.getBytes());
        } catch (final Exception e1) {
            // TODO What if writing to the state file fails??
        }
    }

}

public class FileUploadUtils {

public static void writeFile(final File filePath, final byte[] byteFileContent) {
    try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
        fileOutputStream.write(byteFileContent);
    } catch (final IOException io) {
        io.printStackTrace();
    }
}
}

Comment: If the OP wants to write strings, it would be better to use an `OutputStreamWriter` with the appropriate character set.


Htaccess - Detecting the URL

Question: For my family members I was giving each person their own subdomain
(sister1.mydomain.com, sister2.mydomain.com, etc...)
I was using PHP to detect the domain, and then I'd load information related to the subdomain dynamically.
I'd like to get rid of the subdomains and use the power of .htaccess
My goal is to give the same URL:

www.mydomain.com/sister1
www.mydomain.com/sister2
www.mydomain.com/mommy
www.mydomain.com/daddyo

Obviously, I don't plan to have literal working directories for each person.
I'd pass the "sister1" portion to a process.php script that takes care of the rest.
I've figure out how to do it by manually typing each RewriteRule in my htaccess file:
Options +FollowSymLinks
AddDefaultCharset UTF-8
RewriteEngine on
RewriteBase /

RewriteRule ^/?sister1$ process.php?entity=sister1 [L]
RewriteRule ^/?sister2$ process.php?entity=sister2[L]
RewriteRule ^/?mommy$ process.php?entity=mommy[L]
RewriteRule ^/?daddyo$ process.php?entity=daddyo[L]

I feel this is the long way of doing it.
Is there a more universal way of extracting the text after the first "/" forwardslash, and passing it to process.php?entity=$1 ?
I tried it this way:

RewriteRule ^/([A-Za-z0-9-]+)/?$ process.php?entity=$1 [NC,L]

I'm getting the apache 404 error: "Not Found".
Answer: It is because you have a mandatory / in the beginning of your rule, i.e., you are always looking for something like /sibling in the URL. Your first examples have that first forward slash as optional due to the question mark after it.
You do not need a beginning forward slash - normally the rewrite rule picks up stuff after the domain name
www.example.com/string/mod/rewrite/gets/is.here
So just remove the starting slash and it should work.

Htaccess - Detecting the URL


How to trigger an Apollo query in a Vue component event?

Question: How to trigger an Apollo GraphQL query on a mounted event in a Vue.js component.
Here is what my code looks like:
<template>
</template>

The query runs fine on the first load of the component, but how can I get it to run with various events?
Comment: Make the query a method and call it when the events occur.
Answer: this.$apollo.queries.books.refetch();

if you have variables and need to update them on each call, pass them as parameter of the method refetch:
this.$apollo.queries.books.refetch(variables);


Solve matrix exponential power series

Question: The matrix exponential is defined as
$$ e^A  = \sum_{n=0}^\infty \frac{1}{n!} A^n  $$
However I would like to solve something similar:
$$ B = \sum_{n=1}^\infty \frac{1}{n!} A^{n-1}  $$
(NOTE: starting index and the power)
I can transform that into
$$ B = A^{-1}\sum_{n=0}^\infty \frac{1}{n!} A^{n} -I = A^{-1} \left(e^A - I \right) $$

That works. But when $A^{-1}$ does not exist ($A$ is not invertible) it does not work.
Is it possible to make it work for general $A$? Has anyone thoughts on that? Thanks.
Comment: A generic matrix is invertible and the right and side exists. So if you should be unlucky and have a $B$ with $\det B =0$, then you simply add $\epsilon I$ to $B$ calculate the right hand side and then let $\epsilon \to 0$.
Answer: Basically, your question asks how to apply the function $(e^x-1)/x$ to a matrix. One way to do it is using the integral representation
$$\frac{e^x-1}{x}=\int_0^1 e^{tx}\ dt.$$
Thus we can define $B$ to be
$$
B:=\int_0^1 e^{tA}\ dt.
$$
Since you already know what the matrix exponential is, this expression makes sense: the integral of a matrix is computed by taking the integral of each of its entries.
Note also that this coincides with the power series definition you have written, since $$\int_0^1 \frac{(tA)^{n}}{n!}\ dt=\frac{A^{n}}{(n+1)!}.$$
Comment: The feasible solution for $B$ is $\int_0^1 e^{tA}\ dt$. For any matrix, this is a well-defined quantity that is straightforward to compute.
Comment: That seems good, but I don't quite understand how I can get a feasible solution for $B$ from that...
Answer: Your matrix B is in literature called phi-function $\varphi_1$. The power series expansion of the general form is
\begin{align}
   \varphi_k (A) := \sum_{n=0}^\infty \frac{A^n}{(n+k)!}
\end{align}
If an approximate solution is sufficient a Pade approximation $\varphi_1(A) \approx (1-A/2)^{-1}$ would be a possible solution.

Solve matrix exponential power series


Logistic Regression: Risk Ratio and Interpreting the Magnitude of Confounding

Question: Let's say I have a treatment and a test group, and I am trying to interpret the magnitude of confounding variables using logistic regression.
From my understanding, to do so I need 1) the crude risk ratio ($RR_{crude}$), which from my understanding is the risk ratio of the regression model without the confounding variable(s) added to the model and 2) the adjusted risk ratio ($RR_{adjusted}$), which from my understanding is the risk ratio of the regression model with the confounding variable(s) added to the model.
With this information, if I want to get the magnitude of confounding I can use the following equation - source:
$magnitude of confounding =\frac{RR_{crude} - RR_{adjusted}}{RR_{crude}}$
Now here are my questions:

How do I calculate RR, and is my interpretation of crude and adjusted RR correct (additionally is there a way to calculate RR in Python using scipy or statsmodel) - i.e. I do understand how to calculate Odds Ratios.
Is the way to calculate the magnitude of confounding above correct?
How do I interpret the magnitude of confounding? Does it give me an indication as to by what percentage I need to adjust the results of my treatment group to take into account the effect of confounding variables (i.e. if I have a conversion rate on my treatment group of 9% and the magnitude of confounding, is 0.05, does it mean I need to reduce the conversion rate of my treatment group by 5% to take into account the influence of confounding variables?
Answer: If you already have a valid* logistic multiple regression model that includes confounders, there might not be much sense in trying to evaluate a numeric value of confounding magnitude. As the source you cite states under the heading "Summary of Control of Confounding," multiple regression analysis itself "provide[s] a way of adjusting for confounding in the analysis, provided one has information on the status of the confounding factors in the study subjects."
Thus you can evaluate the log-odds, odds, or probability of the outcome with a logistic regression model for any specified values of confounders or treatment group. So to answer your last point, the logistic regression provides an estimate of the treatment coefficient that directly takes into account confounders, and I don't see that you would otherwise need to take into account the information provided by a measure of magnitude of confounding.
If you do want to calculate a risk ratio (RR), relationships between the RR and the odds ratios or coefficients of a logistic regression model are shown in this question and answer. I have adapted slightly the form used by AdamO in that answer, to illustrate a crude RR ($RR_{NC}$) for a model including no confounders, only treatment $T$:
$$RR_{NC} = \frac{1 + \exp(-\beta_{0,NC})}{1+\exp(-\beta_{0,NC}-\beta_{T,NC})}$$
where $\beta_{0,NC}$ and $\beta_{T,NC}$ are respectively the intercept and the coefficient for treatment in that model omitting confounders. The extension to a model with values $X_i$ for a set of confounders $C$ could provide a type of adjusted RR:
$$RR = \frac{1 + \exp(-\beta_{0}-\sum_{i \in C}\beta_iX_i)}{1+\exp(-\beta_{0}-\beta_{T}-\sum_{i \in C}\beta_iX_i)}$$
but this RR, and thus your estimate of the magnitude of confounding, will depend on the specific confounder values chosen. I suppose you could choose to set all $X_i$ to 0 or some reference values, but what would that really mean? (And I'm not even going to get into the difficulty of determining confidence intervals for these RRs.)
As Frank Harrell put it in a comment on this question, "RRs are at odds with the logistic model (pun intended)." They don't add much useful if you have a valid logistic multiple regression model.

*This answer assumes that the logistic regression model is properly specified. Note that it might need to use transformations of continuous predictors to meet linearity requirements, include interaction terms of confounders with treatment status, etc.
Comment: Thanks, that makes a lot of sense.


There are exactly 116 different groups P where $7\mathbf{Z}^{3} \subset P \subset \mathbf{Z}^{3}$

Question: There are exactly 116 different groups P  where $7\mathbf{Z}^{3} \subset P \subset \mathbf{Z}^{3}$
I don't know how to prove this. Is it provable at all? How?
Comment: Count the number of subgroups of the quotient $\mathbb Z^3/7\mathbb Z^3$.
Answer: By the Fourth (or Lattice, or whatever numbering you use) Isomorphism Theorem, the subgroups of $G$ that contain a normal subgroup $N$ are in one-to-one correspondence with the subgroups of $G/N$.
Here, $G=\mathbf{Z}^3$ is abelian, so $7\mathbb{Z}^3$ is a normal subgroup. Thus, asking for subgroups $P$ that contain $N=7\mathbb{Z}^3$ is equivalent to asking for subgroups of $(\mathbb{Z}^3)/(7\mathbb{Z}^3) \cong (\mathbb{Z}/7\mathbb{Z})^3$.
The latter is a 3-dimensional vector space over $\mathbb{Z}/7\mathbb{Z}$, the field with $7$ elements; the subgroups are the subspaces. Count the subspaces.
Answer: The number of $k$-dimensional subspaces of a vector space of dimension $n$ over a finite field  of $q = p^{m}$ elements is the product
\begin{align}
\binom{n}{k}_{q} = \frac{(q^{n} - 1) \cdots (q^{n} - q^{k-1})}{(q^{k} - 1) \cdots (q^{k} - q^{k-1})}.
\end{align}
To prove this consider the following. A $k$-dimensional subspace is specified by $k$ linearly independent vectors, say, $\{ v_1, \dots, v_k \}$. There are $q^{n}-1$ ways to choose $v_1$, $q^{n} - q$ ways to choose $v_2$ (so as not to lie in a subspace spanned by $v_1$), and so on. Continuing in this manner, there are $q^{n} - q^{j}$ ways to choose $v_{j+1}$ (so as not to lie in the subspace spanned by any preceding vectors). The number of $k$ linearly independent vectors of an $n$-dimensional space is therefore the product
\begin{align}
(q^{n} - 1) \cdots (q^{n} - q^{k-1}).
\end{align}
Setting $n = k$ gives the number of possible bases of each $k$-dimensional subspace. Therefore, we normalize the former by the latter and this gives the rational function which counts the number of $k$-dimensional subspaces.
The total number of subspaces of an $n$-dimensional vector space over a finite field of $q$ elements is therefore the sum
\begin{align}
\sum _{k = 0}^{n} \binom{n}{k} _{q}.
\end{align}
For your example, as my astute colleagues Mariano and Arturo suggest, $n = 3$ and $q = 7$, and the total number of said subspaces is the sum
\begin{align}
\binom{3}{0}_7 + \binom{3}{1}_7  + \binom{3}{2}_7  + \binom{3}{3}_7   = 1 + 57 + 57 + 1 = 116.
\end{align}
Thus, there are $116$ groups $P$ such that $7 \mathbb{Z}^{3} \subset P \subset \mathbb{Z}^{3}$.
Comment: It might be instructive to explain how one arrives at the formula, e.g., with 1 or 2 dimensional subspaces.
Comment: Done. Thanks, friends.
Comment: I too would welcome a little more elaboration. Nonetheless: thank you.


Column-specific context menu for Primefaces DataTable

Question: How can I define context menu for each column differently in Primefaces datatable? Putting
 inside
 does not work properly. I want context menu to be different depending on which column user right-clicked in.
This does not work (context menu is created the same for all columns):

        <h:outputText value="#{value.balance}">
            <f:convertNumber type="currency"></f:convertNumber>
        </h:outputText>

        <h:outputText value="#{value.balance2}">
            <f:convertNumber type="currency"></f:convertNumber>
        </h:outputText>

How to add column-specific context menu in Primefaces dataTable either by using PF components, extending PF components, or adding custom JavaScript?
Comment: Not yet. I am stuck on other assignment right now so it will be a few days before I can try @kian's solution
Answer: Have you tried(I have just tested with Primefaces 3.5):
ContextMenu can be attached to any JSF component, each of rows in primefaces datatable has private and dynamic id(ex: :carList:0:test1  :carList:1:test1  ...), so I think you should use contextMenu inside column:

                        <h:outputText value="#{carr.model}" />

                        <h:outputText value="#{carr.manufacturer}" />

If you want to specify row:

                        <h:outputText value="#{carr.model}" />

Comment: With me, reputation get no mean, i have tested it, and it work fine for me, i just want to help other people !
Comment: No this doesn't work. This just puts a specific context menu per-column. not at all what i want.
Comment: Oh jeez. Sorry RongNK - I'm an idiot. I see that this question isn't even my question.
Comment: oh, that's funny, nothing at all :)
Comment: Here is my question which was falsely closed as a duplicate of this question by an idiot stackoverflow member: http://stackoverflow.com/questions/16099698/primefaces-contextmenu-different-menu-based-on-selected-item
Help me answer it and the 50+ is yours.
Comment: oh, you can set for specify row.
Comment: @RongNguyen Have you done contextmenu inside p:schedule? I cannot make it work when I nested contextmenu inside schedule.
Comment: @Halim Sorry, i do not worked with jsf for one year, so i don't have environment to test it.
Answer: an alternative way is to use the p:menuButton instead.
the p:menuButton can be changed to look like a p:contextMenu
it's all about styleClass.

create custom styleclass to change the down arrow

.contextButton .ui-state-default .ui-icon{
    background:url(YOUR_IMAGE_PATH);
}

create custom styleclass to hide the button border and background

.contextButton .ui-button {   border: none;       background: none; }
.contextButton .ui-button.ui-state-hover,  .ui-button.ui-state-focus,
  .ui-button.ui-state-active {      border: none;   background: none; }

use the custom styleClass in the p:menuButton

      P:MENUITEM HERE

you may refer here for working example
Comment: I like the idea - this is probably the closest approximation of what I need here. With some tweaking it should also be possible to trigger the menubutton on right-click thus simulating context menu. Will try this out and revert
Comment: I too think this is the only solution.
Answer:
Optional for attribute defines which component the contextMenu is attached to. When for is not defined, contextMenu is attached to the page meaning, right-click on anywhere on page will display the menu.

That's what Primefaces Documentation says about the contextMenu tag. So, in the way you have, it's attached to the page meaning. Using for attribute you will be able to integrate with Primefaces Components, but probably no with an specific table column.
Also Datatable documentation suggests that you can only do that when making a selection into the table, as it seems it has special ways to adapt it to tree nodes.
However I highly recommend you looking through docs before asking.
Comment: I have tried "for" attribute as well - should have mentioned in the original question. Usually you can substitue "for" attribute with placing component inside the target component. Anyway, this results in error java.lang.ClassCastException: org.primefaces.component.column.Column cannot be cast to org.primefaces.component.api.Widget.

Still, it should be possible to attach the context menu to specific column by using custom Javascript code...


How the SVM algorithm works with one label in range?

Question: I have a dataset where the features are configurations (numeric values) that describe the situation and the label (only one) is the ranking of the situation (natural value between $[1,5]$). If label is $1$ then the configurations are bad and if the label is $5$ then the configurations are great.
I'm trying to use the SVM algorithm. As I understand, the SVM algorithm is designed for binary classifiers and my problem requires a multi-class classifier. I'm trying to understand how the one-vs-one and one-vs-rest can help here. Is it possible to explain how the SVM algorithm works with those two approaches in the case of one label in range [1,5]? Does my dataset considered as multiclass dataset? What If I have five labels (ranking $[1,5]$) and each one has a binary output ($0$ or $1$)? I'm a bit confused about it.
Answer:
Is it possible to explain how the SVM algorithm works with those two
approaches in the case of one label in range [1,5]

Your target variable (the 'label') $y$ can have 5 realizations: 1,2,3,4,5. Classifying observations into these 5 categories is considered a multiclass problem, yes.
The two approaches that you mentioned, one-vs-one and one-vs-rest, aim to make a binary classifier applicable to non-binary classification problems. Note that these approaches are not limited to SVM. So what do these approaches do?
One-vs-one
In your case, $|y| \cdot \frac{|y| - 1}{2}=10$ models are trained, where |y| is 5 in your case. Each model discriminates between different realizations of $y$:

1 or 2
1 or 3
1 or 4
1 or 5
2 or 3
...
4 or 5

One-vs-rest
A coarser approach that fits 5 models that perform a 'this or other' discrimination:

1 or not 1
2 or not 2
3 or not 3
4 or not 4
5 or not 5

It is noticable, that the number of models that need to be fitted is growing quite quickly for the one-vs-one approach, while one-vs-rest always requires |y| models.

What If I have five labels (ranking [1,5]) and each one has a binary output (0 or 1)? I'm a bit confused about it.

Say instead of the vector $y$ that we had above, you have a matrix $Y$ with one column per possible class realization. The values in each column are binary, 0 or 1.
Assuming that the row sums are 1 for every row, meaning that an observation is only assigned to one class, then we basically end up with the same method as with one-vs-rest. For each column in $Y$, one can fit a model that distinguishes between the respective class and 'other'.


Converting Boolean to Varchar2

Question: I have a sample code where i'm trying to print Boolean value.
It resulted error.

wrong number or types of arguments in call to 'PUT_LINE'
wrong number or types of arguments in call to 'TO_CHAR'

DECLARE
    status BOOLEAN:= false;
    BEGIN
      DBMS_OUTPUT.PUT_LINE(status);
      DBMS_OUTPUT.PUT_LINE(to_char(status));
    END;

By the error message it's clear that Boolean can't be converted to character in both ways (implicit, explicit).
Why its not possible?
Is their any specific reasons? or Oracle just forgot about this type of conversion(Its highly unlikely).
So is their any other way to convert? Or do i have to go for IF or CASE statement to guess what status has.
Comment: What should a Boolean to string conversion be? Should TRUE go to 'TRUE', 'True', 'true', 'T', 't', 'YES', 'Yes', 'yes', 'Y', 'y' or maybe it goes to a number instead: 1? Basically, it's up to the individual to determine what the string (or number!) representation of a Boolean is, because it may vary depending on the context.
Comment: Make sure you accept the answers if they are correct :)
Comment: None of the arguments as to why this is make any sense to me. Loads of languages simply do this without any issue. They decide what the string representation is and then we all deal with it (in the same way). It also does not prevent anybody from doing it any other way if they like to. In PLSQL we are simply forced to do this over and over again. I do not know any sane reason for this.
Answer: It seems you cannot concat varchar and boolean.
Define this function:
CREATE OR REPLACE FUNCTION BOOLEAN_TO_CHAR(STATUS IN BOOLEAN)
RETURN VARCHAR2 IS
BEGIN
  RETURN
   CASE STATUS
     WHEN TRUE THEN 'TRUE'
     WHEN FALSE THEN 'FALSE'
     ELSE 'NULL'
   END;
END;

and use it like this:
DBMS_OUTPUT.PUT_LINE('status'|| BOOLEAN_TO_CHAR(status));

Answer: As an alternative I have been using the SYS.DIUTIL package's BOOL_TO_INT() function:
DECLARE
status BOOLEAN:= false;
BEGIN
  DBMS_OUTPUT.PUT_LINE(sys.diutil.bool_to_int(status));
END;

This will return 1 for true and 0 for false (and null for null).
Answer: You cannot print a boolean variable. For that you can either create a function or use case statement.
In Oracle SQL there is no Boolean data type. Its a PL/SQL data type. Which means you cannot have it as the data type of a table column.

Why its not possible?

Maybe because its not there is ANSI.
Answer: If you use it in APEX, please check APEX_DEBUG.TOCHAR() https://docs.oracle.com/en/database/oracle/application-express/20.2/aeapi/TOCHAR-Function.html
-- https://docs.oracle.com/en/database/oracle/application-express/20.2/aeapi/TOCHAR-Function.html
SET SERVEROUTPUT ON SIZE 2000
BEGIN
    DBMS_OUTPUT.PUT_LINE(APEX_DEBUG.TOCHAR(TRUE));
END;

Answer: It seems that there is a new variant TO_CHAR(boolean) in Oracle 23c. https://docs.oracle.com/en/database/oracle/oracle-database/23/sqlrf/to_char-boolean.html

Converting Boolean to Varchar2


Trouble with GitHub and Ubuntu file permissions

Question: I recently tried to push my new files to my repo and things went haywire.  I also think there's a problem with my SSH.  Not really sure how to fix either of them.
The files were moved out of my project folder while attempting to push them to GitHub, which I'm terrible at. They disappeared out of my local development project folder.  It's a .Rproj folder.  They should be in here:

But I did something with GitHub that made them go poof.
I ran a search for the files with the following, and it shows that the files exist on my machine (it is my machine, no one else uses it), but I don't have permission to access the files.  Does anyone know how to fix this ./.gnupg permission issue?
find $directory -type f -name "Rpackages/saber"
# find: `./.gnupg': Permission denied
find $directory -type f -name "Rpackages"
# find: `./.gnupg': Permission denied
find $directory -type f -name "playerStats.R"
# find: `./.gnupg': Permission denied
find . -print0 | grep -FzZ 'Rpackages/saber'
# find: `./.gnupg': Permission denied
# ./Rpackages/saber./Rpackages/saber/.Rhistory./Rpackages/saber/man./Rpackages/
# saber/man/franchise.info.Rd./Rpackages/saber/man/load.event.Rd./Rpackages/saber
# man/load.roster.Rd./Rpackages/s ....

Answer: There is nothing to fix, you simply cannot go into .gnupg (which could have been created by root or for a different account than yours)
Put sudo before your command, or add 2> /dev/null to its end if you want to ignore them.
Or you can take ownership of the .gnupg folder (if it is in your /homle/myaccount folder)
sudo chown -R myaccount ~myaccount/.gnupg

As shown in "gpg: WARNING: unsafe ownership on configuration file", the permission for that folder should be 700.
Comment: Thanks,.. just to clarify. What is `myaccount`?  My username on my machine?
Comment: @RichardScriven yes, the one you are currently logged on, and under which you are executing those `find` commands.
Comment: @RichardScriven move them back? You mean change the location of the `.gnupg` folder?
Comment: I want to get them out of there. It is a project full of 40 code files that were moved, not copied, moved.  I need them in specific folder so the package will run (and because I don't want to lose them. Btw, I don't know what the `./.gnupg` folder is/does
Comment: @RichardScriven you could, but I am not sure where "there" is: if that `.gnupg` is in your `/home/youraccount` folder, then moving it would break the default location for gpg config files (https://www.gnupg.org/documentation/manuals/gnupg/GPG-Configuration.html)
Comment: @RichardScriven but if you moved all those files (included the `.gnupg`), then yes, you can remove that `.gnupg` folder (or at least move it aside): it doesn't do anything in its new place.
Comment: @RichardScriven just to be sure, that `.gnupg` folder doesn't affect you finding your other files, and moving them back. It just means those other files are not in `.gnupg`, because you cannot explorer that folder. If you found them elsewhere, you can restore them in your project, while ignoring completely this `.gnupg` issue.


Caret: gradient vs gam boosting

Question: What is the difference between a boosted additive model (e.g. caret model: gamboost) and a general stochastic gradient boosting model (caret model: gbm)?
A gradient boosting model is additive by nature, so how does it differ from the gamboost one in the estimation procedure?
Comment: Congrats on answering your own question and answering it. You might want to post it as an answer so it can be properly upvoted. (Welcome to the CV community!) (Unfortunately you cannot upvote your own answers :) )
Comment: I've found the answer myself: gbm is based on regression trees while gamboost applies GAM as base learners (they can either be linear, smooth, etc.). They're both additive models but the choice of base learners change.
Answer: I've found the answer myself: gbm is based on regression trees while gamboost applies GAM as base learners (they can either be linear, smooth, etc.). They're both additive models but the choice of base learners change.

Caret: gradient vs gam boosting


App Cordova não funciona como esperado

Question: Fiz um simples aplicativo utilizando Apache Cordova no Visual Studio 2015, e adicionei o AngulaJS.
Quando eu testo no Riple emulador funciona como esperado:

Então eu gero a APK para testar no smartphone físico, para isso eu uso o comando:
cordova build android --debug

Dentro do diretório do projeto, instalo a apk no aparelho:

Sansumg Galaxy Ace - Android 3.2.6

Também alterei esta configuração <uses-sdk android:minSdkVersion="6" android:targetSdkVersion="10" />, mas não funciona como esperado:

Não sei o que está acontecendo, fico grato com qualquer ajuda.
Comment: aparentemente tem a ver com o arquivo do angular não ter sido localizado. Você pode verificar a localização do mesmo no arquivo index.html
Comment: Eu testei em um dispositivo com plataforma Android 5.1.1 e funcionou, acho que pode ser algo com a versão. O Angular esta referenciado corretamente pois funciona em alguns aparelhos. @RafaelMenaBarreto Obrigado
Answer: Lendo neste link: Apache Cordova Documentation a documentação do Cordova descobri que só funciona a partir da API 14.
:(
Mas obrigado pela ajuda.

App Cordova não funciona como esperado


Activity não retorna a view

Question: Estou tentando compilar porém não esta dando, meu layoute esta assim:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:background="#F9F9F9" >

<include
    android:id="@+id/toolbar_actionbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    layout="@layout/toolbar_default" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="DRAGÃO"
    android:id="@+id/textView"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:textSize="@dimen/abc_text_size_display_3_material"
    android:textColor="#ff0000" />
</RelativeLayout>

Em meu activity eu fiz assim:
import android.support.v7.app.ActionBarActivity;
import org.androidannotations.annotations.EActivity;

@EActivity(R.layout.activity_comentarios)
public class ComentariosActivity extends ActionBarActivity {

}

Tentei remover a linha

@EActivity(R.layout.activity_comentarios)

funcionou porém quando entro na tela ela fica toda laranja como na imagem.

No caso deveria esta assim:

No Logcat aparece este error:

Error:(7, 1) error: The AndroidManifest.xml file contains the original component, and not the AndroidAnnotations generated component. Please register ComentariosActivity_ instead of ComentariosActivity

No meu AndroidManifest esta assim:
<activity android:name=".ComentariosActivity"
       android:label="Comentarios"
       android:screenOrientation="portrait" />

Answer: o próprio Error já da a solução

Please register ComentariosActivity_ instead of ComentariosActivity

, no AndroidManifest coloque:
<activity android:name=".ComentariosActivity_"
   android:label="Comentarios"
   android:screenOrientation="portrait" />

Comment: Tentei fazer isto e mesmo assim as telas não foi chamada
Answer: Consegui resolver o problema, bastou alterar minha classe para:
package com.fomedemais.FomeDemais;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import org.androidannotations.annotations.EActivity;

public class ComentariosActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comentarios);
    }
}

E ainda adicionar no AndroidManifest como a resposta do meu amigo @sparkss
<activity android:name=".ComentariosActivity_"
  android:label="Comentarios"
  android:screenOrientation="portrait" />

Activity não retorna a view


python 3.5 Why is my while loop omitting the first line?

Question: I am trying to write a code where I use a while loop to read in every line in a txt file until a line with nothing in it is seen i.e \n. My txt file and code looks like this:
I like cats
But dogs are
the best

although a tiger
would make for
an awesome pet

file1 = input("Enter name of file: ")
openfile1 = open(file1, "r")
data1 = openfile1.readline().strip()
while data1 !="":
    data1 = openfile1.readline().strip()
    print (data1)

What I want it to print out is:
I like cats
But dogs are
the best

but instead it omits the first line and gives me:
But dogs are
the best

Why is it omitting my first line?
Comment: Because you read the first line before the loop.
Comment: Because you are skipping the first line when you read the line inside the while loop as you've already read the first line outside the loop.
Comment: Thank you for the feedback! I figured it out.
Answer: As others have said you've already read a line once so it didn't show up.
also, there is an easier way of printing file lines.
import os

with open('input.txt') as fl:
    for line in fl:
        print(line.strip())

Comment: Using the with statement and iterating over lines is the Pythonic way to do this so this gets my vote.
Answer: move the print statement to before the readline inside the while loop


Compare specific fields of two nodes side-by-side

Question: I have a content type consisting of 15 large text areas fields.
I would like to be able to select specific fields (or maybe just one for start) and review the content of two nodes side-by-side with the selected fields aligned horizontally (in a table maybe). Also these fields should be available for inline edit using the Editable Fields module, so I need this to be done inside a view which would allow me to use the editable field formatter.
I've checked the Node Compare module which is great, but it doesn't allow the user to check which fields he'd like to review side-by-side. I need to be able to filter those by exposed filters or something. Furthermore Node Compare uses a custom view that doesn't allow me to use the editable formatter.
Any ideas how could I achieve this?
Answer: Install and configure Node Compare module.

Some more details about this module (from its project page):

The module to provide node comparison functionality on user request.
  It compares the values of the fields of nodes.
Comment: Hey node compare should work, I am attaching the screenshot for the same.
Comment: Sorry for this, I was still editing. Please review my question. I've tried the Node Compare but it doesn't fit my requirements.
Comment: Is it possible somehow to reveal the field filter to the user? (for example to be able to tick, which fields I'd like to compare). As far I can see, I can only configure this statically from module settings..
Comment: Also by using Node Compare I'm unable to edit the content of the fields inline with the Editable Fields module, as it doesn't allow me to set a field formatter like a regular view would.
Comment: @LePhleg then why not create 2 block views? and put them side by side on a page.
Comment: @Sssweat because the fields won't be aligned and also this way I think I'll need two identical sets of exposed filters..
Comment: @Sssweat do you have any suggestion on this?
Answer: A thoroughly complicated problem since node compare isn't an option. Entity forms, entity reference and field permissions could do it though.
Of the top of my head I'd start with an entity reference form that allows you to pick all the nodes to compare.. Then when the form is saved, use rules to create a redirect to a view passing the required nids as contextual filters in the url in your edit view. This will limit the view to those nodes.
For only one field at a time, you could create 15 different views and a taxonomy field in the entity reference form to control which view it redirects to.
Or for many fields at the same time, have one view and use the field permissions module. Have a role per field and then apply (actually take away) roles based on which taxonomy terms the user selected in the entity reference form. Then only those fields will appear in the view.
You'd need another rule that would give the user the those roles back at some point.
I'd love to see some other solutions without custom coding.
Comment: Interesting workflow for a strictly non-custom implementation. I'll give it a shot, if no other suggestion would come up soon..


Adicionar métodos ao namespace do plugin sem seletor

Question: Estou criando um plugin em js e preciso adicionar alguns métodos a esse plugin.
Essa é a base do plugin até o momento:
    (function ($) {
    function jarbas(params) {
        ...
    }

    $.fn.jarbas = function (params) {
        // cria funcionalidade a partir do método sem seletor $.jarbas(params);
    }

    // defaults
    $.fn.jarbas.defaults = { ... };

    $.extend({
        jarbas : function (params) {
            switch (typeof params) {
                case 'string':

                    break;
                case 'object':
                    return new jarbas(params);
                    break;
            }
        }
    });
})(jQuery);

Na utilização do plugin eu faço (funciona perfeito):
$.jarbas({ ... });
$('seletor').jarbas({ ... });

é possível criar métodos extendendo o nome do plugin sem a necessidade de seletor? por exemplo:
$.jarbas.remapAll();

Comment: Sim, isso é possivel, mas e esse `.remapAll()`: como iria saber o que fazer se não passa nenhum argumento ou seletor?
Comment: quanto a isso não tem problema, desde que eu possa chamar o método!
Answer: Sim é possivel.
Da mesma maneira que fez $.fn.jarbas.defaults = { ... }; para defenir uma propriedade dessa função pode adicionar um novo método passando uma função:
$.fn.jarbas.remapAll= function(){
    // fazer o que quiser;
}

Exemplo:

$.fn.jarbas = function (params) {
    // cria funcionalidade a partir do método sem seletor $.jarbas(params);
}

// defaults
$.fn.jarbas.defaults = {
    foo: 'bar'
};

$.fn.jarbas.remapAll = function () {
    alert('Eureka! Achei o ' + this.defaults.foo + '!');
}

// testar

alert($.fn.jarbas.defaults.foo);
$.fn.jarbas.remapAll ();

Comment: Obrigado pela resposta, achei que houvesse uma maneira de criar sem .fn visualmente falando! Vlw!
Comment: @Trxplz0 pode fazer só `$.jarbas` (http://jsfiddle.net/mq29zr6p/) mas isso é má prática. O jQuery indica na documentação que deve ser `$.fn.novoMetodo`
Comment: sim no meu caso como eu uso 1 método extensor não funciona só o $.jarbas ele da erro por encontrar o método e não um plugin. De qualquer forma ta respondido! Vou marcar assim que possível!

Quanto a má prática nem sabia, esse .fn não curto não é briga até o resto da vida!
Answer: Seu plugin tem um problema de encadeamento (chaining) dos objetos jQuery. O que a documentação recomenda é que seu plugin sempre retorne this (se sempre se aplicar a coleções de apenas 1 objeto), ou this.each(...), se o plugin precisa lidar com mais de um objeto selecionado.
Isso permite que você encadeie métodos do jQuery na mesma seleção, por exemplo:
$('a').jarbas().show();

Do jeito que seu plugin está construído, retornando new jarbas, isso não será possível. Também não dá para chamar $.jarbas(); se você definiu o método em $.fn. Você pode, sim, chamar $.fn.jarbas().
Quanto a como fazer o plugin funcionar como namespace, o Sergio já respondeu e não vou repetir o que ele disse. Como funções em JavaScript são objetos, você pode pendurar quaisquer propriedades que quiser nelas. Mas isso é meio estranho no mundo do jQuery. Plugins geralmente dependem dos seletores, e não são usados com namespaces dessa forma. O que me leva a sua pergunta final:

é possível criar métodos extendendo o nome do plugin sem a necessidade de seletor?

Sim, mas então não faz sentido colocar seus métodos em $.fn. O que tem lá é usado como protótipo de objetos jQuery, que são seleções de nós do DOM. Se você quer algo que independa de seletor, defina direto no próprio objeto jQuery (ou $):

(function($) {
    $.jarbas = function(){
        document.body.innerHTML += "jarbas
";
    };
    $.jarbas.remapAll = function() {
        document.body.innerHTML += "jarbas remapped
";
    }
}(jQuery));

$.jarbas();
$.jarbas.remapAll();

Comment: obrigado pelas dicas, mas ele retorna o $this e a chamada direta ao $.jarbas é gerada pelo extensor no final que me permite obter ou criar um novo objeto dependendo dos parâmetros. No post eu tirei apenas pra encurta-lo. O que eu preciso é usando seletor e sem. Já foi resolvido! Obrigado!


UnityEngine.UI não funciona

Question: Então, estou aprendendo programação e no curso o professor colocou um codigo no algoritmo que é o "using UnityEngine.UI" para conseguir colocar os comandos e talz, só que quando fui fazer no meu unity, não pega, ele não reconhece como um comando
e sem isso não consigo fazer oque o professor pede.
(sou totalmente iniciante ok se for algo mt basico me desculpem.)
Comment: Aparece algum erro quando vc roda o programa?
Comment: Você instalou o SDK do uinity?
Comment: não aparece nenhum erro, oq só acontece é que o script não considera o UnityEngine.UI como um comando
Comment: como ver se eu instalei o sdk?
Comment: @JoãoFrancisco, você acaba de responder que não...
Comment: @JoãoFrancisco ao invés de colocar uma imagem com o código coloque o próprio código.
Answer: Olá, João, na verdade não é um problema de compilação ou algo parecido, a sua IDE não está identificando a biblioteca do Unity, basta apagar os seguintes arquivos da pasta do seu projeto:
.vscode (no meu caso, que uso o VS Code),
Assimbly-CSharp.csproj,
NomeDoProjet.sln (A solução do Visual Studio, caso esteja usando)
Após isso, abra novamente algum script do seu projeto com a sua IDE e ele será carregado novamente sem nenhum erro.

UnityEngine.UI não funciona


what is .ICEAuthority file in opensuse 11.2

Question: what is .ICEAuthority file in opensuse 11.2?
Comment: What appears to be a simple question is proving very difficult to find anything about. It has something to do with authority, I think authentication token for X server, but the man page for iceauth has nothing of any use. I have modded this up because I am now determined to find out more. You have engaged my interest.
Answer: Here is a good paper on what ICE is, and what it does.
Basically ICE is a inter process communication protocol, with authentication, protocol negotiation and potentially multiplexing built in.
It allows two X clients to talk directly to each other, for example, a video player program could potentially talk to a jukebox program to update each other.
As Richard Holloway says, the .ICEAuthority file is for authentication. It contains a number of random cookies. If two programs have the same cookie, then they're allowed to talk to each other. In practice this either means that they're reading the same .ICEAuthority file, or the cookies have been added.
In a lot of ways it's similar to the xauth program & the .Xauthority file, except that .ICEAuthority is used for client to client, while .Xauthority is for client to server.
Comment: do we have ui for configurating this in opensuse 11.2.
Answer: You have installed and ran Klamav, I get the same error after installing and updating from the command line. Sudo klamav or sudo freshklam. Here is a fix:
mv ~/.ICEauthority ~/.ICEauthority.backup
sudo chown {user}:{user} /home/{user}
sudo reboot


Python not detecting existing modules

Question: Trying to run a .py file on Kali Linux using:
`sudo python2 test.py`

I get the error message:
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    import selenium
ImportError: No module named selenium

The problem is that selenium is already installed, when pip is asked to install selenium this error message is shown:
sudo pip3 install selenium

I get this message:
Requirement already satisfied: selenium in /usr/lib/python3/dist-packages (4.0.0a1)

What should I do? I guess that it is related to pip2, but I cant install it. Please help me.
This the file's code:
import sys
import datetime
import selenium import requests
import time as t from sys
import stdout from selenium
import webdriver from optparse
import OptionParser

Comment: You're trying to run the file with Python 2, but you installed Selenium with pip3.
Comment: pip3 is for python3, you run with python2
Comment: Just create a virtual environment, install the required packages and execute the program there.
Answer: There are multiple different versions of python on your system. The file you are running is with the python2 interpreter. pip3 is a package manager for python3.
If you want to see all your installed versions of python you can run ls /usr/bin/python* (just ignore python-config and pythonw directories). To install selenium on python2 you need to use pip instead of pip3. Alternatively, you can try running that file with python3 since it doesn't look like there are any python2 print statements, xrange, etc. which might cause python3 to fail.
Comment: Which command should I use to install pip2?
Comment: Try running `pip -V`. If it gives you (python 2.x) at the end then use `pip install selenium`. If not then you'll have to do some more digging around
Comment: I got same error tying to get selenium from pip only.
Comment: is there anything stopping you from running the file using python3?
Comment: print '------------------------'
          ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('------------------------')?
Comment: add parenthesis as it suggests

Python not detecting existing modules


How to tell if content has been migrated

Question: I am using drupal2drupal migration. How can I indicate that some content has been migrated as opposed to being manually added.
Comment: Perhaps by the creation date you might be able to tell.
Answer: You could alter the incoming data and attach a taxonomy tag, like 'migrated', to indicate this.
You could also add (migrated) in the title, but you would have to ensure this does not affect users, terms, URL aliases, etc. Hence why I suggest a taxonomy term. I am not that familiar with D2D API but I know this is very easy to do with Migrate Framework.
Comment: Whatever works best for you.
Comment: what about adding a new boolean field (migrated) ?
Answer: It has been a while since I have done a proper D2D migration (I do more imports from non-Drupal sources using custom scripts), but you should be able to examine the migration map table(s) for nodes.  If the destination node ID exists, then you know that the node in question was migrated.
However, when I have used D2D I would prefer to add field_old_nid to each node and add a mapping from nid => field_old_nid for that.  Then just hide that field from public view.
I have found that having the old nid as a field can come in handy down the road.  For example, when you have your old and new sites up, you can easily add an link from the old site to the new site for debug/QA purposes, using the http://example.com/node/nid URL for the old site.  I also seem to recall using some filter shenanigans to fixup LinkIt style links in body content.
Answer: New tables are created for each migration type, the old and new Entity IDs are stored in that table. The name is different for each table, so I can't specifically tell you the table name, but if you look in the database you can see the tables that start with migrate_. A query on that table can tell you if the content has been migrated.


"Node: Created day" mismatched, not reflecting the actual created day

Question: Views Version: 7.x-3.0-alpha1
I was trying to create a blog archive view, like blog/yyyy/mm/dd, where blog/2011/03/10 is  supposed to display all posts created on 2011, March 10th. However, the page blog/2011/03/10 actually displays all posts created on 2011, March, 11th, one day advanced to the supplied day argument.
How to reproduce the bug:

clean install, enable modules.
create blog content type, generate dummy contents.
create a view:
<code>  * Arguments:
        o Node: Created year
        o Node: Created month
        o Node: Created day

  * Path: blog

  * Filters
        o Node: Published Yes
        o Node: Type = blog
</code>

The year, month arguments show correctly, just the day is wrong, always one day prior to the day argument.
Can anyone point me to what went wrong?
Comment: This sounds like a datetime issue relating to the timezone setting of the site.
Comment: just update that the latest 7.x-3.0-beta3 fixed this bug.
Answer: Actually had this bug, but with views 2 on drupal 6, and instead of going forward a day, our view was going backward a day.
Have you tried updating to --dev to see if the issue still exists? I know a lot of patches have been committed since that alpha was released.
Comment: It is probably a bug mentioned and patched here: Incorrect timezone handling in views_date_sql_field()
http://drupal.org/node/1091698


Problema ao dar build no projeto em Android

Question: Estou tentando dar build em um projeto feito em Ionic para android, mas ele me volta o seguinte erro:
<code>cordova build android
Running command: "C:\Program Files\nodejs\node.exe" C:\Users\Lucas\Documents\Projects\primeiro\hooks\after_prepare\010_add_platform_class.js C:\Users\Lucas\Documents\Projects\primeiro
add to body class: platform-android
Running command: cmd "/s /c "C:\Users\Lucas\Documents\Projects\primeiro\platforms\android\cordova\build.bat""
[Error: Please install Android target: "android-22".

Hint: Open the SDK manager by running: C:\Users\Lucas\AppData\Local\Android\android-sdk\tools\android.BAT
You will require:
1. "SDK Platform" for android-22
2. "Android SDK Platform-tools (latest)
3. "Android SDK Build-tools" (latest)]
ERROR building one of the platforms: Error: cmd: Command failed with exit code 2
You may not have the required environment or OS to build this project
**Error: cmd: Command failed with exit code 2**
</code>
O Android SDK está instalado, segue uma imagem do mesmo:

Não consigo entender porque disso acontecer. Eu já instalei os sdk, defini a variável ANDROID_HOME e PATH, e mesmo assim ele continua na mesma mensagem. Agradeço desde já.
Answer: Pela descrição do erro, está faltando o download da API level 22 (Android 5.1.1).
Comment: Cara na hora que li isso dei risada, na moral. Que burro que eu sou, eu estava confundindo Android 2.0 com API level 22, que anta. Agradeço pela resposta. Irei instalar aqui e já dou uma resposta.
Comment: Tudo bem! :D @SCOFIELD
Comment: Pronto. Obrigado novamente.


Basic statistical equation

Question: How would I go about showing that:
$$\sum_{i=1}^n (X_i-\bar{X})^2=\sum_{i=1}^n X_i^2-n\bar{X}^2\,,$$ (where $\bar{X}=\frac{1}{n}\sum_{i=1}^n X_i$)?
Thank you for your help!
Comment: Since this is a routine book-work question, it should carry the `self-study` tag  - and whose [tag wiki info](http://stats.stackexchange.com/tags/self-study/info) you should read and follow the guidelines of (i.e. edit your question). Specifically, what have you tried and what problems did you have?
Comment: As for a big hint: expand the quadratic. Separate out the terms into their own sums. Simplify the terms and cancel where appropriate.
Comment: Thank you very much. It took a little bit of research into the properties of the summation operator but once I understood these I figured out how to show this using the steps you provided.
Comment: Would you like to write up an answer? If you write it I'm happy to clean up the formatting. You might as well have the reputation.
Comment: Done - really appreciate your help.
Answer: The first step is to expand the quadratic, the second is to express each term with its own sum, the third is to simplify and the fourth is to cancel out.
\begin{eqnarray}
\sum_{i=1}^n (X_i-\bar X)^2 &=& \sum_{i=1}^n (X_i^2-2X_i\bar X+\bar X^2)\\
 &=& \sum_{i=1}^n X_i^2-2\bar X\sum_{i=1}^n X_i+n(\bar X^2)\\
 &=& \sum_{i=1}^n X_i^2-2n(\bar X^2)+n(\bar X^2)\\
 &=& \sum_{i=1}^n X_i^2-n(\bar X^2)
\end{eqnarray}
Comment: @Stat The OP is answering his own question (on the basis of some suggestions about how to approach it) - and providing a full answer at my invitation. People solving their own problems is perfectly okay on self-study questions.
Comment: For theses type of questions (i.e. self-study tags), you need to provide some hints, not the full answer. Try not to solve their assignments!
Comment: LOL, I didn't check that out!
Comment: (+1) Alternatively, a geometric interpretation makes short work of this result, which asserts the Pythagorean Theorem holds for a triangle with hypotenuse $x=(X_1,X_2,\ldots,X_n)$ and leg $y=(\bar{X},\bar{X},\ldots,\bar{X})$. To verify this you only need check that the two legs are perpendicular; that is, $(x-y)\cdot y=0$; equivalently, that $x\cdot y=y\cdot y.$  But since $\sum_i X_i=\sum_i \bar{X},$ both dot products equal $\bar{X}\sum_i X_i$, QED.

Basic statistical equation


SQL: how to make multiple COUNT/MAX

Question: I have a table named medic_appointment with the following fields: datetime_diagnosis (DATETIME type) and diagnosis. I need to perform a query that will show me the YEAR_MONTH which had the most occurrence of each disease.
I am currently at this point:
SELECT disease , COUNT(*) AS frequency ,
       EXTRACT(YEAR_MONTH FROM datetime_diagnosis) AS interval
FROM medic_appointment
GROUP BY disease , interval

Which results in the following example table:
disease    frequency   interval
--------   ---------   --------
disease1   5           201609
disease1   8           201610
disease1   22          201611
disease1   1           201612
disease2   7           201611

I am trying to do something like this: using the query mentioned above, increment it in a way that it will select the highest frequency number and return me the interval and disease fields, then group by disease...but it is not working this way and i just cannot find another way to figure it out. Not sure if this is the best option.
edit: expected result:
disease    frequency   interval
--------   ---------   --------
disease1   22          201611
disease2   7           201611

Comment: Providing expected result in words is much complicate to understand. Provide expected resultset.
Answer: Try this:
SELECT disease, frequency, interval
FROM (
  SELECT disease, frequency, interval,
         @rnk := IF(@dis = disease, @rnk + 1,
                    IF(@dis := disease, 1, 1)) AS rnk
  FROM (
     SELECT disease, COUNT(*) AS frequency,
            EXTRACT(YEAR_MONTH FROM datetime_diagnosis) AS interval
     FROM medic_appointment
     GROUP BY disease, interval) AS t
  CROSS JOIN (SELECT @rnk := 0, @dis := '') AS vars
  ORDER BY disease, frequency DESC) AS x
WHERE x.rnk = 1

Comment: I tried this but got an error. MySQL points the syntax error around the @dis := disease, 1,1)...i am still trying to understand this code (have never seen something similar before), so it may take a while :( but thanks for showing this new way of working with SQL codes
Comment: Still no success :( keeps telling me there is some syntax error around 4th line (starts with @rnk := ...
Comment: @Rodrigo `@dis` variable was incorrectly initialized. Please try once more.

SQL: how to make multiple COUNT/MAX


Enviando e-mail através do Nodejs

Question: Sou iniciante aprendendo Node.js e estou travado numa questão de envio de e-mail no site como se fosse aquele ''fale conosco'' utilizando Node.js
A questão é, eu consigo enviar o e-mail, porém ele só envia quando a página dá erro e não atualiza. Apresenta a mensagem na tela "Cannot POST /index''
Mas se eu arrumo esse problema pra direcionar pra própria página (no caso, index), ele não envia o e-mail, não consigo entender, poderiam me ajudar?
A forma que vou colocar no exemplo ele envia o e-mail, porém retorna uma página com o erro informado ("Cannot POST /index"), porém se eu corrijo isso colocando no server.js:
app.use('/index', require('./routes/index'));

O e-mail não é enviado. E se eu tiro o ''action'' ou deixo ''action = /'' no HTMl, ele retorna a página certa, porém não envia o e-mail também.
Obs: estou usando express

server.js

const nodemailer = require('nodemailer');
var enviar = function(req, res, next) {
var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'firstname.lastname@example.com',
        pass: '123'
    }
});
var mailOptions = {
    from: 'email@example.com',
    to: 'firstname.lastname@example.com',
    subject: 'Nome: ' + req.body.nome + ' / Telefone: ' + req.body.telefone,
    text: req.body.mensagem
};
transporter.sendMail(mailOptions, function(error, info) {
    if (error) {
        console.log(error);
    } else {
        console.log('Email sent: ' + info.response);
    }
});
next();
};
app.use(enviar);
index.html

<form method="POST" action="/index">

Nos envie uma mensagem!

        <textarea name="mensagem"></textarea>

    Nome: <input type="text" name="nome" />

    Telefone: <input type="text" name="telefone" />

        <button class="button special" onclick="enviar()">Enviar</button>

</form>
Answer: Essa mensagem de erro "Cannot POST /index" é porque a rota index não deve estar aceitando acesso pelo método POST
Aqui tem um exemplo de rota que recebe um post de formulário:

let express = require("express"),
  path = require('path'),
  nodeMailer = require('nodemailer'),
  bodyParser = require('body-parser');

let app = express();

app.use(express.static('src'));

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.post('/send-email', function (req, res) {
  let transporter = nodeMailer.createTransport({
      host: 'smtp.gmail.com',
      port: 465,
      secure: true,
      auth: {
          user: 'email@example.com',
          pass: 'test'
      }
  });
  let mailOptions = {
      // should be replaced with real recipient's account
      to: 'email@example.com',
      subject: 'Assunto do email',
      body: req.body.mensagem
  };
  transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
          return console.log(error);
      }
      console.log('Message %s sent: %s', info.messageId, info.response);
  });
  //Redirecionar
  res.writeHead(301, { Location: 'index.html' });
  res.end();
});

let server = app.listen(8081, function(){
    let port = server.address().port;
    console.log("Server started at http://localhost:%s", port);
});

Os campos do seu formulário você pode pegar com o req.body. Você pode alterar este exemplo com as suas configurações de conexão.
No caso, o formulário ficaria da seguinte forma:

<form method="POST" action="/send-email">

Nos envie uma mensagem!

        <textarea name="mensagem"></textarea>

        <input type="submit" value="Envoar">

</form>

Enviando e-mail através do Nodejs