Initialization of an ArrayList in one line

Question: I wanted to create a list of options for testing purposes. At first, I did this:
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

Then, I refactored the code as follows:
ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

Is there a better way to do this?
Comment: If this is intended for unit testing, try groovy out for a swing. You can write your test code in it while testing java code, and use `ArrasyList places = ["Buenos Aires", "Córdoba", "La Plata"]`
Comment: Stream.of("val1", "val2").collect(Collectors.toList()); //creates ArrayList, Java8 solution.
Comment: I don't understand why we cannot have some thing like `List = {1, 2, 3, 4, 5}` in Java. Create and init a mutable array in one line, as I know Python and Swift could do that.
Comment: In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>): Map> myMap = new HashMap<>();
Comment: See also http://stackoverflow.com/questions/157944/create-arraylist-from-array
Comment: use double bracing initialization :)
Comment: It seems like you answered yourself in the question: ArrayList places = new ArrayList(asList("Buenos Aires", "Córdoba", "La Plata")); Arrays in Arrays.asList is not needed.
Comment: Why not just use String [] places = {"Buenos Aires", "Córdoba", "La Plata"); ?
Comment: @PaulSmith He might be interested in an elastic array that can grow dynamically. Your initialization will make **places** to have just three elements.
Answer: It would be simpler if you were to just declare it as a List - does it have to be an ArrayList?
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");

Or if you have only one element:
List<String> places = Collections.singletonList("Buenos Aires");

This would mean that places is immutable (trying to change it will cause an UnsupportedOperationException exception to be thrown).
To make a mutable list that is a concrete ArrayList you can create an ArrayList from the immutable list:
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

And import the correct package:
import java.util.Arrays;

Comment: As per my answer, if you're not using methods specific to `ArrayList`, it would be better design to change the declaration to `List`. Specify interfaces, not implementations.
Comment: Just to be clear, `asList(...)` returns a fixed size `List` that blows up on mutating operations like `remove` and `clear`, things the `List` contract claims to support. Even if you left declaration as `List`, you sill need to use `List l = new ArrayList(asList(...))` in order to get an object that doesn't throw OperationNotSupported exceptions. Liskov Substitution Principle anyone?
Comment: @Marcase: Can you not change your class to use a List instead of ArrayList?
Comment: @Christoffer Hammarström: if he changes the declaration to *List* and uses the *List places = Arrays.asList(...);* he will not be able to use *places.add("blabla")*
Comment: Yes, my class has an private ArrayList.
Comment: @maks: True, except that's because of using `asList(...)`, not because of changing the declaration from `ArrayList` to `List`. I would put it as "he will not *need* to use `places.add("blabla")`". He already changed it to `asList(...)` himself.
Comment: How can it be that I need to lookup how to initialise a fucking mutable array every time I need to? And this is supposedly the best way? What an horrible language.
Comment: @Software Monkey: I wanted to know how to initialize an ArrayList. It's not real code, I was just testing things out. So, yes I might change it to List, but that would not answer my question.
Comment: I find this answer slightly misleading, because it suggests that `Arrays.asList` returns something immutable.  That's not true.  It returns a list that can't be lengthened or shortened; but which can be mutated by swapping out an element for a new value.
Answer: Actually, probably the "best" way to initialize the ArrayList is the method you wrote, as it does not need to create a new List in any way:
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");

The catch is that there is quite a bit of typing required to refer to that list instance.
There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):
ArrayList<String> list = new ArrayList<String>() {{
    add("A");
    add("B");
    add("C");
}};

However, I'm not too fond of that method because what you end up with is a subclass of ArrayList which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.
What would have been nice was if the Collection Literals proposal for Project Coin was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):
List<String> list = ["A", "B", "C"];

Unfortunately it won't help you here, as it will initialize an immutable List rather than an ArrayList, and furthermore, it's not available yet, if it ever will be.
Comment: See http://stackoverflow.com/questions/924285/ for more information about the double-brace initialization, pros and cons.
Comment: you don't need the second .
Comment: @Delight The "diamond operator" was introduced in Java 7, which wasn't released when I wrote this answer back in 2009 ;)
Answer: The simple answer
Java 9 or later:
List<String> strings = List.of("foo", "bar", "baz");

List.of(...) will give you an immutable List, so it cannot be changed.
Which is what you want in most cases where you're prepopulating it.
This does not allow null elements.
Java 8 or earlier:
List<String> strings = Arrays.asList("foo", "bar", "baz");

Arrays.asList(...) will give you a List* backed by an array, so it cannot change length.
But you can call List.set(...), so it's still mutable.
This does allow null elements.
*
Implementation detail: It's a private nested class inside java.util.Arrays, named ArrayList,
which is a different class from java.util.ArrayList, even though their simple names are the same.
Static import
You can make Java 8 Arrays.asList even shorter with a static import:
import static java.util.Arrays.asList;
...
List<String> strings = asList("foo", "bar", "baz");

Any modern IDE* will suggest and do this for you.
I don't recommend statically importing the List.of method as just of, because it's confusing.
*
For example, in IntelliJ IDEA you press Alt+Enter and select Static import method...
Using Streams
Why does it have to be a List?
With Java 8 or later you can use a Stream which is more flexible:
Stream<String> strings = Stream.of("foo", "bar", "baz");

You can concatenate Streams:
Stream<String> strings = Stream.concat(Stream.of("foo", "bar"),
                                       Stream.of("baz", "qux"));

Or you can go from a Stream to a List:
import static java.util.stream.Collectors.toList;
...
var strings = Stream.of("foo", "bar", "baz").toList(); // Java 16

List<String> strings = Stream.of("foo", "bar", "baz").collect(toList()); // Java 8

But preferably, just use the Stream without collecting it to a List.
If you specifically need a java.util.ArrayList*
If you want to both prepopulate an ArrayList and add to it afterwards, use
List<String> strings = new ArrayList<>(List.of("foo", "bar"));

or in Java 8 or earlier:
List<String> strings = new ArrayList<>(asList("foo", "bar"));

or using Stream:
import static java.util.stream.Collectors.toCollection;

List<String> strings = Stream.of("foo", "bar")
                             .collect(toCollection(ArrayList::new));

Then you can add to it after construction:
strings.add("baz");

But again, it's better to just use the Stream directly instead of collecting it to a List.
*You probably don't need specifically an ArrayList. To quote JEP 269:

There is a small set of use cases for initializing a mutable collection instance with a predefined set of values. It's usually preferable to have those predefined values be in an immutable collection, and then to initialize the mutable collection via a copy constructor.

(emphasis mine)
Program to interfaces, not to implementations
You said you've declared the list as an ArrayList in your code, but you should only do that if you're using some member of ArrayList that's not in List.
Which you are most likely not doing.
Usually you should just declare variables by the most general interface that you are going to use (e.g. Iterable, Collection, or List), and initialize them with the specific implementation (e.g. ArrayList, LinkedList or Arrays.asList()).
Otherwise you're limiting your code to that specific type, and it'll be harder to change when you want to.
For example, if you're passing an ArrayList to a void method(...):
// Iterable if you just need iteration, for (String s : strings):
void method(Iterable<String> strings) {
    for (String s : strings) { ... }
}

// Collection if you also need .size(), .isEmpty(), or .stream():
void method(Collection<String> strings) {
    if (!strings.isEmpty()) { strings.stream()... }
}

// List if you also need random access, .get(index):
void method(List<String> strings) {
    strings.get(...)
}

// Don't declare a specific list implementation
// unless you're sure you need it:
void method(ArrayList<String> strings) {
    ??? // You don't want to limit yourself to just ArrayList
}

Another example would be always declaring variable an InputStream even though it is usually a FileInputStream or a BufferedInputStream, because one day soon you or somebody else will want to use some other kind of InputStream.
Comment: It's worth mentioning that streams need to be closed whereas lists do not.
Comment: @MikeLowery: Are you thinking of `InputStream` and `OutputStream`? `java.util.stream.Stream` does not need to be closed. It does need a *terminal operation*, but you're not going to forget that, because without it the stream does nothing.
Comment: That's what I was actually working with, yes. But `java.util.stream.Stream` extends `BaseStream` which does have a `close()` method because it implements `AutoCloseable`. At the very least an IDE is going to complain about a potential resource leak.
Comment: @MikeLowery: You don't need to close Streams in general, and i haven't seen IntelliJ IDEA complain about me not doing so. See https://stackoverflow.com/questions/22125169/why-is-java-8-stream-class-autocloseable
Comment: Eclipse does, provided you have it configured to find potential resource leaks. Personally I think it's confusing to have a class implement `AutoCloseable` when it may not need to actually be closed, but that's exactly what they did (see [API note](https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html)).
Comment: Also `Arrays.asList` allows passing null elements, while `List.of` doesn't.
Answer: If you need a simple list of size 1:
List<String> strings = new ArrayList<String>(Collections.singletonList("A"));

If you need a list of several objects:
List<String> strings = new ArrayList<String>();
Collections.addAll(strings,"A","B","C","D");

Answer: With Guava you can write:
ArrayList<String> places = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata");

In Guava there are also other useful static constructors. You can read about them here.
Comment: @beckah method Arrays.asLists creates object of type List, while question is about creating ArrayList
Comment: I'm pretty sure you can do this with just `java.util.Arrays` such as, `List names = Arrays.asList("Beckah", "Sam", "Michael");`
Comment: [*This method is not actually very useful and will likely be deprecated in the future.*](https://google.github.io/guava/releases/22.0/api/docs/com/google/common/collect/Lists.html#newArrayList-E...-)
Comment: @beckah `Arrays.asList` creates a list that can't be modified. If the list needs to be modified `Lists.newArrayList` will work and `Arrays.asList` won't.
Answer: With java-9 and above, as suggested in JEP 269: Convenience Factory Methods for Collections, creating an unmodifiable List instead of an ArrayList could be achieved using collection literals now with -
List<String> list = List.of("A", "B", "C");

Set<String> set = Set.of("A", "B", "C");

A similar approach would apply to Map as well -
Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3")

which is similar to Collection Literals proposal as stated by @coobird. Further clarified in the JEP as well -

Alternatives

Language changes have been considered several times, and rejected:
Project Coin Proposal, 29 March 2009
Project Coin Proposal, 30 March 2009
JEP 186 discussion on lambda-dev, January-March 2014
The language
proposals were set aside in preference to a library-based proposal as
summarized in this message.

Related: What is the point of overloaded Convenience Factory Methods for Collections in Java 9
Comment: Note that this creates an immutable `List` and not a modifiable `ArrayList`!
Comment: @xuiqzy precisely an *unmodifiable* one, if one was to mention
Answer: Collection literals didn't make it into Java 8, but it is possible to use the Stream API to initialize a list in one rather long line:
List<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toList());

If you need to ensure that your List is an ArrayList:
ArrayList<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toCollection(ArrayList::new));

Answer: import com.google.common.collect.ImmutableList;

....

List<String> places = ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");

Comment: No, it's not the same. As ImmutableList is documenting its immutability in the result type when unmodifiableList masquerades it  as a normal List.
Comment: I don't want to add a new dependency just to do that.
Comment: That's the same as `Collections.unmodifiableList(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"))`, which becomes `unmodifiableList(asList("Buenos Aires", "Córdoba", "La Plata"))` with static imports. You don't need Google Collections for this.
Comment: You're going to pass that `ImmutableList` to other methods that take a `List`, and then you've lost that documentation anyway.
Comment: Instead of the immutable one, google collections also offer mutable array list:
List = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata");
Comment: @ChristofferHammarström No, you can still check its type at runtime, which can be useful.
Comment: @xuiqzy: Yes, but i was talking about in source code. Running extra code to check what type of List is being passed isn't what i call documentation. And if you're doing that you can just check if its a Collections.UnmodifiableList so the original point is moot anyway.
Answer: You could create a factory method:
public static ArrayList<String> createArrayList(String ... elements) {
  ArrayList<String> list = new ArrayList<String>();
  for (String element : elements) {
    list.add(element);
  }
  return list;
}

....

ArrayList<String> places = createArrayList(
  "São Paulo", "Rio de Janeiro", "Brasília");

But it's not much better than your first refactoring.
For greater flexibility, it can be generic:
public static <T> ArrayList<T> createArrayList(T ... elements) {
  ArrayList<T> list = new ArrayList<T>();
  for (T element : elements) {
    list.add(element);
  }
  return list;
}

Comment: @LeoHolanda: Creating factory methods for every little thing is too much, I agree. But _depending_ on the situation, and on the number of times that that method is going to be used, it might make sense to create it. Creating extra abstraction layers is meant to _remove_ complexity, by creating more _meaningful_ methods that capture the _intent_ of the designer.
Comment: Look back at the original post, it is asking for array initialization in *one line*, not 7 additional lines.
Comment: I think we can replace the enhanced `for` with `Collections.addAll(elements)` as described [here](https://stackoverflow.com/a/7238739/6243352).
Answer: In Java 9 we can easily initialize an ArrayList in a single line:
List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");

or
List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));

This new approach of Java 9 has many advantages over the previous ones:

Space Efficiency
Immutability
Thread Safe

See this post for more details -> What is the difference between List.of and Arrays.asList?
Comment: The first example does not create an `ArrayList`, despite the preceding sentence indicating that it does.
Answer: Java 9 has the following method to create an immutable list as documented (or documented as unmodifiable Java 10+):
List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");

which is easily adapted to create a mutable list, if required:
List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));

Similar methods are available for Set and Map.
Please note that these methods do not accept null elements, a little bit hidden in the documentation:

Throws:
NullPointerException - if an element is null ...
Comment: Its good that you explicitly said "immutable list" and then showed another example of mutable list because it makes it clear which to use when.
Answer: Simply use below code as follows.
List<String> list = new ArrayList<String>() {{
            add("A");
            add("B");
            add("C");
}};

Comment: This is not one-line
Answer: (Should be a comment, but too long, so new reply). As others have mentioned, the Arrays.asList method is fixed size, but that's not the only issue with it. It also doesn't handle inheritance very well. For instance, suppose you have the following:
class A {}
class B extends A {}

public List getAList() {
    return Arrays.asList(new B());
}

The above results in a compiler error, because List (which is what is returned by Arrays.asList) is not a subclass of List, even though you can add Objects of type B to a List object.  To get around this, you need to do something like:
new ArrayList(Arrays.asList(b1, b2, b3))

This is probably the best way to go about doing this, especially if you need an unbounded list or need to use inheritance.
Comment: this is relevant only for Java versions previous to Java 8 (or even older) - the mentioned compiler error cannot be reproduced with Java 8 or later (example https://ideone.com/WHPY5d) - with not-so-old versions, the compiler is able to correctly infer the list type
Answer: About the most compact way to do this is:
Double array[] = { 1.0, 2.0, 3.0};
List<Double> list = Arrays.asList(array);

Answer: With Eclipse Collections you can write the following:
List<String> list = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");

You can also be more specific about the types and whether they are Mutable or Immutable.
MutableList<String> mList = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableList<String> iList = Lists.immutable.with("Buenos Aires", "Córdoba", "La Plata");

You can also do the same with Sets and Bags:
Set<String> set = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableSet<String> mSet = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet<String> iSet = Sets.immutable.with("Buenos Aires", "Córdoba", "La Plata");

Bag<String> bag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableBag<String> mBag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableBag<String> iBag = Bags.immutable.with("Buenos Aires", "Córdoba", "La Plata");

Note: I am a committer for Eclipse Collections.
Answer: Here is another way:
List<String> values = Stream.of("One", "Two").collect(Collectors.toList());

Answer: List<String> names = Arrays.asList("2", "@2234", "21", "11");

Comment: Note that this creates an immutable List and not a modifiable ArrayList!
Answer: You can use the below statements:
Code Snippet:
String [] arr = {"Sharlock", "Homes", "Watson"};

List<String> names = Arrays.asList(arr);

Comment: You can inline first expression to have compact solution: `letters = Arrays.asList(new String[]{"A", "B", "C"});`
Answer: There are multiple ways to create and initialize list in one line. Some examples:
//Using Double brace initialization, creates a new (anonymous) subclass of ArrayList
List<String> list1 = new ArrayList<>() {{ add("A");  add("B"); }};

//Immutable List
List<String> list2 = List.of("A", "B");

//Fixed size list. Can't add or remove element, though replacing the element is allowed.
List<String> list3 = Arrays.asList("A", "B");

//Modifiable list
List<String> list4 = new ArrayList<>(Arrays.asList("A", "B"));

//Using Java Stream, no guarantees on the type, mutability, serializability, or thread-safety
List<String> list5 = Stream.of("A", "B").collect(Collectors.toList());

//Thread safe List
List<String> list6 = new CopyOnWriteArrayList<>(Arrays.asList("A", "B"));

Answer: Like Tom said:
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");

But since you complained of wanting an ArrayList, you should first know that ArrayList is a subclass of List and you could simply add this line:
ArrayList<String> myPlaces = new ArrayList(places);

Although, that might make you complain about 'performance'.
In that case, it doesn't make sense to me, why, since your list is predefined it wasn't defined as an array (since the size is known at the time of initialization). And if that's an option for you:
String[] places = { "Buenos Aires", "Córdoba", "La Plata" };

In case you don't care about the minor performance differences then you can also copy an array to an ArrayList very simply:
ArrayList<String> myPlaces = new ArrayList(Arrays.asList(places));

Okay, but in the future, you need a bit more than just the place name, you need a country code too. Assuming this is still a predefined list that will never change during run-time, then it's fitting to use an enum set, which would require re-compilation if the list needed to be changed in the future.
enum Places { BUENOS_AIRES, CORDOBA, LA_PLATA }

would become:
enum Places {
    BUENOS_AIRES("Buenos Aires", 123),
    CORDOBA("Córdoba", 456),
    LA_PLATA("La Plata", 789);

    String name;
    int code;

    Places(String name, int code) {
      this.name = name;
      this.code = code;
    }
}

Enums have a static values method that returns an array containing all of the values of the enum in the order they are declared, e.g.:
for (Places p : Places.values()) {
    System.out.printf("The place %s has code %d%n",
                  p.name, p.code);
}

In that case, I guess you wouldn't need your ArrayList.
P.S. Randyaa demonstrated another nice way using the static utility method Collections.addAll.
Answer: Yes. With the help of Arrays you can initialize an immutable List (instead of an ArrayList) in one line:
List<String> strlist = Arrays.asList("aaa", "bbb", "ccc");

Answer: You can use StickyList from Cactoos:
List<String> names = new StickyList<>(
  "Scott Fitzgerald", "Fyodor Dostoyevsky"
);

Answer: Using Arrays.asList("Buenos Aires", "Córdoba", "La Plata"); is correct. but Any calls to Arrays.asList() with zero arguments or only one argument could be replaced with either a call to Collections.singletonList() or Collections.emptyList() which will save some memory.
Note: the list returned by Collections.singletonList() is immutable, while the list returned Arrays.asList() allows calling the set() method. This may break the code in rare cases.
Answer: Try with this code line:
Collections.singletonList(provider)

Comment: Add a brief description of your answer.
Answer: In Java, you can't do
ArrayList<String> places = new ArrayList<String>( Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

As was pointed out, you'd need to do a double brace initialization:
List<String> places = new ArrayList<String>() {{ add("x"); add("y"); }};

But this may force you into adding an annotation @SuppressWarnings("serial") or generate a serial UUID which is annoying. Also most code formatters will unwrap that into multiple statements/lines.
Alternatively you can do
List<String> places = Arrays.asList(new String[] {"x", "y" });

but then you may want to do a @SuppressWarnings("unchecked").
Also according to javadoc you should be able to do this:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

But I'm not able to get it to compile with JDK 1.6.
Comment: Wrong! You *can* do the first line, and that is the right answer btw
Answer: Collections.singletonList(messageBody)

If you'd need to have a list of one item!
Collections is from java.util package.
Answer: The best way to do it:
package main_package;

import java.util.ArrayList;

public class Stackkkk {
    public static void main(String[] args) {
        ArrayList<Object> list = new ArrayList<Object>();
        add(list, "1", "2", "3", "4", "5", "6");
        System.out.println("I added " + list.size() + " element in one line");
    }

    public static void add(ArrayList<Object> list, Object... objects) {
        for (Object object : objects)
            list.add(object);
    }
}

Just create a function that can have as many elements as you want and call it to add them in one line.
Comment: If you go through all the trouble you might as well make it a template method instead of using plain `Object`.
Answer: interestingly no one-liner with the other overloaded Stream::collect method is listed
ArrayList<String> places = Stream.of( "Buenos Aires", "Córdoba", "La Plata" ).collect( ArrayList::new, ArrayList::add, ArrayList::addAll );

Comment: Totally different answer. Thanks
Answer: For me, Arrays.asList() is the best and most convenient one. I always like to initialize that way.
If you are a beginner in Java Collections then I would like you to refer ArrayList initialization.
Comment: Why is Arrays.asList() better than creating a new ArrayList in one line with `add()` methods?
Answer: Here is code by abacus-common
// ArrayList
List<String> list = N.asList("Buenos Aires", "Córdoba", "La Plata");
// HashSet
Set<String> set = N.asSet("Buenos Aires", "Córdoba", "La Plata");
// HashMap
Map<String, Integer> map = N.asMap("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);

// Or for Immutable List/Set/Map
ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);

// The most efficient way, which is similar with Arrays.asList(...) in JDK.
// but returns a flexible-size list backed by the specified array.
List<String> set = Array.asList("Buenos Aires", "Córdoba", "La Plata");

Declaration: I'm the developer of abacus-common.
Answer: Why not make a simple utility function that does this?
static  ArrayList ll(A... a) {
  ArrayList l = new ArrayList(a.length);
  for (A x : a) l.add(x);
  return l;
}

"ll" stands for "literal list".
ArrayList<String> places = ll("Buenos Aires", "Córdoba", "La Plata");

Comment: you could use Collections.addAll instead of the for loop. Also, if you name the method `list`, the name requires no explanation :)
Answer: Simplest way : you can use this approach to add multiple elements to any type of collection like ArrayList and HashSet
ArrayList<String> allViews = new ArrayList<String>();
Collections.addAll(allViews,"hello","world","abc","def","ghi");

Answer: I suspect the original question relates to a desire to declare and initialize the ArrayList in one line and avoid having to create separate code to acheive the initialization. Thus, the answer lies in the question but may be generalized as follows:
ArrayList<AnyClass> arrayListOfAnyClass = new ArrayList<>(Arrays.asList(
  new AnyClass(param11, param12, ...),
  new AnyClass(param21, param22, ...),
  new AnyClass(param31, param32, ...),
  ...
));

Answer: Actually, it's possible to do it in one line:
Arrays.asList(new MyClass[] {new MyClass("arg1"), new MyClass("arg2")})

Comment: May I ask what this adds to the question? This answer is already covered multiple times by other answers.
Comment: This is actually a really bad soluition as it creates an ABSTRACT LIST. You will not be able to add anything more to the container.
Answer: public static <T> List<T> asList(T... a) {
    return new ArrayList<T>(a);
}

This is the implementation of Arrays.asList, so you could go with
ArrayList<String> arr = (ArrayList<String>) Arrays.asList("1", "2");

Comment: -1 Those are [not the same class](http://stackoverflow.com/questions/12015980/arrays-aslist-confusing-source-code/12015999#12015999).


Theorem 2.13 in Walter Rudin's Principles of Mathematical Analysis

Question: While reading Walter Rudin's Principles of Mathematical Analysis, I ran into the following theorem:

Theorem 2.13. Let $A$ be a countable set, and let $B_n$ be the set of all $n$-tuples $\left(a_1,\dots,a_n\right)$, where $a_k\in A$ ($k=1,\dots,n$), and the elements $a_1,\dots,a_n$ need not be distinct. Then $B_n$ is countable.
Proof. That $B_1$ is countable is evident since $B_1=A$. (pause)

Okay, from the theorem's statement, I can see that $B_1=\left\{a_1:a_1\in A\right\}=A$ (assuming $\left(a_1\right)=a_1$). So far so good.

(continue) Suppose $B_{n-1}$ is countable ($n=2,3,4,\dots$). The elements of $B_n$ are of the form
$$
\left(b,a\right)\qquad\left(b\in B_{n-1},a\in A\right).\text{ (pause)}
$$

This makes sense because $B_n$ differs from $B_{n-1}$ in the sense that $B_n$ has an additional element, $a$. Now, this is what throws me off:

(continue) For every fixed $b$, the set of pairs $\left(b,a\right)$ is equivalent to $A$. (pause)

I am going to end right here. How is this true? I mean, if I take $b\in B_1$, then $\left(b,a\right)$ is a $2$-tuple, and $A$ has no element that is a $2$-tuple.
What am I missing?
Answer: Fix any $b\in B_{n-1}$, and let $S_b=\{\langle b,a\rangle:a\in A\}$; the assertion is that $S_b$ is equivalent to $A$. By this he means simply that there is a bijection between $S_b$ and $A$, and it's easy to describe one: the map
$$f_b:S_b\to A:\langle b,a\rangle\mapsto a$$
is such a bijection.
Comment: @Josué: You're welcome!
Comment: Thank you for the clarification! That makes sense. For a moment there, I thought that with *equivalent* he meant *equal*.


Determine if $f=g$ almost everywhere.

Question: Determine the set of real values where the given function $f$ does not equal the given function $g$. Then use Definition 1.2.3 to prove $f=g$ almost everywhere.
Definition 1.2.3: The functions $f$ and $g$ are said to be equal almost everywhere when $f(x)=g(x)$ for all $x$ in the functions domains, except possible for a set $x$ values that has measure zero.
The two functions are
$f(x)=\begin{cases}
1 & x\in(0,1) \\
0 & x\notin (0,1)
\end{cases}$
and $g(x)=\begin{cases}
1 & x\in[0,1] \\
0 & x\neq[0,1]
\end{cases}$
I see that $f(1)\neq g(1) $ and $f(0)\neq g(0)$.
So is the set of real values where $f\neq g$ $\{0,1\}$?
And how to I show that $f=g$ almost everywhere using the definition?
This is what I have for determining measure zero:
Let $\epsilon >0$ be given and let $S=\{0,1\}$. Then we can cover $S$ with the open intervals $I_1 = (-\frac{\epsilon}{4},\frac{\epsilon}{4})$ and $I_2 = (\frac{1-\epsilon}{4}, \frac{1+\epsilon}{4})$.
$m(I_1)=0$ and $m(I_2)= \frac{\epsilon}{2}$.
Then $\sum_{n=1}^{2} m(I_n) = 0+\frac{\epsilon}{2} = \frac{\epsilon}{2} < \epsilon$
Comment: Show that the set $\{0,1\}$ has measure zero.
Comment: almost every with respect to which measure?
Comment: @GuyFsone the question does not specify as to which measure
Comment: @rover2 Then it has to be Lebesgue. Show that $\int_S 1\text{d}x=0$ where $S$ has cardinality $2$...
Comment: i added above my attempt at showing measure zero if anyone can validate it?
Answer: If your measure is Lebesgue measure $\lambda$, then $\lambda(\{0,1\})=0$ and the functions agree on the rest of the points, so you found your zero measure set. (I think you refer to Lebesgue measure as you are  using open interval to compute the measure of your set, allegedly using the Lebesgue outer measure representation of measurable sets).
Of course on different measure spaces this might not be true. Let $(\mathbb R, \{\emptyset,\mathbb R,\{1\}, \mathbb R\backslash \{1\}\}, \delta_1)$ be your measure space, where $\delta_1(A)=1$ if $1\in A$ and $0$ otherwise. Then for every zero measure set $A$ in your $\sigma$-algebra (only $\mathbb R\backslash \{1\}$ and $\emptyset$), there exist a point $\mathbb R\backslash A$ where the two functions differ.

Determine if $f=g$ almost everywhere.


X random variable with binomial distribution. calc E(exp(x))

Question: i have problems with calulating
$$E(e ^X)$$
X has a binomialdistributon with parameters n,p. E is the expectation.
My approach $$ E(e^X)= \sum_{k=0}^n e^k \binom{n}{k}p^k (1-p)^{n-k}  = ... ?$$
Answer: Hint Note that $e^k \cdot p^k = (e \cdot p)^k$. Apply the Binomial Theorem...
Comment: Binomial theorem... do you think of this: $(ep+1-p)^n$ ?
Comment: @user1324258 Exactly!
Comment: Ohh its very simple thank you!
Answer: $$ E(e^X)= \sum_{k=0}^n e^{k} \binom{n}{k}p^k (1-p)^{n-k}  = \sum_{k=0}^n \binom{n}{k}(ep)^k (1-p)^{n-k} =(1-p+pe)^{n}$$
Answer: hint:$$E(e^X)= \sum_{k=0}^n e^k \binom{n}{k}p^k (1-p)^{n-k} $$ $$\sum_{k=0}^n   \binom{n}{k}({ep})^k (1-p)^{n-k}=(ep+1-p)^n$$


After a vendor update the Login from FosuserBundle returns Call to a member function has() on nu

Question: in Januar I have the similar problem, and actually I'm wondering why the problem comes again:
It's a symfony 2.8 project, and I'm using the fosuserbundle, in the config.json is the version
"friendsofsymfony/user-bundle": "~2.1",

So its not a dev-Version. On 5th Januar I make a vendor update - all works fine.
Yesterday i make an vendor update, and on calling the /login I got
Call to a member function has() on null
at
[path_to_my_project] /vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php line 184
I have tested to downgrade the fosuserbundle, but that does not help. I assume, it has to with some update on the symfony sources after the 5th Janaur 2018.
Has somebody acutally the same problem?
Cheers
Thomas
Answer: For those, who has the similar problem: It seems it has to do with some changes from
"friendsofsymfony/user-bundle": "2.0.2" to "friendsofsymfony/user-bundle": "2.1.0".
So i write in the composer.json the Version 2.0.2 until i find exactly, why this problem occurs.


How to Retrieve the data from the server

Question: After the successful connection to the server(my local host),i want to retrieve the data that server sends to me. Can anyone please suggest me what should i do for this?
After receiving that data, i have to store it into an Array and then have to fetch it one by one into the dropdown list.
Thanks
Comment: getting data from a server is usually done via an http request
Comment: I known that my questions are quite silly, but let me inform you all that,i have started with Android just two weeks before. I don't even have the basic knowledge of it,and this is my learning stage.
Comment: Thanks Slayton, But i have receive a response from the server, now just i have to retrieve that data in an Array. And than have to fetch the data from that array n place it in my Spinner object
Comment: Sheetal, you are probably not going to get the response you are looking for b/c client server communication is not a trivial problem that someone can simply explain in a few lines.  There are simple implementations but those only work for some cases. You should buy a book that explains how to implement client/server communication in Android. It will be more complete then any answer you get here and will address a lot of the caveats that you will need to take into account.
Answer: Sheetal i have not worked with any application with server,but  i retrieved data locally and then placed it in an array and showed in the spinner, this might help u
<code>Cursor c = db.fetchAllReminders();
            startManagingCursor(c);

            // Create an array to specify the fields we want (only the TITLE)
            String[] from = new String[]{DataManager.NAME};
            // and an array of the fields we want to bind in the view
            int[] to=new int[] { android.R.id.text1 };
//         to[0]=android.R.id.text1;

             final Spinner spinner = (Spinner) this.findViewById(R.id.spins);

            // Now create a simple cursor adapter and set it to display
            final SimpleCursorAdapter reminders =new SimpleCursorAdapter(this,
                    android.R.layout.simple_spinner_item, c, from, to);
            spinner.setAdapter(reminders);
</code>


Showing $\{x\in X|f(\{x\}\times[0,1])\subseteq U\}$ is open

Question: Let $f:X\times[0,1]\rightarrow Y$ be a continuous function, and let $U\subseteq Y$ be an open set. Show that the set $V=\{x\in X|f(\{x\}\times[0,1])\subseteq U\}$ is open in $X$.
I don't really know where to start with this problem, and I don't see how it relates to compactness or boundedness, which is what the preceding chapter was about.
Answer: Let $x\in V$ and $t\in[0,1]$, let $V_{x,t}$, $U_{x,t}$ such that $x\in V_{x,t}$, $t\in U_{x,t}$ and $f(V_{x,t}\times U_{x,t})\subseteq U$. Now $[0,1]\subseteq U:=U_{x,t_{1}}\cup\cdots\cup U_{x,t_{N}}$, let $W=V_{x,t_{1}}\cap\cdots\cap V_{x,t_{N}}$, now $x\in W\subseteq V$.
Answer: The compactness of $[0,1]$ makes the projection $X\times [0,1]\to X$ into a closed map. Now note that the complement of $V$ is the projection of the complement of $f^{-1}(U)$, and therefore closed.


thumbanail create function error with php version 5.2.9

Question: My servers php version is 5.2.9,
i'm uploading some pictures into my site, i want to create thumbnails of that images,
but none of the thumbnail create functions are working in my site.
like imagecreatefromjpeg(),
imagecreatetruecolor(),
everything is saying undefined function..
what will be reason for this.
Is the functions are not supported in php version 5.2.9
How can i solve this problem.
Can anyone help to fix this issue.
Thanks in Advance
Comment: can you use like @imagecreatefromjpeg
Answer: It looks like the GD library is not installed. Are you on a shared host, or an own server?
Comment: how can i know whether gd library enabled or not?
i have searched in my phpinfo, but nothing showed like gd
Comment: You should see a heading named "GD" with "GD Support  Enabled". I'm sure you don't have GD library now. Again: what OS are you using? Win32 or Linux? Are you able to install software on that server?
Comment: check phpinfo or as administrator to enable gd library to specific gd2


Does anyone know of a program or script to show which route is being used for an IP address?

Question: In Windows (say Windows 10), I'd like to put in an address, and then the relevant line from the routing table is shown (if any). So, pretend you are pinging an address and the computer processes the routing table and figures out which route to use. It would also be nice for the program to show which of the various network adapters/interfaces it would use. That way, if I suspect there is a routing issue, I can quickly figure out if there is a route and if so, is that the route I would expect. With modern configurations having like 80 lines in the routing table and multiple physical adapters as well as VPN adapters and such, there can be a lot to look through to figure out what's happening.
Comment: ...which determines the first hop shown in tracert.
Comment: You don't like tracert? https://ss64.com/nt/tracert.html
Comment: I don't understand. Tracert shows responses from endpoints as a packet actually traverses a network. I'm talking about the routing table on my machine.
Answer: Powershell:
Find-NetRoute -RemoteIPAddress <destination>

or somewhat similar to the route print output:
Find-NetRoute -RemoteIPAddress <destination> | Format-Table -Property DestinationPrefix,NextHop,InterfaceAlias


Is the matrix dimension important for performing a valid PCA?

Question: If $X$ is a $m × n$ matrix, where $m$ is the number of measurement types (variables) and $n$ is the number of samples, would it be correct to perform a PCA on a matrix that has $m \geq n$ ? If not, please provide some arguments why would this be a problem.
I remember having heard that doing such an analysis would be invalid, but the Wikipedia page for PCA doesn't mention a low $n/m$ ratio as being a potential limitation for using the method.
Please note that I am a biologist and aim at a more practical answer (if possible).
Answer: PCA of variables. Number of observations n is low relative to number of variables.
1) Mathematical aspect. Whenever n<=m correlation matrix is singular which means some of last m principle components are zero-variance, that is, they are not existant. This is not a problem to PCA, generally speaking, since you could just ignore those. However, many software (mostly those uniting PCA and Factor Analysis in one command or procedure) will not allow you to have singular correlation matrix.
2) Statistical aspect. To have your results reliable you must have correlations reliable; that requires considerable sample size which always should be larger than number of variables. They say, if you have m=20 you ought to have n=100 or so. But if you have m=100 you should have n=300 or so. As m grows, minimal recommended n/m proportion diminishes.
Comment: Thank you for the answer! Having mentioned the correlation matrix, now the n/m problem is clearer, but how do you define a "reliable result"? If the PCA has been performed in order to simplify and inspect the data structure, how can one notice that the results are not reliable?
Comment: Mentioning "relible" simply nods towards "representative sample" theme. Mathematically one has error-free regression line with 2 variables and 2 points (individuals). But what if one of the latter two is outlier. No, let us have as many individuals as we can collect, to balance atypical deviates. With your correlation matrix, you just will want to be sure that high correlations in it are significant (reliable).
Answer: I do not think that you would get any useful information from such an analysis, as lore in my subject area (psychology) suggests a 10;1 ratio in favour of n as a precondition. In some circumstances (where communalities are high) you can get away with 5 or 3 to 1, but a ratio of less than 1 is probably a recipe for disaster.
Comment: @ils well, i know that R will not allow you to fit this model. I got the numbers from Tabachnick & Fidell, Understanding Multivariate Statistics, and a closer look at these assumptions from MacCallum et al http://notendur.hi.is/adg11/Proffraedi/Fabriger__Wegener__MacCallum_og_Strahan_(1999).pdf
Comment: Thank you very much for the quick response! Could you briefly elaborate what the consequences of such an "disaster" would be? A PCA could be done on such a matrix anyway, some hints about the potential problems will be welcome.
Comment: As I have already received some hints from @ttnphns concerning the reliability problems that might occur, could you point me at some references that treat the problem and suggest the ration you mentioned?
Answer: Matrix dimension by itself have little todo with PCA validity. What will change is the interpretation of your data and it's all dependent on how you want to use the result.
PCA is very powerful to use to find anomalys or outliers in your data. Maybe you have performed an experiment on two different days, used different machines in the experiment etc. If the purpose is to get an overview of data PCA is one of the most efficient way to do that regardless of any n/m ratios.
If your main interest is to investigate clusters or relations between samples, then #variables are not very important. (But other type of statistics on the result might be important if #samples are low).
If you look at individual variables, then they will be less reliable if you have few samples. However, this is a problem you will have with any other method as well. If you find patterns among variables that make sense then you should certainly not disregard your findings because you have a low n/m ratio. However, few observations are almost allways problematic and should lead to caution in interpretation and the more samples you have the less important is the #sample/#variable relation.


Error when pull data from dictionary and path-combine in pandas

Question: I tried to pull data from 3 cities. How can I read all 3 city data instead of reading one by one below? Do I have duplicated code for reading data below? How to read data from dictionary to avoid the error? Thanks so much.
import csv
with open('C:\\Users\\jasch\\chicago.csv') as chicago_data:
    csvReader = csv.reader(chicago_data)

import csv
with open('C:\\Users\\jasch\\new_york_city.csv') as new_york_data:
    csvReader = csv.reader(new_york_data)

import csv
with open('C:\\Users\\jasch\\washington.csv') as washington_data:
    csvReader = csv.reader(washington_data)

import time
import pandas as pd
import numpy as np

CITY_DATA = { 'chicago': 'chicago.csv',
              'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }

df = pd.read_csv(CITY_DATA[city])

df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
print (df['month'])

NameError                                 Traceback (most recent call last)
<ipython-input-16-b1588646f194> in <module>()
      7               'washington': 'washington.csv' }
      8
----> 9 df = pd.read_csv(CITY_DATA[city])
     10
     11 df['Start Time'] = pd.to_datetime(df['Start Time'])

NameError: name 'city' is not defined

3. csv files of city data have almost the same column names below.
     Start Time             End Time  Trip Duration  \
0  2017-05-29 18:36:27  2017-05-29 18:49:27            780
1  2017-06-12 19:00:33  2017-06-12 19:24:22           1429
2  2017-02-13 17:02:02  2017-02-13 17:20:10           1088
3  2017-04-24 18:39:45  2017-04-24 18:54:59            914
4  2017-01-26 15:36:07  2017-01-26 15:43:21            434

              Start Station                          End Station  \
0     Columbus Dr & Randolph St                 Federal St & Polk St
1        Kingsbury St & Erie St  Orleans St & Merchandise Mart Plaza
2         Canal St & Madison St              Paulina Ave & North Ave
3  Spaulding Ave & Armitage Ave       California Ave & Milwaukee Ave
4        Clark St & Randolph St         Financial Pl & Congress Pkwy

    User Type  Gender  Birth Year
0  Subscriber    Male      1991.0
1    Customer     NaN         NaN
2  Subscriber  Female      1982.0
3  Subscriber    Male      1966.0
4  Subscriber  Female      1983.0

Answer: I think you don't need to go through all the trouble of reading in files with the csv module first. You are also re-assigning csvReader two times, so the first two files (Chicago and New York) are not referred to by anything after you are done reading in csv files.
Below is the pandas way of reading in multiple files and combining them into one file:
import pandas as pd
import os

city_data_files = ['C:\\Users\\jasch\\chicago.csv','C:\\Users\\jasch\\new_york_city.csv', 'C:\\Users\\jasch\\washington.csv']

In this line below, we are looping through the list of file paths and creating a DataFrame for each one, leaving us with a list of DataFrames. Additionally we are using the .assign() method to add a column with the filename. We do this so after combining the DataFrames together we can still tell apart which row came from which file.
dfs = [
       pd.read_csv(city_data_file, parse_dates=['Start Time'])\
       .assign(filename=os.path.basename(city_data_file))
       for city_data_file in city_data_files
       ]

Now we can go ahead and combine all the DataFrames into one DataFrame.
df = pd.concat(dfs) # this line combines the contents of the files
df['month'] = df['Start Time'].dt.month

As for your error - the stack trace is telling you exactly what the problem is:
----> 9 df = pd.read_csv(CITY_DATA[city])
NameError: name 'city' is not defined

You are using the variable city but have never defined it anywhere in your code.


Imagem quebra o título

Question: Tenho uma imagem e embaixo dela tenho um título, ao lado tenho três bloco.
Segue a imagem:

Mas quando eu adiciono apenas uma linha de título, ele quebra, a imagem acaba descendo.

Queria deixar a imagem todas iguais com uma linha ou com duas linhas, elas não se movesse, como na primeira imagem?
HTML

Performance em CSS - BrazilJS 2012 DUAS LINHAS

            Link da palestra:
            Duração:10:20
            Palestrante:Paul Ishid
             Assista agora

Performance em CSS - BrazilJS 2012

            Link da palestra:
            Duração:10:20
            Palestrante:Paul Ishid
             Assista agora

Performance em CSS - BrazilJS 2012 DUAS LINHAS

            Link da palestra:
            Duração:10:20
            Palestrante:Paul Ishid
             Assista agora

CSS
.lectures {
  width: 300px;
  overflow: hidden;
  margin: 20px;
  padding-right: 22px;
  font-family: 'Aleo';
  display: inline-block;
  position: relative; }
  .lectures:before {
    content: '';
    position: absolute;
    border-right: 1px solid #DADADA;
    position: absolute;
    height: 60%;
    right: 0;
    top: 50px; }
  .lectures img {
    width: 280px;
    height: 150px;
    display: block;
    margin: 0 auto;
    border-radius: 5px; }
  .lectures .lectures-title {
    text-align: center;
    font-size: 16px;
    font-family: helvetica;
    padding-bottom: 7px;
    margin: 5px; }
    .lectures .lectures-title a {
      color: #D90452; }
  .lectures .lectures-about {
    display: block;
    padding: 0 0 10px 10px;
    font-family: 'helvetica';
    font-size: 12px;
    color: #f2d750;
    padding-top: 7px;
    background: #333;
    margin-top: 10px;
    border-radius: 10px;
    background: #8e7300; }
  .lectures strong {
    padding-left: 5px;
    color: #F2F2F2; }
  .lectures h3 {
    height: 50px;
  }

.watch {
  display: block;
  text-align: center; }
  .watch a {
    background: #f2d750;
    color: #D90452;
    border-bottom: 4px solid #8e7300;
    border-radius: 10px;
    font-size: 20px;
    padding: 10px;
    display: block;
    width: 70%;
    margin: 10px auto; }

http://codepen.io/Andersonn/pen/KCxyr
Answer: 1) Solução
Foi adicionado:
.lectures h3 {
    height: 50px;
  }

No código Css completo:
.lectures {
  width: 300px;
  overflow: hidden;
  margin: 20px;
  padding-right: 22px;
  font-family: 'Aleo';
  display: inline-block;
  position: relative; }
  .lectures:before {
    content: '';
    position: absolute;
    border-right: 1px solid #DADADA;
    position: absolute;
    height: 60%;
    right: 0;
    top: 50px; }
  .lectures img {
    width: 280px;
    height: 150px;
    display: block;
    margin: 0 auto;
    border-radius: 5px; }
  .lectures .lectures-title {
    text-align: center;
    font-size: 16px;
    font-family: helvetica;
    padding-bottom: 7px;
    margin: 5px; }
    .lectures .lectures-title a {
      color: #D90452; }
  .lectures .lectures-about {
    display: block;
    padding: 0 0 10px 10px;
    font-family: 'helvetica';
    font-size: 12px;
    color: #f2d750;
    padding-top: 7px;
    background: #333;
    margin-top: 10px;
    border-radius: 10px;
    background: #8e7300; }
  .lectures strong {
    padding-left: 5px;
    color: #F2F2F2; }
  .lectures h3 {
    height: 50px;
  }

.watch {
  display: block;
  text-align: center; }
  .watch a {
    background: #f2d750;
    color: #D90452;
    border-bottom: 4px solid #8e7300;
    border-radius: 10px;
    font-size: 20px;
    padding: 10px;
    display: block;
    width: 70%;
    margin: 10px auto; }

2) Solução:
Foi adicionado height: 50px em .lectures .lectures-title
.lectures .lectures-title {
        text-align: center;
        font-size: 16px;
        font-family: helvetica;
        padding-bottom: 7px;
        margin: 5px; height: 50px;}

No Código Css Completo
.lectures {
  width: 300px;
  overflow: hidden;
  margin: 20px;
  padding-right: 22px;
  font-family: 'Aleo';
  display: inline-block;
  position: relative; }
  .lectures:before {
    content: '';
    position: absolute;
    border-right: 1px solid #DADADA;
    position: absolute;
    height: 60%;
    right: 0;
    top: 50px; }
  .lectures img {
    width: 280px;
    height: 150px;
    display: block;
    margin: 0 auto;
    border-radius: 5px; }
  .lectures .lectures-title {
    text-align: center;
    font-size: 16px;
    font-family: helvetica;
    padding-bottom: 7px;
    margin: 5px; height: 50px;}
    .lectures .lectures-title a {
      color: #D90452; }
  .lectures .lectures-about {
    display: block;
    padding: 0 0 10px 10px;
    font-family: 'helvetica';
    font-size: 12px;
    color: #f2d750;
    padding-top: 7px;
    background: #333;
    margin-top: 10px;
    border-radius: 10px;
    background: #8e7300; }
  .lectures strong {
    padding-left: 5px;
    color: #F2F2F2; }

.watch {
  display: block;
  text-align: center; }
  .watch a {
    background: #f2d750;
    color: #D90452;
    border-bottom: 4px solid #8e7300;
    border-radius: 10px;
    font-size: 20px;
    padding: 10px;
    display: block;
    width: 70%;
    margin: 10px auto; }

Exemplo Online: CodePen
Comment: Muito bom! Estava martelando aqui a cabeça pra tentar achar, Obrigado @Maria
Comment: @bfavaretto esse foi meu primeiro comentário sem ver nada, mas, o que acontece ele tem mais itens abaixo igual está no CodePen dá uma olhada: http://codepen.io/anon/pen/pBlef
Comment: Outra possibilidade é mexer no `vertical-align`.
Comment: Ah, agora entendi.

Imagem quebra o título


Java detect circular references during custom cloning

Question: I am writing a custom clone method for each entity. for deep copy is there a way to detect circular references or do I have to manually figure it out and restrict cloning to be unidirectional instead of bidirectional.
For example we use hibernate an hence a User object has a reference to Address and Address has a reference to User. Trying to see if doing a deep copy of Address as well as User is possible without running into circular reference issues
Comment: To handle circular references an IdentityMap can be used. This keep track of every object it find and when you serialize or copy data you can use this to ensure you handle repeated objects correctly. e.g. you might just have the same object many times in a structure and you don't want to turn these into different objects.
Answer: To implement this, you need a Map of references to already cloned objects. We implemented deep clone something like this:
In our entity base class:
<code>public void deepClone() {
    Map<EntityBase,EntityBase> alreadyCloned =
        new IdentityHashMap<EntityBase,EntityBase>();
    return deepClone(this,alreadyCloned);
}

private static EntityBase deepClone(EntityBase entity,
                                    Map<EntityBase,EntityBase> alreadyCloned) {
    EntityBase clone = alreadyCloned.get(entity);
    if( clone != null ) {
        return alreadyClonedEntity;
    }
    clone = newInstance(entity.getClass);
    alreadyCloned.put(this,clone);
    // fill clone's attributes from original entity. Call
    // deepClone(entity,alreadyCloned)
    // recursively for each entity valued object.
    ...
}
</code>
Comment: HashMap is a terrible idea to use in such a case (both can be bogus and it's slow). IdentityHashMap is a lot better.
Comment: +1 Great comment. Updated my answer and fixed my own code :) But I have to admit that HashMap is not slow. IMHO it is unbelievable fast.
Comment: The difference in slowness between HashMap and IdentityHashMap depends on the .hashCode and .equals implementations of the keys. If these are bad, HashMap gets slow (and in this algorithm you may get wrong results, like merging different objects because they are equal).
Comment: @Daniel, allocation on put and tree alike structure is a high (and unnecessary) price to pay for a hash table. You can have totally lock-free (concurrent) hashmap w/o allocation on put. Btw. IdentityHashMap (on top of not using `Object.hashCode` which is a relatevely slow virtual call) uses linear-probe internal structure which beats the tree alike one of HashMap in every possible way.
Comment: Your code will not work in the following situation where an Address has a user object as well as a createby user object and modified by user object.
Comment: Is there sth. wrong, you return a variable, that is no where declared? return alreadyClonedEntity;
Answer: @Daniel: Thank you very much for this great answer!
I just used your code and modified it a little based on my needs which makes it easier to use with subclasses. Maybe someone else is interested in that as well so here is my code for the base class:
<code>/**
 * Perform a deep clone.
 *
 * @return Deep Clone.
 * @throws CloneNotSupportedException
 */
@SuppressWarnings("unchecked")
public VersionedEntityImpl deepClone() throws CloneNotSupportedException {
    Map<VersionedEntityImpl, VersionedEntityImpl> alreadyCloned = new IdentityHashMap<VersionedEntityImpl, VersionedEntityImpl>();
    return deepClone(this, alreadyCloned);
}

/**
 * Perform a deep clone.
 *
 * @param entity
 * @param alreadyCloned
 * @return Deep Clone.
 * @throws CloneNotSupportedException
 */
@SuppressWarnings("unchecked")
protected VersionedEntityImpl deepClone(VersionedEntityImpl entity,
        Map<VersionedEntityImpl, VersionedEntityImpl> alreadyCloned) throws CloneNotSupportedException {
    if (entity != null) {
        VersionedEntityImpl clone = alreadyCloned.get(entity);
        if (clone != null) {
            return clone;
        }
        clone = entity.clone();
        alreadyCloned.put(entity, clone);
        return entity.deepCloneEntity(clone, alreadyCloned);
    }
    return null;
}

/**
 * Method performing a deep clone of an entity (circles are eliminated automatically). Calls
 * deepClone(entity,alreadyCloned) recursively for each entity valued object.
 *
 * @param clone
 * @param alreadyCloned
 * @return clone
 * @throws CloneNotSupportedException
 */
protected abstract VersionedEntityImpl deepCloneEntity(VersionedEntityImpl clone,
        Map<VersionedEntityImpl, VersionedEntityImpl> alreadyCloned) throws CloneNotSupportedException;
</code>
What to put into the subclasses:
<code>@SuppressWarnings("unchecked")
@Override
protected VersionedEntityImpl deepCloneEntity(VersionedEntityImpl clone,
        Map<VersionedEntityImpl, VersionedEntityImpl> alreadyCloned) throws CloneNotSupportedException {
    // fill clone's attributes from original entity. Call
    // deepClone(entity,alreadyCloned)
    // recursively for each entity valued object.
    if (this.associatedItems != null) {
        List<SomeClass> listClone = new LinkedList<SomeClass>();
        for (SomeClass someClass: this.associatedItems) {
            listClone.add((SomeClass) super.deepClone(someClass, alreadyCloned));
        }
        ((SomeOtherClass) clone).setAssociatedItems(listClone);
    }
    ((SomeOtherClass) clone).setYetAnotherItem((YetAnotherClass) super.deepClone(this.yai, alreadyCloned));

    return clone;
}
</code>
It is not perfect as of yet but it gets the job done nicely for now :)


Understanding the definition of omnibus tests

Question: From Wikipedia

Omnibus tests ... test whether the explained variance in a set of
  data is significantly greater than the unexplained variance,
  overall.
...
Omnibus test as a statistical test is implemented on an overall
  hypothesis that tends to find general significance between parameters'
  variance, while examining parameters of the same type, such as:
  Hypotheses regarding equality vs. inequality between k expectancies
  $µ_1=µ_2=…=µ_k$ vs. $µ_1≠µ_2≠...≠ µ_k$ in Analysis Of Variance(ANOVA)
  ;

I was wondering what it means by a variance  being explained or unexplained?
How shall I understand what an Omnibus test is?
What is a set that is not omnibus?
Thanks and regards!

Added: I was wondering if the following likelihood ratio test for the global null is an omnibus test, quoted from Casella and Berger's Statistical Inference?

...
Answer: I wouldn't look for a rigorous definition of omnibus test. It seems typically used for overall tests with wide scope, packing several tests into one.
Other terms used with similar import are portmanteau statistic and factotum statistic.
Over a century or more, there have been all sorts of fashions over terminology, including statisticians reaching for their Latin and Greek (ancillary, histogram, chi-square, heteroscedasticity), statisticians reaching for their thesaurus (as here), statisticians naming tests after their teachers or friends, ideally in pairs (Mann-Whitney, Kruskal-Wallis), and statisticians eager to show off their homespun sides (jackknife, bootstrap). Even the words that look familiar had to be invented (average, mode, regression).
Comment: Count the equals signs, sometimes. The more there are, the more omnibus-like. However, I guess scope is the important thing. But I don't think there is consistency on this. Often names, as here, are just sticky labels: you can peel them off, or they drop off, and nothing's different underneath. I don't think there's an idea lurking there except that of an overarching test. You might find a definition lurking somewhere. This is just my impression: corrections and rebuttals may follow.
Comment: Thanks! How can I tell if a test is omnibus or not?
Comment: Is an omnibus test contrasted to multiple comparisons?
Comment: Can be. Depends what you mean by multiple comparisons. Do you mean comparing individual means after anova (classical, narrow sense) or any post hoc specific comparison once a model is fitted? I don't see that the idea is confined to anova or linear models set-ups. If you want some definitions, you may need to define some terms yourself first.
Comment: I saw omnibus test when reading about [multiple comparisons](https://en.wikipedia.org/wiki/Multiple_comparisons). The link has what multiple comparisons is trying to do.
Comment: No, it is the Wikipedia article on multiple comparisons. It seems to range from very clear and reasonable statements to unwarranted emphasis on what follows anova, but I have only skimmed it.
Answer:
I was wondering what it means by a variance being explained or
  unexplained?

It the context of ANOVA it means the variance "explained" by group membership and the variance that remains unexplained.  To understand this in detail you have to really look at the equations.  I'll try to explain it anyway without introducing too many equations.  In the case of a one-way ANOVA each value observed can be thought of as being composed of three sources of variance, the grand mean, the group mean deviation from the grand mean, and error... $x = \bar{\bar{x}} + (\bar{\bar{x}} - \bar{x}_k) + e$.  If you assume there are no group differences then all $\bar{x}_k = \bar{\bar{x}}$ therefore, by estimating $\bar{x}_k$ you haven't 'explained' very little or no extra variance.  Imagine instead that the null hypothesis is false and you go ahead and estimated the deviations of the group means from the grand means.  If you then adjust each score by the deviation of the group to which it belongs and then recalculated the variance of the scores, you will find that the variance is smaller than it was before.  That reduction in variance is the variance that you 'explained' by estimating means for each group.

How shall I understand what an omnibus test is?

Tests are referred to as omnibus if after rejecting the null hypothesis you do not know where the differences assessed by the statistical test are.  In the case of F tests they are omnibus when there is more than one df in the numerator (3 or more groups) it is omnibus.  In the case of Chi-square tests, when there is more than one df it is omnibus.

What is a set that is not omnibus?

Comparisons between two groups such as those that happen in the cases detailed above F with 1 df in the numerator and Chi Square with 1 df.
Comment: To be honest my eyes start to glaze over when I see that much greek notation, especially if I haven't eased into getting used to whatever specific notation conventions the author is using.  The title of the test itself certainly sounds omnibus.
Comment: Thanks, Russell!  In [Casella and Berger's Statistical Inference](http://i.stack.imgur.com/xMBk7.png), is the likelihood ratio test for the global null an omnibus test?
Comment: I did a quick google search and it looks like this procedure is used to test an overall logistic regression model or to compare two models.  As before, it should yield an F or Chi-square test statistic.  The rules mentioned above still hold.  If the df is > 1 then you are testing one or more comparisons units of interest (in anova this would be $\bar{x}_1 = \bar{\bar{x}}, \bar{x}_2 = \bar{\bar{x}}, ..., \bar{x}_k = \bar{\bar{x}}$ and in the regression framework it is $b_0 = 0, b_1 = 0, ..., b_k = 0$.
Comment: Thanks, Russell! I added more context to the quote, and hope that it may be clearer. It is a general approach, since it only involves likelihood ratio test (LRT) and Union-intersection test (UIT).
Comment: I posted it as [a new question](http://stats.stackexchange.com/questions/59941/is-the-likelihood-ratio-test-for-the-global-null-considered-to-be-an-omnibus-tes).


Are there any standardized single-letter names for the flats and sharps?

Question: The white keys on the piano have single letter names:

C, D, E, F, G, A, B

The black keys require a minimum of 2 letters to "spell" their names :

Db, Eb, Gb, Ab, Bb

or

C#, D#, F#, G#, A#

Is anybody aware of any common single-letter names for the black notes?  I have been playing around with using

H, I, J, K, L

But I don't love it and thought I'd see if anybody knew of a convention that already exists.
Comment: Whilst it does not answer your question, be aware that there are good reasons for using the sharp/flat notation. Using different names will convey less information. And also mean that no one else understands you.
Comment: German nomenclature calls the B "H", and the B flat "B" - but that's only one of the five.
Comment: Actually, Shostakovich did the same when adopting his own musical sigil "D S C H": German for "E flat" is "Es", which has two letters but *sounds* exactly like "S".
Comment: @freddyz Yes that's what I'm saying.
Comment: Following what @endorph said it's also worth remembering that on many instruments these notes are not the same. F# is the same as Gb on a piano but not, for example, on a violin.
Comment: @KilianFoth and thus the reason Bach could write an invention (I believe, possibly a fugue) using the letters of his name :-)
Comment: @JimM so are you saying that on a violin, F# and Gb will have different pitch?
Comment: Related [question](https://music.stackexchange.com/q/23976/2600).
Answer: Not using letter names, but in set theory instead of giving out letter names to the 12 pitches they are just enumerated typically starting at C as such:

C  C#/Db  D  D#/Eb  E    F  F#/Gb  G  G#/Ab  A  A#/Bb  B
0    1    2    3    4    5    6    7    8    9   10   11

This allows a much easier path to do calculations and look at reoccurring ideas in a 12-tone equal temperament system where enharmonic notes correspond to the exact same frequency.
Comment: @Dancia The notation you mention is very close to the standard, except that T and E are most typically used for 10 and 11, rather than A and B.
Comment: It is unfortunate that whoever invented this system called it "set theory," as it has just about nothing to do with mathematical Set Theory.
Comment: 10 and 11 both are still made of two symbols (1 and 0, 1 and 1). OP is in search of `common single-letter`/symbol. If you count not in base 10, but in 16 (hexadecimal), it could be `0 1 2 3 4 5 6 7 8 9 A B`, but I don't think its common.
Comment: Well, sorta... once you include operations it gets closer to a ring :-)
Comment: @CarlWitthoft it kind of does when you actually look at analysis
Comment: I think in this context, "set theory" is better described as "modular arithmetic"
Comment: @CarlWitthoft In fact, mathematical set theory, as well as number theory, group theory, and category theory, are all integral parts of modern music theory. You can find numerous articles, for example, in the journal Perspectives of New Music.
Comment: @Dancia  try 0, 1, 2, ..., 7, 8 , 9, B, H
Answer: Perhaps the German names may be helpful. While not a single letter name, these are single syllable names and thus easy to sing. Using these is at least semi-standard.
https://www.library.yale.edu/cataloging/music/keylang.htm
There is the possibility of using a chromatic do-re-mi system. https://en.wikipedia.org/wiki/Solf%C3%A8ge
The latter two systems do map more than one name to a single note.
Comment: +1 for the (chromatic) movable Do where one-syllable names are given to notes raised or lowered by a semitone
Comment: Yale link is dead.
Answer: Not that I'm aware of. The whole point is that being called a # or b actually gives information out. If you know some theory, it can explain what is happening when accidentals are used, and if they were different letter names, then key sigs would be tricky, I think. There actually is already 'H', in Germany and other countries, used for B - Bb being called B. Now how confusing is that? And once you start adding Doh - both fixed and moveable- into the equation, it's possibly best to let sleeping dogs lie...
Comment: 'H' as in [BACH](https://en.wikipedia.org/wiki/BACH_motif).
Answer: The closest thing to this was Boethius in the 6th century. He tried to use the system you mention and just went through the alphabet.
But his system didn't have sharps and flats, just the note names. When accidentals were first introduced, on the note B, they used a rounded "b" for the flat, and a boxed "b", (#) for the sharp.
So, no, the notes have always been referred to with the two characters.
Comment: Wouldn't that be a natural, not a sharp?
Answer: As far as written systems go, the closest you'll get to a single-character notation for the entire chromatic scale is the numeric system in Dom's answer, generally notated as 0 1 2 3 4 5 6 7 8 9 T E.
For spoken letter-names incorporating a single syllable, the most common system I've encountered is adding "-sh" for sharps and "-f" for flats. Thus:
C Ceesh D Deesh E (Eesh) F Feesh G Geesh A Aysh B (Beesh)
and
C (Ceef) B Beef A Ayf G Geef F (Feef) E Eef D Deef
Answer: I'm finding this problem when learning the bass. The syllable of "flat" just gets in the way and interrupts any flow I have. I've taken to just adding an "eef" when I'm saying the notes I'm playing to myself, this keeps the info and makes the sound concise.
A Aeef B C Ceef D Deef E F Feef G Geef.
Works for me anyhow.
Answer: I call this PƏÆTK-BEADG-CF system (circle of fourths/counter-clockwise) and GDAEB-KTÆƏP-FC system (circle of fifths/clockwise) (I just use dashes to group those patterns into chunks). The note names are based on the circle of fifths/fourths - and the occuring pattern: BEADG (circle of fourth/counter-clockwise pattern) - and the counterpart flat note names influenced by IPA/International Phonetic Alphabet.
How did I come to this solution?
As you may know, the notes in circle of fourths in flats are (starting from Bb):
Bb Eb Ab Db Gb B E A D G C F
or the same in sharps:
A# D# G# C# F# B E A D G C F
Immediately one can see the common ground between the sequences of flat notes and natural notes:

Bb Eb Ab Db Gb
B  E  A  D  G

So what I've done is I have taken those flat notes and assigned them new close phonemes (influenced by IPA/International Phonetic Alphabet):

Bb = P (voiceless counterpart letter of B)
Eb = Ə (pronounced [ə], as in words "a" [ə] or "the" [ðə], particularly derived from English word "the")
Ab = Æ (pronounced [æ], as in words "and" [ænd] or "man" [mæn])
Db = T (voiceless counterpart letter of D)
Gb = K (voiceless counterpart letter of G)

So the note letters starting from C, are:
C T D Ə E F K G Æ A P B
The circle of fourths (going counter-clockwise in the circle of fifths) are in my system (starting from P):
P Ə Æ T K B E A D G C F (PƏÆTK-BEADG-CF)
And the circle of fifths (going clockwise in the circle of fifths) are in my system (starting from G):
G D A E B K T Æ Ə P F C (GDAEB-KTÆƏP-FC)
The system helps to immediately to find the notes in a guitar.
Circle of 4ths. In a standard E tuned guitar, one can easily find those patterns (using my PƏÆTK-BEADG-CF notation system). Counting the notes per fret, starting from the 6th string, just remember to step one fret to left at the 2nd string:

E|  F  K  G  Æ  A  P  B [C] T  D  Ə  E  F  K  G  Æ  A  P [B] C  T  D  Ə  E
B|  C  T  D  Ə  E  F  K [G] Æ  A  P  B  C  T  D  Ə  E  F [K] G  Æ  A  P  B
G|  Æ  A  P  B  C  T [D] Ə  E  F  K  G  Æ  A  P  B  C [T] D  Ə  E  F  K  G
D|  Ə  E  F  K  G  Æ [A] P  B  C  T  D  Ə  E  F  K  G [Æ] A  P  B  C  T  D
A|  P  B  C  T  D  Ə [E] F  K  G  Æ  A  P  B  C  T  D [Ə] E  F  K  G  Æ  A
E|  F  K  G  Æ  A  P [B] C  T  D  Ə  E  F  K  G  Æ  A [P] B  C  T  D  Ə  E

Figuring out only one fret-full of notes. The notes are the same on 1st string and 6th string. Imagine that there is a 7th string. Count one forward from the 1st string/6th string with GDAEB-KTÆƏP-FC and you'll get the correct note for the 2nd string:

E|  F  K  G  Æ  A  P [B] C  T  D  Ə  E  F  K  G  Æ  A  P  B  C  T  D  Ə  E
B|  C  T  D  Ə  E  F [K] G  Æ  A  P  B  C  T  D  Ə  E  F  K  G  Æ  A  P  B
G|  Æ  A  P  B  C  T [D] Ə  E  F  K  G  Æ  A  P  B  C  T  D  Ə  E  F  K  G
D|  Ə  E  F  K  G  Æ [A] P  B  C  T  D  Ə  E  F  K  G  Æ  A  P  B  C  T  D
A|  P  B  C  T  D  Ə [E] F  K  G  Æ  A  P  B  C  T  D  Ə  E  F  K  G  Æ  A
E|  F  K  G  Æ  A  P [B] C  T  D  Ə  E  F  K  G  Æ  A  P  B  C  T  D  Ə  E
B|                   (K)

Circle of 5ths. Again, count with GDAEB-KTÆƏP-FC, all way up from the 6th string to the 1st string, remember the one fret jump on the 2nd string:

E|  F  K  G  Æ  A  P  B  C  T  D  Ə  E  F [K] G  Æ  A  P  B  C  T  D  Ə  E
B|  C  T  D  Ə  E  F  K  G  Æ  A  P [B] C  T  D  Ə  E  F  K  G  Æ  A  P  B
G|  Æ  A  P  B  C  T  D  Ə [E] F  K  G  Æ  A  P  B  C  T  D  Ə  E  F  K  G
D|  Ə  E  F  K  G  Æ [A] P  B  C  T  D  Ə  E  F  K  G  Æ  A  P  B  C  T  D
A|  P  B  C  T [D] Ə  E  F  K  G  Æ  A  P  B  C  T  D  Ə  E  F  K  G  Æ  A
E|  F  K [G] Æ  A  P  B  C  T  D  Ə  E  F  K  G  Æ  A  P  B  C  T  D  Ə  E

If one deliberately needs to determine whether it's a sharpened or flattened note, one could go with those previous suggestions of adding -eesh (sharp) and -eef (flat) to the the notes (-eesh/-eef only determine whether it's a flattened note or sharpened note, those names, -eesh/-eef, do not themselves flatten or sharpen the notes in this system, as there are already the names T Ə K Æ P for flattened/sharpened/black notes):
C# = Teesh, D# = Əeesh, F# = Keesh, G# = Æeesh, A# = Peesh
Db = Teef, Eb = Əeef, Gb = Keef, Ab = Æeef, Bb = Peef
NOTE: There is also similarities between sharp notes and the natural notes:
A# D# G# C# F#
A  D  G  C  F
But I'd rather go with the flat note based system, PƏÆTK-BEADG-CF. BEADG (mnemonic: "bead-G" or "bitchy") or BEADG-CF (mnemonic: "bitchy cipher") is also pronounced more easily and more easily remembered than ADGCF.
Comment: Wow! Are you sure you didn't mean to post this on the [Conlang stack](https://conlang.stackexchange.com/)?


java - check If a String contains all characters of another String, but not in order

Question: I need a Method that takes all the characters of a String and checks if those characters are in another String.
The Method I have:
public boolean isItemUsable2(String word1, String word2) {
        int count = 0;
        for (int i = 0; i < word2.length(); i++) {
            String itemPiece = Character.toString(word2.charAt(i));
            if (word1.contains(itemPiece)) {
                count++;
            }
        }
        return count == word2.length();
    }

The problem is, for example word 1 is "12345++" and word 2 is "155" it should say it's false since there is only one 5, but it shows true and I don't know how to fix it.
Comment: you'd need to "remember" that you already looked for a `5`, and where you found it. Then, when you look for the 2nd `5`, it should be after the first `5`. I recommend looking at [`Map`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Map.html), [`String.indexOf(char)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#indexOf(int)) and [`String.indexOf(char, int)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#indexOf(int,int)).
Comment: Alternatively, you can check [this question](https://stackoverflow.com/q/6712587/10819573). Once you create the frequency maps of the two strings, you can easily check what you want.
Answer: You can solve this problem by using a List of characters for the search word. Attempt to remove each test character from the list. If it is successfully removed, you know word1 contained the character while simultaneously preventing it from being checked again.
public static boolean isItemUsable2(String word1, String word2)
{
    final List<Character> word1Chars = new ArrayList<>();
    for (char aChar : word1.toCharArray())
        word1Chars.add(aChar);
    boolean usable = !word2.isEmpty();
    for (int i = 0; i < word2.length() && usable; i++)
    {
        usable = word1Chars.remove((Character) word2.charAt(i));
    }
    return usable;
}

Answer: I would use regex.  This isn't the most efficient way to do it, but it will work
public static boolean isItemUsable2(String a, String b) {
    Map<Character, Integer> map = new HashMap<>();
    for (char c : b.toCharArray()) {
        map.merge(c, 1, (k,v) -> v + 1);
    }

    for (Entry<Character, Integer> entry : map.entrySet()) {
        Pattern pattern = Pattern.compile(Pattern.quote(entry.getKey().toString()) + "{" + entry.getValue() + "}");
        if (!pattern.matcher(a).find()) {
            return false;
        }
    }
    return true;
}


Why isnt else if statement working?

Question: JavaScript
function AdultNumber(){              /* Ticket Number Validation   */
    var AdInput = $("#adult").val();

    if (AdInput > 0 ){
        document.getElementById("AdTickError").textContent = "";
        return true;

    } else if( AdInput > 20) {
        confirm("You sure you want 20+ Passengers?");
        return true;
    } else {
        document.getElementById("AdTickError").textContent = "Incorrect Enter Correct Number Of Passengers";
        return false;
    }
}

HTML:
Adults(+16)
    <input type="number" id="adult" name="user_adult">

Why does it not display confirm box if user inputs over 20? I want it that if user chooses 20 or over an confirm box prompts asking user if they want to continue.
Comment: One issue is that it will always hit the first if statement because anything greater than 20 is also greater than 0.  So it won't enter the else if statement.
Comment: i know it sounds crazy, but could it be the work of other wordly beings?
Comment: do you ever call the function AdultNumber?
Answer: You may want to change this condition:
if (AdInput > 0 )
to this:
if (AdInput > 0 && AdInput <= 20){
Answer: Values retrieved from DOM elements are always treated as strings. You need to say:
var AdInput = parseFloat($("#adult").val());

Or, depending on your needs, you may wanna use parseInt() instead of parseFloat() to get an integer not a float.
Comment: There is no "need" to  do this. The relational comparison operator (`>`) will implicitly convert the value to number anyway.
Comment: Not true, the comparison operator will treat the number as a string and will compare their lengths.
Comment: Y2H is right. Felix King you must be new to JS.
Comment: @Anarakanitach: You guys are joking right? Since when does the `>` compare the **length** of a string? If any, it compares the strings based on the lexicographical order. E.g. `"ab" < "b"` is `true`. According to you it should be `false`, since `"ab"` is "longer". However if you are comparing a number and a string, then the string is converted to a number. Example: `100 < "20"` is `false`. Consequently, `"200" > 0` is the same as `200 > 0`. No explicit type conversion required. See the spec: http://www.ecma-international.org/ecma-262/6.0/#sec-abstract-relational-comparison
Comment: Maybe this is a better example to convince you: `"20" < "100"` is `false`, but `"20" < 100` (or `20 < "100")` is `true`. The issue with the OP's code is just the order of conditions, not the data type of the values.
Comment: I'm sorry Felix but I just tried the code myself and, for instance, "10" is neither greater than nor smaller than 20. However, "10" is greater than 0. I just tested these scenarios myself. Maybe tomorrow I'll start looking at the documentation regarding this part (if any exists).
Comment: Oh wait, OK my bad I'm so sorry I misspelled a number in my code. Apparently you were right after. Thanks for pushing me to figure this 1 out.

Why isnt else if statement working?


A/B Testing Proportions - baseline rate is close to 1

Question: I need a gut check here...
I'm trying to run an A/B test where the baseline metric is a conversion rate that is close to 1 - somewhere in the 80-85% range.
And so when I run my sample size calculation - i believe i'm just doing a Two Proportion Z-Test - the required sample size is very low, like a few thousand.
This doesn't make much sense to me intuitively? I know that if baseline rate is higher, the sample size will decrease just looking at the formula... but intuitively, I have a hard time understanding how we can gain significance by jut a few thousand samples.
We're working on ads, and a normal CTR ad campaign for us requires ~1M ads for sample size (where CTR is closer to 1%).
Other details: using power = 80%, alpha = 0.05, and an MDE (absolute) of 5% which I suppose is quite high that also contributes?
The reason I chose an MDE of 5% is because stakeholders have said we're ok observing an increase or decrease in the rate by 5% (absolute not relative)
Any thoughts? Should I be using a different calculation?
Answer: Every time I have a concern about a power calculation, I simulate it.
The function in R to compute the requisite sample size is power.prop.test.
``` r
p1 = 0.85
p2 = 1.05*0.85

N = ceiling(power.prop.test(p1=p1, p2=p2, power=0.8)$n)

N
#> [1] 974

Created on 2023-03-04 by the reprex package (v2.0.1)
Ok, that seems low.  Let's simulate it
sims = replicate(1000, {

  x = rbinom(2, N, c(p2, p1))
  test = prop.test(x, rep(N, 2))

  (test$p.value<0.05)
})

mean(sims)
> 0.778 # Depending on your random seed

So it looks like this sample size is fine.
Comment: thank you for the response. sorry can you clarify what you are doing in your 2nd block of code simulating, and how i should be thinking about your follow up statement? my company has obviously much more daily users to test on, so i feel a bit silly saying "we need 1000 users for this a/b test" which we can achieve in the span of 1 hour.... would i consider changing my MDE and power? is there a separate stat test i should be using?
Comment: 2nd block of code is repeatedly sampling two binomial random variables, one with probability of success `p2` and the other with probability of success `p1`.  Then, I run a test of proportions and determine how many times the null is rejected.  778 of the 1000 simulations reject the null, hence the power of the test when the sample size in each group is `N` is approximately 77.8%
Comment: How should you think about my follow up statement?  I had accidentally included a sentence I didn't mean to, so now things should be copacetic.
Comment: thank you very much. last question if you dont mind since you seem to be well informed on experimentation - how should i approach choosing the appropriate statistical test with A/B testing, aside from whether my metric is a proportion or continuous. for example, do i need to look at the distribution of the data and how would i do that? i apologize, im a fairly new grad and still learning analytics basics
Comment: @jc315 that's not really a question I can answer in the comments. I can say that if the randomization is successful and Reilly independent of all other factors, the type of outcome (e.g. continuous or binary) is all that matters.


Segmentation fault (core dumped) c

Question: URI 1463
Estou resolvendo o Exercício 1464 do URI (Link do Exercício), e tive o problema de "segmentation fault (core dumped)" e não consigo localizar a raíz do erro (sei que propriamente possa estar no realloc/malloc).
Segue abaixo o seguinte código do 1463 em cpp:
#include <iostream>
#include <string>
#include <queue>
using namespace std;

typedef struct no
{
    char info;
    struct no *left;
    struct no *right;
} Node;

typedef struct treeBin
{
    Node *root;
} treeBin;

string removeSpace(string input)
{
    string phrase;
    int cont, aux = 0;
    for (cont = 0; cont < input.length(); cont++)
    {
        if (input[cont] != ' ')
        {
            phrase.push_back(input[cont]);
        }
    }
    return phrase;
}

Node *createNode(string input, int first, int end)
{
    int cont = 0, cont_parent = 0, separator = 0;
    char carac = ' ';
    Node *node = (Node *)realloc(node, sizeof(Node));
    if (first == end)
    {
        node->right = NULL;
        node->left = NULL;
        node->info = input[first];
    }
    else
    {
        if ((input[first] == '(') && (input[end] == ')'))
        {
            node = createNode(input, first + 1, end - 1);
        }
        else
        {
            for (cont = first; cont <= end; cont++)
            {
                if (input[cont] == '(')
                {
                    cont_parent++;
                }
                else if (input[cont] == ')')
                {
                    cont_parent--;
                }
                else if (input[cont] == '+' || input[cont] == '-')
                {
                    if (cont_parent == 0)
                    {
                        separator = cont;
                        carac = input[cont];
                    }
                }
                else if (input[cont] == '/' || input[cont] == '*')
                {
                    if (cont_parent == 0 && (carac != '+' && carac != '-'))
                    {
                        separator = cont;
                        carac = input[cont];
                    }
                }
            }
            node->info = carac;
            node->left = createNode(input, first, separator - 1);
            node->right = createNode(input, separator + 1, end);
        }
    }
    return node;
}

void printLine(queue<Node *> row, int currentLevel)
{
    queue<Node *> aux;
    if (row.empty())
    {
        return;
    }
    else
    {
        cout << "Nivel " << currentLevel << ": ";
        while (!row.empty())
        {
            cout << row.front()->info;
            if (row.front()->left != NULL)
            {
                aux.push(row.front()->left);
            }
            if (row.front()->right != NULL)
            {
                aux.push(row.front()->right);
            }
            row.pop();
        }
        cout << endl;
        printLine(aux, currentLevel + 1);
    }
}

void printTree(treeBin *binTree)
{
    queue<Node *> aux;
    aux.push(binTree->root);
    printLine(aux, 0);
}

main()
{
    string input;
    treeBin *binTree = new treeBin;

    getline(cin, input);
    do
    {
        input = removeSpace(input);
        cout << input << endl;
        binTree->root = createNode(input, 0, input.length() - 1);
        printTree(binTree);
        getline(cin, input);
        if (!cin.eof())
            cout << endl;
    } while (!cin.eof());
    return 0;
}

Answer: Temos que entender que segmentation fault (core dumped) é um erro muito comum e dificil em tempo de execução, naturalmente todo programa é chamado de processo esse processo tem uma parte da memoria destinada para ele que é gerenciado pelo SO sistema operacional.
O que ocorre quando segmentation fault acontece é que seu PROCESSO ou seja seu programa está acessando a memoria de outro processo, como por exemplo quando acessamos um ponteiro NULL.
Eu dividi a solução em 3 etapas, 1: compilar a versão de debug, 2: usar o gdb para debugar.
1:g++ -g main.c -o main
a FLAG -g indica a versão de debug.
2:  gdb main
Primeiro lancei um break em main avancei linha por linha, avançando percebi que seu codigo deu problema na seguinte linha:
133: binTree->root = createNode(input, 0, input.length() - 1);
Entrando na função eu notei a seguinte linha:
36:    Node *node = (Node *)realloc(node, sizeof(Node));
Note que realloc só funciona para um ponteiro que já tenha sido alocado, tanto por new quanto por malloc ou calloc.
Corrigi sua linha por:    Node *node = new Node; // Alocando a memoria.
CODIGO CORRIGIDO:
#include <iostream>
#include <string>
#include <queue>
using namespace std;

typedef struct no
{
    char info;
    struct no *left;
    struct no *right;
} Node;

typedef struct treeBin
{
    Node *root;
} treeBin;

string removeSpace(string input)
{
    string phrase;
    int cont, aux = 0;
    for (cont = 0; cont < input.length(); cont++)
    {
        if (input[cont] != ' ')
        {
            phrase.push_back(input[cont]);
        }
    }
    return phrase;
}

Node *createNode(string input, int first, int end)
{
    int cont = 0, cont_parent = 0, separator = 0;
    char carac = ' ';
    Node *node = new Node; // CORRIGIDO
    // Node *node = (Node *)realloc(node, sizeof(Node)); ERRO
    if (first == end)
    {
        node->right = NULL;
        node->left = NULL;
        node->info = input[first];
    }
    else
    {
        if ((input[first] == '(') && (input[end] == ')'))
        {
            node = createNode(input, first + 1, end - 1);
        }
        else
        {
            for (cont = first; cont <= end; cont++)
            {
                if (input[cont] == '(')
                {
                    cont_parent++;
                }
                else if (input[cont] == ')')
                {
                    cont_parent--;
                }
                else if (input[cont] == '+' || input[cont] == '-')
                {
                    if (cont_parent == 0)
                    {
                        separator = cont;
                        carac = input[cont];
                    }
                }
                else if (input[cont] == '/' || input[cont] == '*')
                {
                    if (cont_parent == 0 && (carac != '+' && carac != '-'))
                    {
                        separator = cont;
                        carac = input[cont];
                    }
                }
            }
            node->info = carac;
            node->left = createNode(input, first, separator - 1);
            node->right = createNode(input, separator + 1, end);
        }
    }
    return node;
}

void printLine(queue<Node *> row, int currentLevel)
{
    queue<Node *> aux;
    if (row.empty())
    {
        return;
    }
    else
    {
        cout << "Nivel " << currentLevel << ": ";
        while (!row.empty())
        {
            cout << row.front()->info;
            if (row.front()->left != NULL)
            {
                aux.push(row.front()->left);
            }
            if (row.front()->right != NULL)
            {
                aux.push(row.front()->right);
            }
            row.pop();
        }
        cout << endl;
        printLine(aux, currentLevel + 1);
    }
}

void printTree(treeBin *binTree)
{
    queue<Node *> aux;
    aux.push(binTree->root);
    printLine(aux, 0);
}

main()
{
    string input;
    treeBin *binTree = new treeBin;

    getline(cin, input);
    do
    {
        input = removeSpace(input);
        cout << input << endl;
        binTree->root = createNode(input, 0, input.length() - 1);
        printTree(binTree);
        getline(cin, input);
        if (!cin.eof())
            cout << endl;
    } while (!cin.eof());
    return 0;
}

Comment: Estranho, o código funciona no g++ 8.1.0. com certeza tem algo haver com a versão do compilador usado.
Comment: Obrigado William, porém continua apresentando Segmentation Fault no Debugger e no URI, (na mesma linha `Node *node = new Node;`)

Segmentation fault (core dumped) c


Propriedade do Tablix no Report Builder 3.0

Question: Gostaria de saber se existe alguma propriedade no Tablix que me informe se o campo está no estado expanded ou collapsed?
Estou querendo exibir algumas informações em uma coluna apenas se o campo da esquerda estiver expandido. A ideia seria algo mais ou menos assim:
=IIF(Fields!DivisionT.Expanded = False, "", First(Fields!QtdeApr.Value))

Conhecem alguma maneira de fazer isso?
Answer: Descobri a maneira de fazer o que quero. Não preciso usar nenhum recurso de expressões, basta usar a propriedade de visibilidade do campo em questão.
Relembrando que: "Estou querendo exibir algumas informações em uma coluna apenas se o campo da esquerda estiver expandido." A solução é:

Clique com o botão direito do mouse no campo da direita (campo que deve aparecer apenas se...).
Selecione a propriedade Visibility
Selecione Hide
Marque a opção: "Display can be toggled by this report item:"
Na Combo Box abaixo dessa opção selecione o nome do campo da direita.

O resultado disso é que o campo da direita sempre iniciará oculto mas, quando o campo da esquerda for expandido, o da direita aparecerá.
Resultado obtido!


How to keep "active" css on menu item when clicking on other link on same page?

Question: I have an issue with my main menu.
When you click on the "Cases by Topic" menu item, you are taken to the "Cases by Topic" page. The "Cases by Topic" menu item is then given the css class "active". I set it up so if a menu item has "active" css it is dark blue, rather than light blue to indicate it is the current menu item.
The page it's self has a drupal block that has a bunch of taxonomy menu items. Each one of these taxonomy menu items also point to this page but will load a different set of information in the page (which is a drupal view).
When they click on a taxonomy link in the block it reloads the page, but then the "Cases by Topic" main menu item no longer has the "active" css class on it.
Here is a picture example:
The user clicks on the "Cases by Topic" main menu item and the page loads. At this point the "Cases by Topic" menu item has the 'active' css class.  The user then clicks on a taxonomy link in the drupal block ("Access to Information").

The same page reloads, but now the "active" css is on the taxonomy link and not the main menu "Cases by Topic" menu item.

I would really like to have the "active" css class stay on the "Cases by Topic" main menu item, even when people click the links in the taxonomy block.
At the very least I would not have the taxonomy link just clicked have "active" css and "Cases by Topic" should keep that css class.
Any ideas?
Answer: You could consider using jQuery client-side to set the class based on path. See this post on how to do that: http://www.itworld.com/article/2832973/development/setting-an-active-menu-item-based-on-the-current-url-with-jquery.html
or you could try using Menu Trail By Path module
https://www.drupal.org/project/menu_trail_by_path
Answer: Borrowed from here: This deals with hover, but you should be able to modify the principles to work for you. With this you could create css that functions on the taxonomy menu item being active.
When I hover over a div or class with an id of "a", can I get the background color of a div or class with the id of "b" to change?

Yes, you can do that, but only if #b is after #a in the HTML.

If #b comes immediately after #a: http://jsfiddle.net/u7tYE/

#a:hover + #b {
    background: #ccc
}

Div A

Div B

That's using the adjacent sibling combinator (+).

If there are other elements between #a and #b, you can use this: http://jsfiddle.net/u7tYE/1/

#a:hover ~ #b {
    background: #ccc
}

Div A

random other elements

random other elements

random other elements

Div B

That's using the general sibling combinator (~).

Both + and ~ work in all modern browsers and IE7+

If #b is a descendant of #a, you can simply use #a:hover #b.

ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.

Answer: Future readers may be interested in controlling the active trail with the module: menu_position

Often times site builders want certain types of content to appear in a
  specific position in the navigational menu. The simplest solution,
  adding all of that content individually to the menu system, has
  performance and usability issues. (Imagine hundreds of menu items
  added to one spot in the menu.)
This module allows for the creation of rules that will dynamically add
  the current page into the menu system at the requested spots.
This includes affecting:

The main links of the theme
The secondary links of the theme
The breadcrumb trail
Menu blocks provided by core's Menu module
Menu blocks provided by the Menu Block module
Comment: @NiallMurphy thanks for the explanation! I've edited the answer if you can check it, thanks.
Comment: Not sure why downvoted, it's a contrib module and works well.


MySQL não conectando conecta por erro em socket

Question: Boa tarde amigos, após ter instalado corretamente o MySQL 5.7 no meu Ubuntu 16.04, ao tentar conectar ao banco, recebo uma mensagem de erro falando que não foi possível conectar através do socket.
Executo: mysql -u root -p
E logo em seguida, recebo o erro:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

No diretório /var/run/mysqld/mysqld.sock não existe o arquivo com extensão .sock
Já desinstalei e instalei, tentei com a versão 5.6 e nada tem funcionado. Alguma sugestão?
Obrigado!
Comment: No my.cnf você pode editar a opção do .sock, salvo engano. Depois disso use o `chmod -R 755` no diretorio, exemplo: `chmod -R 755 /var/run/mysqld/mysqld.sock`.
Answer: Conforme essa resposta do SOen, um problema comum que causa o ERROR 2002 é instalar o mysql-client ao invés do mysql-server.
No ubuntu você pode instalar o pacote mysql-server com:
sudo apt-get install mysql-server

Outra possibilidade é que o serviço do mysql não tenha sido inicializado. Em versões recentes do Ubuntu você pode fazer isso com:
sudo start mysql

Finalmente é possível que seu mysql não esteja escutando na combinação de endereço / porta padrão (127.0.0.1:3306). Nesse caso você tem duas opções:

Editar suas configurações no arquivo my.cnf
Especificar o endereço e porta esperados na hora de conectar:
mysql -h [ip/host] -P [porta] -u root -p [database]

Answer: Ola! tive um problema parecido com este

"ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)"

então eu comentei a linha sock=/var/run/mysqld/mysqld.sock em /etc/asterisk/cdr_mysql.conf e resolveu.