Programs & Examples On #Arraylist

A simple collection data type found in some languages / platforms (such as in Java or .NET). The array list implements a list using an array, benefiting from both the DSs strengths.

How to convert an ArrayList containing Integers to primitive int array?

It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.

Just go with Apache Commons

make arrayList.toArray() return more specific types

I got the answer...this seems to be working perfectly fine

public int[] test ( int[]b )
{
    ArrayList<Integer> l = new ArrayList<Integer>();
    Object[] returnArrayObject = l.toArray();
    int returnArray[] = new int[returnArrayObject.length];
    for (int i = 0; i < returnArrayObject.length; i++){
         returnArray[i] = (Integer)  returnArrayObject[i];
    }

    return returnArray;
}

How do I update the element at a certain position in an ArrayList?

 arrList.set(5,newValue);

and if u want to update it then add this line also

 youradapater.NotifyDataSetChanged();

Creating multiple objects with different names in a loop to store in an array list

You can use this code...

public class Main {

    public static void main(String args[]) {
        String[] names = {"First", "Second", "Third"};//You Can Add More Names
        double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
        List<Customer> customers = new ArrayList<Customer>();
        int i = 0;
        while (i < names.length) {
            customers.add(new Customer(names[i], amount[i]));
            i++;
        }
    }
}

Sorting arraylist in alphabetical order (case insensitive)

def  lst = ["A2", "A1", "k22", "A6", "a3", "a5", "A4", "A7"]; 

println lst.sort { a, b -> a.compareToIgnoreCase b }

This should be able to sort with case insensitive but I am not sure how to tackle the alphanumeric strings lists

Java - remove last known item from ArrayList

First error: You're casting a ClientThread as a String for some reason.

Second error: You're not calling remove on your List.

Is is homework? If so, you might want to use the tag.

Load arrayList data into JTable

Basic method for beginners like me.

public void loadDataToJtable(ArrayList<String> liste){
        
    rows = table.getRowCount();

    cols = table.getColumnCount();

    for (int i = 0; i < rows ; i++) {

            for ( int k  = 0; k < cols ; k++) {
            
            for (int h = 0; h < list1.size(); h++) {
                
                String b =  list1.get(h);
                b = table.getValueAt(i, k).toString();
                
            }
        }
    }
}

How to display all elements in an arraylist?

Hi sorry the code for the second one should be:

private static void getAll(CarList c1) {

ArrayList <Car> cars = c1.getAll(); // error incompatible type
for(Car item : cars)
{   
      System.out.println(item.getMake()
                       + " "
                       + item.getReg()
                       );
}

}

I have a class called CarList which contains the arraylist and its method, so in the tester class, i have basically this code to use that CarList class:

CarList c1; c1 = new CarList();

everything else works, such as adding and removing cars and displaying an inidividual car, i just need a code to display all cars in the arraylist.

How to create an 2D ArrayList in java?

ArrayList<String>[][] list = new ArrayList[10][10];
list[0][0] = new ArrayList<>();
list[0][0].add("test");

Adding Multiple Values in ArrayList at a single index

ArrayList<ArrayList> arrObjList = new ArrayList<ArrayList>();
ArrayList<Double> arrObjInner1= new ArrayList<Double>();
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);

arrObjList.add(arrObjInner1);

You can have as many ArrayList inside the arrObjList. I hope this will help you.

java: ArrayList - how can I check if an index exists?

a simple way to do this:

try {
  list.get( index ); 
} 
catch ( IndexOutOfBoundsException e ) {
  if(list.isEmpty() || index >= list.size()){
    // Adding new item to list.
  }
}

convert ArrayList<MyCustomClass> to JSONArray

I know its already answered, but theres a better solution here use this code :

for ( Field f : context.getFields() ) {
     if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
           //DO String To JSON
     }
     /// And so on...
}

This way you can access variables from class without manually typing them..

Faster and better .. Hope this helps.

Cheers. :D

How to add element in List while iterating in java?

Just iterate the old-fashion way, because you need explicit index handling:

List myList = ...
...
int length = myList.size();
for(int i = 0; i < length; i++) {
   String s = myList.get(i);
   // add items here, if you want to
}

Use of contains in Java ArrayList<String>

Yes, that should work for Strings, but if you are worried about duplicates use a Set. This collection prevents duplicates without you having to do anything. A HashSet is OK to use, but it is unordered so if you want to preserve insertion order you use a LinkedHashSet.

How do I find out what type each object is in a ArrayList<Object>?

for (Object object : list) {
    System.out.println(object.getClass().getName());
}

Create ArrayList from array

You can do it in java 8 as follows

ArrayList<Element> list = (ArrayList<Element>)Arrays.stream(array).collect(Collectors.toList());

What is the Simplest Way to Reverse an ArrayList?

Collections.reverse(aList);

Example (Reference):

ArrayList aList = new ArrayList();
//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
Collections.reverse(aList);
System.out.println("After Reverse Order, ArrayList Contains : " + aList);

Pass Arraylist as argument to function

Define it as

<return type> AnalyzeArray(ArrayList<Integer> list) {

How to find an object in an ArrayList by property

Following with Oleg answer, if you want to find ALL objects in a List filtered by a property, you could do something like:

//Search into a generic list ALL items with a generic property
public final class SearchTools {
       public static <T> List<T> findByProperty(Collection<T> col, Predicate<T> filter) {
           List<T> filteredList = (List<T>) col.stream().filter(filter).collect(Collectors.toList());
           return filteredList;
     }

//Search in the list "listItems" ALL items of type "Item" with the specific property "iD_item=itemID"
public static final class ItemTools {
         public static List<Item> findByItemID(Collection<Item> listItems, String itemID) {
             return SearchTools.findByProperty(listItems, item -> itemID.equals(item.getiD_Item()));
         }
     }
}

and similarly if you want to filter ALL items in a HashMap with a certain Property

//Search into a MAP ALL items with a given property
public final class SearchTools {
       public static <T> HashMap<String,T> filterByProperty(HashMap<String,T> completeMap, Predicate<? super Map.Entry<String,T>> filter) {
           HashMap<String,T> filteredList = (HashMap<String,T>) completeMap.entrySet().stream()
                                .filter(filter)
                                .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));
           return filteredList;
     }

     //Search into the MAP ALL items with specific properties
public static final class ItemTools {

        public static HashMap<String,Item> filterByParentID(HashMap<String,Item> mapItems, String parentID) {
            return SearchTools.filterByProperty(mapItems, mapItem -> parentID.equals(mapItem.getValue().getiD_Parent()));
        }

        public static HashMap<String,Item> filterBySciName(HashMap<String,Item> mapItems, String sciName) {
            return SearchTools.filterByProperty(mapItems, mapItem -> sciName.equals(mapItem.getValue().getSciName()));
        }
    }

How to use ArrayAdapter<myClass>

Subclass the ArrayAdapter and override the method getView() to return your own view that contains the contents that you want to display.

Adding to an ArrayList Java

Instantiate a new ArrayList:

List<String> myList = new ArrayList<String>();

Iterate over your data structure (with a for loop, for instance, more details on your code would help.) and for each element (yourElement):

myList.add(yourElement);

Java ArrayList of Arrays?

Should be

private ArrayList<String[]> action = new ArrayList<String[]>();
action.add(new String[2]);
...

You can't specify the size of the array within the generic parameter, only add arrays of specific size to the list later. This also means that the compiler can't guarantee that all sub-arrays be of the same size, it must be ensured by you.

A better solution might be to encapsulate this within a class, where you can ensure the uniform size of the arrays as a type invariant.

Variable length (Dynamic) Arrays in Java

Arrays are fixed size once instantiated. You can use a List instead.

Autoboxing make a List usable similar to an array, you can put simply int-values into it:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);

How to split() a delimited string to a List<String>

Just u can use with using System.Linq;

List<string> stringList = line.Split(',')     // this is array
 .ToList();     // this is a list which you can loop in all split string

ArrayList: how does the size increase?

(oldSize * 3)/2 + 1

If you are using default constructor then initial size of ArrayList will be 10 else you can pass the initial size of array while creating the object of ArrayList.

Example: In case default constructor

List<String> list = new ArrayList<>();
list.size()

Example: In case parameterized constructor

List<String> list = new ArrayList<>(5);
list.size()

How do I clone a generic List in Java?

ArrayList newArrayList = (ArrayList) oldArrayList.clone();

Most efficient way to see if an ArrayList contains an object in Java

Maybe a List isn't what you need.

Maybe a TreeSet would be a better container. You get O(log N) insertion and retrieval, and ordered iteration (but won't allow duplicates).

LinkedHashMap might be even better for your use case, check that out too.

Java Compare Two List's object values?

I found a very basic example of List comparison at List Compare This example verifies the size first and then checks the availability of the particular element of one list in another.

Passing ArrayList from servlet to JSP

here list attribute name set in request request.setAttribute("List",list); and ArrayList list=new ArrayList();

<%

ArrayList<Category> a=(ArrayList<Category>)request.getAttribute("List");

out.print(a);

for(int i=0;i<a.size();i++)

{
    out.println(a.get(i));

}


%>

Passing ArrayList through Intent

//arraylist/Pojo you can Pass using bundle  like this 
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
                        args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
                        intent.putExtra("BUNDLE",args);
 startActivity(intent); 


Get SecondActivity like this
  Intent intent = getIntent();
        Bundle args = intent.getBundleExtra("BUNDLE");
String filter = bundle.getString("imageSliders");

//Happy coding

How does a ArrayList's contains() method evaluate objects?

class Thing {  
    public int value;  

    public Thing (int x) {
        value = x;
    }

    equals (Thing x) {
        if (x.value == value) return true;
        return false;
    }
}

You must write:

class Thing {  
    public int value;  

    public Thing (int x) {
        value = x;
    }

    public boolean equals (Object o) {
    Thing x = (Thing) o;
        if (x.value == value) return true;
        return false;
    }
}

Now it works ;)

Convert an array into an ArrayList

This will give you a list.

List<Card> cardsList = Arrays.asList(hand);

If you want an arraylist, you can do

ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));

ArrayList filter

As you didn't give us very much information, I'm assuming the language you're writing the code in is C#. First of all: Prefer System.Collections.Generic.List over an ArrayList. Secondly: One way would be to loop through every item in the list and check whether it contains "How". Another way would be to use LINQ. Here's a quick example that filters out every item which doesn't contain "How":

var list = new List<string>();
list.AddRange(new string[] {
    "How are you?",
    "How you doing?",
    "Joe",
    "Mike", });

foreach (string str in list.Where(s => s.Contains("How")))
{
    Console.WriteLine(str);
}
Console.ReadLine();

Print ArrayList

since you haven't provide a custom implementation for toString() method it calls the default on which is going to print the address in memory for that object

solution in your Address class override the toString() method like this

public class Address {

int addressNo ; 
....
....
...

protected String toString(){
    return Integer.toString(addressNo);
}

now when you call

houseAddress.get(i)  in the `System.out.print()` method like this

System.out.print( houseAddress.get(i) ) the toString() of the Address object will be called

When to use HashMap over LinkedList or ArrayList and vice-versa

The downfall of ArrayList and LinkedList is that when iterating through them, depending on the search algorithm, the time it takes to find an item grows with the size of the list.

The beauty of hashing is that although you sacrifice some extra time searching for the element, the time taken does not grow with the size of the map. This is because the HashMap finds information by converting the element you are searching for, directly into the index, so it can make the jump.

Long story short... LinkedList: Consumes a little more memory than ArrayList, low cost for insertions(add & remove) ArrayList: Consumes low memory, but similar to LinkedList, and takes extra time to search when large. HashMap: Can perform a jump to the value, making the search time constant for large maps. Consumes more memory and takes longer to find the value than small lists.

Java: how can I split an ArrayList in multiple small ArrayLists?

You need to know the chunk size by which you're dividing your list. Say you have a list of 108 entries and you need a chunk size of 25. Thus you will end up with 5 lists:

  • 4 having 25 entries each;
  • 1 (the fifth) having 8 elements.

Code:

public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>();
        for (int i=0; i<108; i++){
            list.add(i);
        }
        int size= list.size();
        int j=0;
                List< List<Integer> > splittedList = new ArrayList<List<Integer>>()  ;
                List<Integer> tempList = new ArrayList<Integer>();
        for(j=0;j<size;j++){
            tempList.add(list.get(j));
        if((j+1)%25==0){
            // chunk of 25 created and clearing tempList
            splittedList.add(tempList);
            tempList = null;
            //intializing it again for new chunk 
            tempList = new ArrayList<Integer>();
        }
        }
        if(size%25!=0){
            //adding the remaining enteries 
            splittedList.add(tempList);
        }
        for (int k=0;k<splittedList.size(); k++){
            //(k+1) because we started from k=0
            System.out.println("Chunk number: "+(k+1)+" has elements = "+splittedList.get(k).size());
        }
    }

How to use an arraylist as a prepared statement parameter

why making life hard-

PreparedStatement pstmt = conn.prepareStatement("select * from employee where id in ("+ StringUtils.join(arraylistParameter.iterator(),",") +)");

Foreach loop in java for a custom object list

You can fix your example with the iterator pattern by changing the parametrization of the class:

List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Iterator<Room> i = rooms.iterator(); i.hasNext(); ) {
  String item = i.next();
  System.out.println(item);
}

or much simpler way:

List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Room room : rooms) {
  System.out.println(room);
}

Java ArrayList how to add elements at the beginning

I think the implement should be easy, but considering about the efficiency, you should use LinkedList but not ArrayList as the container. You can refer to the following code:

import java.util.LinkedList;
import java.util.List;

public class DataContainer {

    private List<Integer> list;

    int length = 10;
    public void addDataToArrayList(int data){
        list.add(0, data);
        if(list.size()>10){
            list.remove(length);
        }
    }

    public static void main(String[] args) {
        DataContainer comp = new DataContainer();
        comp.list = new LinkedList<Integer>();

        int cycleCount = 100000000;

        for(int i = 0; i < cycleCount; i ++){
            comp.addDataToArrayList(i);
        }
    }
}

Convert an ArrayList to an object array

Convert an ArrayList to an object array

ArrayList has a constructor that takes a Collection, so the common idiom is:

List<T> list = new ArrayList<T>(Arrays.asList(array));

Which constructs a copy of the list created by the array.

now, Arrays.asList(array) will wrap the array, so changes to the list will affect the array, and visa versa. Although you can't add or remove

elements from such a list.

Arraylist swap elements

for (int i = 0; i < list.size(); i++) {
        if (i < list.size() - 1) {
            if (list.get(i) > list.get(i + 1)) {
                int j = list.get(i);
                list.remove(i);
                list.add(i, list.get(i));
                list.remove(i + 1);
                list.add(j);
                i = -1;
            }
        }
    }

Correct way to synchronize ArrayList in java

You're synchronizing twice, which is pointless and possibly slows down the code: changes while iterating over the list need a synchronnization over the entire operation, which you are doing with synchronized (in_queue_list) Using Collections.synchronizedList() is superfluous in that case (it creates a wrapper that synchronizes individual operations).

However, since you are emptying the list completely, the iterated removal of the first element is the worst possible way to do it, sice for each element all following elements have to be copied, making this an O(n^2) operation - horribly slow for larger lists.

Instead, simply call clear() - no iteration needed.

Edit: If you need the single-method synchronization of Collections.synchronizedList() later on, then this is the correct way:

List<Record> in_queue_list = Collections.synchronizedList(in_queue);
in_queue_list.clear(); // synchronized implicitly, 

But in many cases, the single-method synchronization is insufficient (e.g. for all iteration, or when you get a value, do computations based on it, and replace it with the result). In that case, you have to use manual synchronization anyway, so Collections.synchronizedList() is just useless additional overhead.

How to declare an ArrayList with values?

The Guava library contains convenience methods for creating lists and other collections which makes this much prettier than using the standard library classes.

Example:

ArrayList<String> list = newArrayList("a", "b", "c");

(This assumes import static com.google.common.collect.Lists.newArrayList;)

Convert List<String> to List<Integer> directly

If you use Google Guava library this is what you can do, see Lists#transform

    String s = "AttributeGet:1,16,10106,10111";


    List<Integer> attributeIDGet = new ArrayList<Integer>();

    if(s.contains("AttributeGet:")) {
        List<String> attributeIDGetS = Arrays.asList(s.split(":")[1].split(","));
        attributeIDGet =
        Lists.transform(attributeIDGetS, new Function<String, Integer>() {
            public Integer apply(String e) {
                return Integer.parseInt(e);
            };
        });
    }

Yep, agree with above answer that's it's bloated, but stylish. But it's just another way.

Difference between size and length methods?

Based on the syntax I'm assuming that it is some language which is descendant of C. As per what I have seen, length is used for simple collection items like arrays and in most cases it is a property.

size() is a function and is used for dynamic collection objects. However for all the purposes of using, you wont find any differences in outcome using either of them. In most implementations, size simply returns length property.

Java ArrayList clear() function

it's not true the clear() function clear the Arraylist and start from index 0

From Arraylist to Array

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0])). In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation. You can follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

Using generics (as in the above answers) is your best bet here. I've just double checked and:

test.put("test", arraylistone); 
ArrayList current = new ArrayList();
current = (ArrayList) test.get("test");

will work as well, through I wouldn't recommend it as the generics ensure that only the correct data is added, rather than trying to do the handling at retrieval time.

What's the C++ version of Java's ArrayList

A couple of additional points re use of vector here.

Unlike ArrayList and Array in Java, you don't need to do anything special to treat a vector as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.

Unlike ArrayList, a vector can efficiently hold primitive types without encapsulation as a full-fledged object.

When removing items from a vector, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.

Make sure if you store complex objects in the vector that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.

Advice about reserve()ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.

Get specific objects from ArrayList when objects were added anonymously?

I would suggest overriding the equals(Object) of your Party class. It might look something like this:

public boolean equals(Object o){
    if(o == null)
        return false;
    if(o instanceof String)
        return name.equalsIgnoreCase((String)o);
    else if(o instanceof Party)
        return equals(((Party)o).name);
    return false;
}

After you do that, you could use the indexOf(Object) method to retrieve the index of the party specified by its name, as shown below:

int index = cave.parties.indexOf("SecondParty");

Would return the index of the Party with the name SecondParty.

Note: This only works because you are overriding the equals(Object) method.

Initialization of an ArrayList in one line

Here is code by AbacusUtil

// 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 AbacusUtil.

Arrays.asList() of an array

Use java.utils.Arrays:

public int getTheNumber(int[] factors) {
    int[] f = (int[])factors.clone();
    Arrays.sort(f);
    return f[0]*f[(f.length-1];
}

Or if you want to be efficient avoid all the object allocation just actually do the work:

public static int getTheNumber(int[] array) {
    if (array.length == 0)
        throw new IllegalArgumentException();
    int min = array[0];
    int max = array[0];
    for (int i = 1; i< array.length;++i) {
        int v = array[i];
        if (v < min) {
            min = v;
        } else if (v > max) {
            max = v;
        }
    }
    return min * max;
}

Adding null values to arraylist

You could create Util class:

public final class CollectionHelpers {
    public static <T> boolean addNullSafe(List<T> list, T element) {
        if (list == null || element == null) {
            return false;
        }

        return list.add(element);
    }
}

And then use it:

Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);

Create an ArrayList of unique values

Pretty late to the party, but here's my two cents:

Use a LinkedHashSet

I assume what you need is a collection which:

  • disallows you to insert duplicates;
  • retains insertion order.

LinkedHashSet does this. The advantage over using an ArrayList is that LinkedHashSet has a complexity of O(1) for the contains operation, as opposed to ArrayList, which has O(n).


Of course, you need to implement your object's equals and hashCode methods properly.

How does one convert a HashMap to a List in Java?

If you wanna maintain the same order in your list, say: your Map looks like:

map.put(1, "msg1")
map.put(2, "msg2")
map.put(3, "msg3")

and you want your list looks like

["msg1", "msg2", "msg3"]   // same order as the map

you will have to iterate through the Map:

// sort your map based on key, otherwise you will get IndexOutofBoundException
Map<String, String> treeMap = new TreeMap<String, String>(map)

List<String> list = new List<String>();
for (treeMap.Entry<Integer, String> entry : treeMap.entrySet()) {
    list.add(entry.getKey(), entry.getValue());
}  

How to remove specific object from ArrayList in Java?

simple use remove() function. and pass object as param u want to remove. ur arraylist.remove(obj)

Add object to ArrayList at specified index

If you are using the Android flavor of Java, might I suggest using a SparseArray. It's a more memory efficient mapping of integers to objects and easier to iterate over than a Map

Check if a value exists in ArrayList

Better to use a HashSet than an ArrayList when you are checking for existence of a value. Java docs for HashSet says: "This class offers constant time performance for the basic operations (add, remove, contains and size)"

ArrayList.contains() might have to iterate the whole list to find the instance you are looking for.

ArrayList of int array in java

For the more inexperienced, I have decided to add an example to demonstrate how to input and output an ArrayList of Integer arrays based on this question here.

    ArrayList<Integer[]> arrayList = new ArrayList<Integer[]>();
    while(n > 0)
    {
        int d = scan.nextInt();
       Integer temp[] = new Integer[d];
        for (int i = 0 ; i < d ; i++)
        {
            int t = scan.nextInt();
            temp[i]=Integer.valueOf(t);
        }
        arrayList.add(temp);
        n--;
    }//n is the size of the ArrayList that has been taken as a user input & d is the size 
    //of each individual array.

     //to print something  out from this ArrayList, we take in two 
    // values,index and index1 which is the number of the line we want and 
    // and the position of the element within that line (since the question
    // followed a 1-based numbering scheme, I did not change it here)

    System.out.println(Integer.valueOf(arrayList.get(index-1)[index1-1]));

Thanks to this answer on this question here, I got the correct answer. I believe this satisfactorily answers OP's question, albeit a little late and can serve as an explanation for those with less experience.

Common elements in two lists

consider two list L1 ans L2

Using Java8 we can easily find it out

L1.stream().filter(L2::contains).collect(Collectors.toList())

How to remove all null elements from a ArrayList or String Array?

Similar to @Lithium answer but does not throw a "List may not contain type null" error:

   list.removeAll(Collections.<T>singleton(null));

How to use an array list in Java?

You could either get your strings by index (System.out.println(S.get(0));) or iterate through it:

for (String s : S) {
  System.out.println(s);
}

For other ways to iterate through a list (and their implications) see traditional for loop vs Iterator in Java.

Additionally:

  • you shouldn't use variable names starting with upper-case letters
  • you should parametrize your array list: ArrayList<String> list = new ArrayList<String>();
  • you should get familiar with Java's extensive API documentation (aka Javadoc), e.g. Java 5, Java 6

Searching in a ArrayList with custom objects for certain strings

boolean found;

for(CustomObject obj : ArrayOfCustObj) {

   if(obj.getName.equals("Android")) {

      found = true;
   }
}

Print an ArrayList with a for-each loop

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

list.clear() vs list = new ArrayList<Integer>();

I would suggest using list.clear() rather than allocating a new object. When you call the "new" keyword, you are creating more space in memory. In reality, it doesn't matter much. I suppose that if you know how large the list will be, it might be a good idea to create a new space but then specify how large the array will be.

The truth is, it's not going to matter unless you're doing scientific programming. In that case, you need to go learn C++.

Better way to find index of item in ArrayList?

ArrayList has a indexOf() method. Check the API for more, but here's how it works:

private ArrayList<String> _categories; // Initialize all this stuff

private int getCategoryPos(String category) {
  return _categories.indexOf(category);
}

indexOf() will return exactly what your method returns, fast.

Convert ArrayList to String array in Android

You can try this code

String[] stringA = new String[stringArrayList.size()];
stringArrayList.toArray(stringA)
System.out.println(stringA[0]);

Get specific ArrayList item

mainList.get(3);

For future reference, you should refer to the Java API for these types of questions:

http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html

It's a useful thing!

Java method: Finding object in array list given a known attribute value

I solved this using java 8 lambdas

int dogId = 2;

return dogList.stream().filter(dog-> dogId == dog.getId()).collect(Collectors.toList()).get(0);

How to create a Multidimensional ArrayList in Java?

ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();

Depending on your requirements, you might use a Generic class like the one below to make access easier:

import java.util.ArrayList;

class TwoDimentionalArrayList<T> extends ArrayList<ArrayList<T>> {
    public void addToInnerArray(int index, T element) {
        while (index >= this.size()) {
            this.add(new ArrayList<T>());
        }
        this.get(index).add(element);
    }

    public void addToInnerArray(int index, int index2, T element) {
        while (index >= this.size()) {
            this.add(new ArrayList<T>());
        }

        ArrayList<T> inner = this.get(index);
        while (index2 >= inner.size()) {
            inner.add(null);
        }

        inner.set(index2, element);
    }
}

How to insert values in two dimensional array programmatically?

You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.

If you know how to do it with one-dimensional arrays then you know how to do it with n-dimensional arrays: There are no n-dimensional arrays in Java, only arrays of arrays (of arrays...).

But you can chain the index operator for array element access.

String[][] x = new String[2][];
x[0] = new String[1];
x[1] = new String[2];

x[0][0] = "a1";
    // No x[0][1] available
x[1][0] = "b1";
x[1][1] = "b2";

Note the dimensions of the child arrays don't need to match.

How to count the number of occurrences of an element in a List

This shows, why it is important to "Refer to objects by their interfaces" as described in Effective Java book.

If you code to the implementation and use ArrayList in let's say, 50 places in your code, when you find a good "List" implementation that count the items, you will have to change all those 50 places, and probably you'll have to break your code ( if it is only used by you there is not a big deal, but if it is used by someone else uses, you'll break their code too)

By programming to the interface you can let those 50 places unchanged and replace the implementation from ArrayList to "CountItemsList" (for instance ) or some other class.

Below is a very basic sample on how this could be written. This is only a sample, a production ready List would be much more complicated.

import java.util.*;

public class CountItemsList<E> extends ArrayList<E> { 

    // This is private. It is not visible from outside.
    private Map<E,Integer> count = new HashMap<E,Integer>();

    // There are several entry points to this class
    // this is just to show one of them.
    public boolean add( E element  ) { 
        if( !count.containsKey( element ) ){
            count.put( element, 1 );
        } else { 
            count.put( element, count.get( element ) + 1 );
        }
        return super.add( element );
    }

    // This method belongs to CountItemList interface ( or class ) 
    // to used you have to cast.
    public int getCount( E element ) { 
        if( ! count.containsKey( element ) ) {
            return 0;
        }
        return count.get( element );
    }

    public static void main( String [] args ) { 
        List<String> animals = new CountItemsList<String>();
        animals.add("bat");
        animals.add("owl");
        animals.add("bat");
        animals.add("bat");

        System.out.println( (( CountItemsList<String> )animals).getCount( "bat" ));
    }
}

OO principles applied here: inheritance, polymorphism, abstraction, encapsulation.

add item in array list of android

item=sp.getItemAtPosition(i).toString();
list.add(item);
adapter.notifyDataSetChanged () ;

look up ArrayAdapter.notifyDataSetChanged()

How do I populate a JComboBox with an ArrayList?

By combining existing answers (this one and this one) the proper type safe way to add an ArrayList to a JComboBox is the following:

private DefaultComboBoxModel<YourClass> getComboBoxModel(List<YourClass> yourClassList)
{
    YourClass[] comboBoxModel = yourClassList.toArray(new YourClass[0]);
    return new DefaultComboBoxModel<>(comboBoxModel);
}

In your GUI code you set the entire list into your JComboBox as follows:

DefaultComboBoxModel<YourClass> comboBoxModel = getComboBoxModel(yourClassList);
comboBox.setModel(comboBoxModel);

How to dynamically add elements to String array?

You cant add add items in string array more than its size, i'll suggest you to use ArrayList you can add items dynamically at run time in arrayList if you feel any problem you can freely ask

Get value (String) of ArrayList<ArrayList<String>>(); in Java

The right way to iterate on a list inside list is:

//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
    ArrayList<String> currentList = collection.get(i);
    //now iterate on the current list
    for (int j = 0; j < currentList.size(); j++) {
        String s = currentList.get(1);
    }
}

How to use ArrayList.addAll()?

You can use the asList method with varargs to do this in one line:

java.util.Arrays.asList('+', '-', '*', '^');

If the list does not need to be modified further then this would already be enough. Otherwise you can pass it to the ArrayList constructor to create a mutable list:

new ArrayList(Arrays.asList('+', '-', '*', '^'));

Populating a ListView using an ArrayList?

Try the below answer to populate listview using ArrayList

public class ExampleActivity extends Activity
{
    ArrayList<String> movies;

    public void onCreate(Bundle saveInstanceState)
    {
       super.onCreate(saveInstanceState);
       setContentView(R.layout.list);

       // Get the reference of movies
       ListView moviesList=(ListView)findViewById(R.id.listview);

       movies = new ArrayList<String>();
       getMovies();

       // Create The Adapter with passing ArrayList as 3rd parameter
       ArrayAdapter<String> arrayAdapter =      
                 new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, movies);
       // Set The Adapter
       moviesList.setAdapter(arrayAdapter); 

       // register onClickListener to handle click events on each item
       moviesList.setOnItemClickListener(new OnItemClickListener()
       {
           // argument position gives the index of item which is clicked
           public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3)
           {
               String selectedmovie=movies.get(position);
               Toast.makeText(getApplicationContext(), "Movie Selected : "+selectedmovie,   Toast.LENGTH_LONG).show();
           }
        });
    }

    void getmovies()
    {
        movies.add("X-Men");
        movies.add("IRONMAN");
        movies.add("SPIDY");
        movies.add("NARNIA");
        movies.add("LIONKING");
        movies.add("AVENGERS");   
    }
}

How to quickly and conveniently create a one element arraylist

Yet another alternative is double brace initialization, e.g.

new ArrayList<String>() {{ add(s); }};

but it is inefficient and obscure. Therefore only suitable:

  • in code that doesn't mind memory leaks, such as most unit tests and other short-lived programs;
  • and if none of the other solutions apply, which I think implies you've scrolled all the way down here looking to populate a different type of container than the ArrayList in the question.

Java ArrayList of Doubles

You are encountering a problem because you cannot construct the ArrayList and populate it at the same time. You either need to create it and then manually populate it as such:

ArrayList list = new ArrayList<Double>();
list.add(1.38);
...

Or, alternatively if it is more convenient for you, you can populate the ArrayList from a primitive array containing your values. For example:

Double[] array = {1.38, 2.56, 4.3};
ArrayList<Double> list = new ArrayList<Double>(Arrays.asList(array));

Java ArrayList - how can I tell if two lists are equal, order not mattering?

// helper class, so we don't have to do a whole lot of autoboxing
private static class Count {
    public int count = 0;
}

public boolean haveSameElements(final List<String> list1, final List<String> list2) {
    // (list1, list1) is always true
    if (list1 == list2) return true;

    // If either list is null, or the lengths are not equal, they can't possibly match 
    if (list1 == null || list2 == null || list1.size() != list2.size())
        return false;

    // (switch the two checks above if (null, null) should return false)

    Map<String, Count> counts = new HashMap<>();

    // Count the items in list1
    for (String item : list1) {
        if (!counts.containsKey(item)) counts.put(item, new Count());
        counts.get(item).count += 1;
    }

    // Subtract the count of items in list2
    for (String item : list2) {
        // If the map doesn't contain the item here, then this item wasn't in list1
        if (!counts.containsKey(item)) return false;
        counts.get(item).count -= 1;
    }

    // If any count is nonzero at this point, then the two lists don't match
    for (Map.Entry<String, Count> entry : counts.entrySet()) {
        if (entry.getValue().count != 0) return false;
    }

    return true;
}

java howto ArrayList push, pop, shift, and unshift

Underscore-java library contains methods push(values), pop(), shift() and unshift(values).

Code example:

import com.github.underscore.U:

List<String> strings = Arrays.asList("one", "two", " three");
List<String> newStrings = U.push(strings, "four", "five");
// ["one", " two", "three", " four", "five"]
String newPopString = U.pop(strings).fst();
// " three"
String newShiftString = U.shift(strings).fst();
// "one"
List<String> newUnshiftStrings = U.unshift(strings, "four", "five");
// ["four", " five", "one", " two", "three"]

ArrayList vs List<> in C#

Using List<T> you can prevent casting errors. It is very useful to avoid a runtime casting error.

Example:

Here (using ArrayList) you can compile this code but you will see an execution error later.

ArrayList array1 = new ArrayList();
array1.Add(1);
array1.Add("Pony"); //No error at compile process
int total = 0;
foreach (int num in array1)
{
 total += num; //-->Runtime Error
}

If you use List, you avoid these errors:

List<int> list1 = new List<int>();
list1.Add(1);
//list1.Add("Pony"); //<-- Error at compile process
int total = 0;
foreach (int num in list1 )
{
 total += num;
}

Reference: MSDN

Convert Iterator to ArrayList

use google guava !

Iterable<String> fieldsIterable = ...
List<String> fields = Lists.newArrayList(fieldsIterable);

++

Simple way to compare 2 ArrayLists

As far as I understand it correctly, I think it's easiest to work with 4 lists: - Your sourceList - Your destinationList - A removedItemsList - A newlyAddedItemsList

Multi-dimensional arraylist or list in C#?

Depending on your exact requirements, you may do best with a jagged array of sorts with:

List<string>[] results = new { new List<string>(), new List<string>() };

Or you may do well with a list of lists or some other such construct.

How can I sort an ArrayList of Strings in Java?

Collections.sort(teamsName.subList(1, teamsName.size()));

The code above will reflect the actual sublist of your original list sorted.

Add multiple items to already initialized arraylist in java

If you are looking to avoid multiple code lines to save space, maybe this syntax could be useful:

        java.util.ArrayList lisFieldNames = new ArrayList() {
            {
                add("value1"); 
                add("value2");
            }
        };

Removing new lines, you can show it compressed as:

        java.util.ArrayList lisFieldNames = new ArrayList() {
            {
                add("value1"); add("value2"); (...);
            }
        };

How can I slice an ArrayList out of an ArrayList in Java?

This is how I solved it. I forgot that sublist was a direct reference to the elements in the original list, so it makes sense why it wouldn't work.

ArrayList<Integer> inputA = new ArrayList<Integer>(input.subList(0, input.size()/2));

How to search for a string in an arraylist

List <String> list = new ArrayList();  
           list.add("behold"); 
           list.add("bend"); 
           list.add("bet"); 
           list.add("bear"); 
           list.add("beat"); 
           list.add("become"); 
           list.add("begin");

           List <String> listClone = new ArrayList<String>(); 
           Pattern pattern = Pattern.compile("bea",Pattern.CASE_INSENSITIVE); //incase u r not concerned about upper/lower case
           for (String string : list) {
               if(pattern.matcher(string).find()) {
                   listClone.add(string);
                   continue;
               }
           }
        System.out.println(listClone);

In Java, can you modify a List while iterating through it?

Use Java 8's removeIf(),

To remove safely,

letters.removeIf(x -> !x.equals("A"));

how to fix java.lang.IndexOutOfBoundsException

Use if(index.length() < 0) for Integer

or

Use if(index.equals(null) for String

Option to ignore case with .contains method?

For Java 8, You can have one more solution like below

List<String> list = new ArrayList<>();
String searchTerm = "dvd";

if(String.join(",", list).toLowerCase().contains(searchTerm)) {
  System.out.println("Element Present!");
}

Best way to convert an ArrayList to a string

If you happen to be doing this on Android, there is a nice utility for this called TextUtils which has a .join(String delimiter, Iterable) method.

List<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
String joined = TextUtils.join(", ", list);

Obviously not much use outside of Android, but figured I'd add it to this thread...

How to sort an ArrayList in Java

Use a Comparator like this:

List<Fruit> fruits= new ArrayList<Fruit>();

Fruit fruit;
for(int i = 0; i < 100; i++)
{
  fruit = new Fruit();
  fruit.setname(...);
  fruits.add(fruit);
}

// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
        @Override
        public int compare(Fruit fruit2, Fruit fruit1)
        {

            return  fruit1.fruitName.compareTo(fruit2.fruitName);
        }
    });

Now your fruits list is sorted based on fruitName.

Retrieving a random item from ArrayList

public static Item getRandomChestItem(List<Item> items) {
    return items.get(new Random().nextInt(items.size()));
}

How to Sort Date in descending order From Arraylist Date in android?

Date is Comparable so just create list of List<Date> and sort it using Collections.sort(). And use Collections.reverseOrder() to get comparator in reverse ordering.

From Java Doc

Returns a comparator that imposes the reverse ordering of the specified comparator. If the specified comparator is null, this method is equivalent to reverseOrder() (in other words, it returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface).

How to iterate through an ArrayList of Objects of ArrayList of Objects?

When using Java8 it would be more easier and a single liner only.

    gunList.get(2).getBullets().forEach(n -> System.out.println(n));

How to convert a String into an ArrayList?

Ok i'm going to extend on the answers here since a lot of the people who come here want to split the string by a whitespace. This is how it's done:

List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));

How can I calculate the difference between two ArrayLists?

Hi use this class this will compare both lists and shows exactly the mismatch b/w both lists.

import java.util.ArrayList;
import java.util.List;


public class ListCompare {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List<String> dbVinList;
        dbVinList = new ArrayList<String>();
        List<String> ediVinList;
        ediVinList = new ArrayList<String>();           

        dbVinList.add("A");
        dbVinList.add("B");
        dbVinList.add("C");
        dbVinList.add("D");

        ediVinList.add("A");
        ediVinList.add("C");
        ediVinList.add("E");
        ediVinList.add("F");
        /*ediVinList.add("G");
        ediVinList.add("H");
        ediVinList.add("I");
        ediVinList.add("J");*/  

        List<String> dbVinListClone = dbVinList;
        List<String> ediVinListClone = ediVinList;

        boolean flag;
        String mismatchVins = null;
        if(dbVinListClone.containsAll(ediVinListClone)){
            flag = dbVinListClone.removeAll(ediVinListClone);   
            if(flag){
                mismatchVins = getMismatchVins(dbVinListClone);
            }
        }else{
            flag = ediVinListClone.removeAll(dbVinListClone);
            if(flag){
                mismatchVins = getMismatchVins(ediVinListClone);
            }
        }
        if(mismatchVins != null){
            System.out.println("mismatch vins : "+mismatchVins);
        }       

    }

    private static String getMismatchVins(List<String> mismatchList){
        StringBuilder mismatchVins = new StringBuilder();
        int i = 0;
        for(String mismatch : mismatchList){
            i++;
            if(i < mismatchList.size() && i!=5){
                mismatchVins.append(mismatch).append(",");  
            }else{
                mismatchVins.append(mismatch);
            }
            if(i==5){               
                break;
            }
        }
        String mismatch1;
        if(mismatchVins.length() > 100){
            mismatch1 = mismatchVins.substring(0, 99);
        }else{
            mismatch1 = mismatchVins.toString();
        }       
        return mismatch1;
    }

}

what is the difference between ajax and jquery and which one is better?

Ajax is a way of using Javascript for communicating with serverside without loading the page over again. jQuery uses ajax for many of its functions, but it nothing else than a library that provides easier functionality.

With jQuery you dont have to think about creating xml objects ect ect, everything is done for you, but with straight up javascript ajax you need to program every single step of the ajax call.

Map HTML to JSON

I had a similar issue where I wanted to represent HTML as JSON in the following way:

  • For HTML text nodes, use a string
  • For HTML elements, use an array with:
    • The (tag) name of the element
    • An object, mapping attribute keys to attribute values
    • The (inlined) list of children nodes

Example:

<div>
  <span>text</span>Text2
</div>

becomes

[
   'div',
   {},
   ['span', {}, 'text'],
   'Text2'
]

I wrote a function which handles transforming a DOM Element into this kind of JS structure. You can find this function at the end of this answer. The function is written in Typescript. You can use the Typescript playground to convert it to clean JavaScript.


Furthermore, if you need to parse an html string into DOM, assign to .innerHtml:

let element = document.createElement('div')
element.innerHtml = htmlString

Also, this one is common knowledge but if you need a JSON string output, use JSON.stringify.


/**
 * A NodeDescriptor stands for either an (HTML) Element, or for a text node
 */
export type NodeDescriptor = ElementDescriptor | string

/**
 * Array representing an HTML Element. It consists of:
 *
 * - The (tag) name of the element
 * - An object, mapping attribute keys to attribute values
 * - The (inlined) list of children nodes
 */
export type ElementDescriptor = [
   string,
   Record<string, string>,
   ...NodeDescriptor[]
]

export let htmlToJs = (element: Element, trim = true): ElementDescriptor => {
   let convertElement = (element: Element): ElementDescriptor => {
      let attributeObject: Record<string, string> = {}
      for (let { name, value } of element.attributes) {
         attributeObject[name] = value
      }

      let childArray: NodeDescriptor[] = []
      for (let node of element.childNodes) {
         let converter = htmlToJsDispatch[node.nodeType]
         if (converter) {
            let descriptor = converter(node as any)
            let skip = false

            if (trim && typeof descriptor === 'string') {
               descriptor = descriptor.trim()
               if (descriptor === '') skip = true
            }

            if (!skip) childArray.push(descriptor)
         }
      }

      return [element.tagName.toLowerCase(), attributeObject, ...childArray]
   }

   let htmlToJsDispatch = {
      [element.ELEMENT_NODE]: convertElement,
      [element.TEXT_NODE]: (node: Text): string => node.data,
   }

   return convertElement(element)
}

How to set the env variable for PHP?

Try display phpinfo() by file and check this var.

Qt jpg image display

Using QPainter and QImage to paint on a window-widget (QMainWindow) (just another method)

class MainWindow : public QMainWindow
{    
    public:
        MainWindow();
    protected:
        void paintEvent(QPaintEvent* event) override;

    protected:
        QImage image = QImage("/path/to/image.jpg");
};

// for convenience resize window to image size
MainWindow::MainWindow()
{
    setMinimumSize(image.size());
}

void MainWindow::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    QRect rect = event->rect();
    painter.drawImage(rect, image, rect);
}


int main(int argc, char** argv)
{
    QApplication a(argc, argv);

    MainWindow mainWindow;
    mainWindow.show();
    return a.exec();
}

json Uncaught SyntaxError: Unexpected token :

I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].

The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.

Good to go! here is my working code for this:

_x000D_
_x000D_
  $.ajax({_x000D_
      crossOrigin: true,_x000D_
      url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",_x000D_
      type : "GET",_x000D_
      success:function(data){_x000D_
         console.log(data);_x000D_
      }_x000D_
    })
_x000D_
_x000D_
_x000D_

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

Try This.

Controller:

List<CountryModel> countryList = db.countryTable.ToList();
ViewBag.Country = new SelectList(countryList, "Country", "CountryName");

How to change the color of a button?

You can change the colour two ways; through XML or through coding. I would recommend XML since it's easier to follow for beginners.

XML:

<Button
    android:background="@android:color/white"
    android:textColor="@android:color/black"
/>

You can also use hex values ex.

android:background="@android:color/white"

Coding:

//btn represents your button object

btn.setBackgroundColor(Color.WHITE);
btn.setTextColor(Color.BLACK);

How to get UTC timestamp in Ruby?

time = Time.zone.now()

It will work as

irb> Time.zone.now
=> 2017-12-02 12:06:41 UTC

How to use Utilities.sleep() function

Serge is right - my workaround:

function mySleep (sec)
{
  SpreadsheetApp.flush();
  Utilities.sleep(sec*1000);
  SpreadsheetApp.flush();
}

How to create nonexistent subdirectories recursively using Bash?

mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8

How to get a list of sub-folders and their files, ordered by folder-names

Hej man, why are you using this ?

dir /s/b/o:gn > f.txt (wrong one)

Don't you know what is that 'g' in '/o' ??

Check this out: http://www.computerhope.com/dirhlp.htm or dir /? for dir help

You should be using this instead:

dir /s/b/o:n > f.txt (right one)

Bluetooth pairing without user confirmation

BT version 2.0 or less - You should be able to pair/bond using a standard PIN code, entered programmatically e.g. 1234 or 0000. This is not very secure but many BT devices do this.

BT version 2.1 or greater - Mode 4 Secure Simple Pairing "just works" model can be used. It uses elliptical encryption (whatever that is) and is very secure but is open to Man In The Middle attacks. Compared to the old '0000' pin code approach it is light years ahead. This doesn't require any user input.

This is according to the Bluetooth specs but what you can use depends on what verson of the Bluetooth standard your stack supports and what API you have.

Convert an enum to List<string>

Use Enum's static method, GetNames. It returns a string[], like so:

Enum.GetNames(typeof(DataSourceTypes))

If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

You will need Using System.Linq; at the top of your class to use .ToList()

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

You must add a reference to assembly 'netstandard, Version=2.0.0.0

This issue is based on your installed version of visual studio and Windows, you can follow the following steps:-

  1. Go to Command Window
  2. downgraded your PCL by the following command

    Install-Package Xamarin.Forms -Version 2.5.1.527436
    
  3. Rebuild Your Project.
  4. Now You will able to see the required output

how to hide keyboard after typing in EditText in android?

You might also want to define the imeOptions within the EditText. This way, the keyboard will go away once you press on Done:

<EditText
    android:id="@+id/editText1"
    android:inputType="text"
    android:imeOptions="actionDone"/>

How to install Selenium WebDriver on Mac OS

Install

If you use homebrew (which I recommend), you can install selenium using:

brew install selenium-server-standalone

Running

updated -port port_number

To run selenium, do: selenium-server -port 4444

For more options: selenium-server -help

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

Minimal solution that worked for me for current project

  • A create-react-app project
  • Ubuntu / *nix
  • 2020
  • Node 14.7

delete node_modules/browserslist directory in the project

now

npm run build

no longer generates that message

SQL MERGE statement to update data

Update energydata set energydata.kWh = temp.kWh 
where energydata.webmeterID = (select webmeterID from temp_energydata as temp) 

Format a JavaScript string using placeholders and an object of substitutions?

How about using ES6 template literals?

var a = "cat";
var b = "fat";
console.log(`my ${a} is ${b}`); //notice back-ticked string

More about template literals...

Play infinitely looping video on-load in HTML5

The loop attribute should do it:

<video width="320" height="240" autoplay loop>
  <source src="movie.mp4" type="video/mp4" />
  <source src="movie.ogg" type="video/ogg" />
  Your browser does not support the video tag.
</video>

Should you have a problem with the loop attribute (as we had in the past), listen to the videoEnd event and call the play() method when it fires.

Note1: I'm not sure about the behavior on Apple's iPad/iPhone, because they have some restrictions against autoplay.

Note2: loop="true" and autoplay="autoplay" are deprecated

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

An elegant way in Swift 3 and better to understand:

override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
    let leftMargin:CGFloat = 40
    let imgWidth:CGFloat = 24
    let imgHeight:CGFloat = 24
    return CGRect(x: leftMargin, y: (contentRect.size.height-imgHeight) * 0.5, width: imgWidth, height: imgHeight)
}

override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
    let leftMargin:CGFloat = 80
    let rightMargin:CGFloat = 80
    return CGRect(x: leftMargin, y: 0, width: contentRect.size.width-leftMargin-rightMargin, height: contentRect.size.height)
}
override func backgroundRect(forBounds bounds: CGRect) -> CGRect {
    let leftMargin:CGFloat = 10
    let rightMargin:CGFloat = 10
    let topMargin:CGFloat = 10
    let bottomMargin:CGFloat = 10
    return CGRect(x: leftMargin, y: topMargin, width: bounds.size.width-leftMargin-rightMargin, height: bounds.size.height-topMargin-bottomMargin)
}
override func contentRect(forBounds bounds: CGRect) -> CGRect {
    let leftMargin:CGFloat = 5
    let rightMargin:CGFloat = 5
    let topMargin:CGFloat = 5
    let bottomMargin:CGFloat = 5
    return CGRect(x: leftMargin, y: topMargin, width: bounds.size.width-leftMargin-rightMargin, height: bounds.size.height-topMargin-bottomMargin)
}

How do I do redo (i.e. "undo undo") in Vim?

Also check out :undolist, which offers multiple paths through the undo history. This is useful if you accidentally type something after undoing too much.

Does Arduino use C or C++?

Both are supported. To quote the Arduino homepage,

The core libraries are written in C and C++ and compiled using avr-gcc

Note that C++ is a superset of C (well, almost), and thus can often look very similar. I am not an expert, but I guess that most of what you will program for the Arduino in your first year on that platform will not need anything but plain C.

Where can I find MySQL logs in phpMyAdmin?

If you are using XAMPP as your server, you'll find a logs directory as a child of the XAMPP directory. If you have not tried XAMPP, which runs on any system (Windows, Mac OS & Linux) find more here: http://www.apachefriends.org/en/xampp.html

HTTP GET in VBS

        strRequest = "<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" " &_
         "xmlns:tem=""http://tempuri.org/"">" &_
         "<soap:Header/>" &_
         "<soap:Body>" &_
            "<tem:Authorization>" &_
                "<tem:strCC>"&1234123412341234&"</tem:strCC>" &_
                "<tem:strEXPMNTH>"&11&"</tem:strEXPMNTH>" &_
                "<tem:CVV2>"&123&"</tem:CVV2>" &_
                "<tem:strYR>"&23&"</tem:strYR>" &_
                "<tem:dblAmount>"&1235&"</tem:dblAmount>" &_
            "</tem:Authorization>" &_
        "</soap:Body>" &_
        "</soap:Envelope>"

        EndPointLink = "http://www.trainingrite.net/trainingrite_epaysystem" &_
                "/trainingrite_epaysystem/tr_epaysys.asmx"



dim http
set http=createObject("Microsoft.XMLHTTP")
http.open "POST",EndPointLink,false
http.setRequestHeader "Content-Type","text/xml"

msgbox "REQUEST : " & strRequest
http.send strRequest

If http.Status = 200 Then
'msgbox "RESPONSE : " & http.responseXML.xml
msgbox "RESPONSE : " & http.responseText
responseText=http.responseText
else
msgbox "ERRCODE : " & http.status
End If

Call ParseTag(responseText,"AuthorizationResult")

Call CreateXMLEvidence(responseText,strRequest)

'Function to fetch the required message from a TAG
Function ParseTag(ResponseXML,SearchTag)

 ResponseMessage=split(split(split(ResponseXML,SearchTag)(1),"</")(0),">")(1)
 Msgbox ResponseMessage

End Function

'Function to create XML test evidence files
Function CreateXMLEvidence(ResponseXML,strRequest)

 Set fso=createobject("Scripting.FileSystemObject")
 Set qfile=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleResponse.xml",2)
 Set qfile1=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleReuest.xml",2)

 qfile.write ResponseXML
 qfile.close

 qfile1.write strRequest
 qfile1.close

End Function

how to rotate text left 90 degree and cell size is adjusted according to text in html

Without calculating height. Strict CSS and HTML. <span/> only for Chrome, because the chrome isn't able change text direction for <th/>.

_x000D_
_x000D_
th _x000D_
{_x000D_
  vertical-align: bottom;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
th span _x000D_
{_x000D_
  -ms-writing-mode: tb-rl;_x000D_
  -webkit-writing-mode: vertical-rl;_x000D_
  writing-mode: vertical-rl;_x000D_
  transform: rotate(180deg);_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <th><span>Rotated text by 90 deg.</span></th>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to get the PID of a process by giving the process name in Mac OS X ?

This is the shortest command I could find that does the job:

ps -ax | awk '/[t]he_app_name/{print $1}'

Putting brackets around the first letter stops awk from finding the awk process itself.

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I believe this error caused because of downloading SRC instead of BINARY from Maven site. Please make sure to download Binary zip.

Because the below path, you will get only when you download SRC:

M2_HOME C:\apache-maven-3.0.4\apache-maven\src

enter image description here

Python : Trying to POST form using requests

I was having problems here (i.e. sending form-data whilst uploading a file) until I used the following:

files = {'file': (filename, open(filepath, 'rb'), 'text/xml'),
         'Content-Disposition': 'form-data; name="file"; filename="' + filename + '"',
         'Content-Type': 'text/xml'}

That's the input that ended up working for me. In Chrome Dev Tools -> Network tab, I clicked the request I was interested in. In the Headers tab, there's a Form Data section, and it showed both the Content-Disposition and the Content-Type headers being set there.

I did NOT need to set headers in the actual requests.post() command for this to succeed (including them actually caused it to fail)

How do I change the root directory of an Apache server?

For Apache 2 on Linux Mint 17.3 Cinnamon 64-bit, the following works:

  1. In /etc/apache2/sites-available/ open the 000-default.conf file, and change the Document Root to the absolute path of your directory.

    sudo vim /etc/apache2/sites-available/000-default.conf

  2. In folder /etc/apache2/ open file httpd.conf, and add a <Directory> tag referencing your directory and containing the exact same settings as the tag for var/www.

     sudo vim /etc/apache2/apache2.conf
    

    On my machine it looked like this:


     <Directory /home/my_user_name/php/>
             Options Indexes FollowSymLinks
             AllowOverride All
             Require all granted
     </Directory>
    

Note: In the first step you probably want to change Document Root in the default-ssl.conf file as well for SSL purposes. But as far as I can tell, this isn't required to get a general development environment running.

How to get a file directory path from file path?

If you care target files to be symbolic link, firstly you can check it and get the original file. The if clause below may help you.

if [ -h $file ]
then
 base=$(dirname $(readlink $file))
else
 base=$(dirname $file)
fi

Setting href attribute at runtime

Set the href attribute with

$(selector).attr('href', 'url_goes_here');

and read it using

$(selector).attr('href');

Where "selector" is any valid jQuery selector for your <a> element (".myClass" or "#myId" to name the most simple ones).

Hope this helps !

How to convert NSData to byte array in iPhone?

Already answered, but to generalize to help other readers:

    //Here:   NSData * fileData;
    uint8_t * bytePtr = (uint8_t  * )[fileData bytes];

    // Here, For getting individual bytes from fileData, uint8_t is used.
    // You may choose any other data type per your need, eg. uint16, int32, char, uchar, ... .
    // Make sure, fileData has atleast number of bytes that a single byte chunk would need. eg. for int32, fileData length must be > 4 bytes. Makes sense ?

    // Now, if you want to access whole data (fileData) as an array of uint8_t
    NSInteger totalData = [fileData length] / sizeof(uint8_t);

    for (int i = 0 ; i < totalData; i ++)
    {
        NSLog(@"data byte chunk : %x", bytePtr[i]);
    }

Declaring array of objects

You can instantiate an array of "object type" in one line like this (just replace new Object() with your object):

var elements = 1000;
var MyArray = Array.apply(null, Array(elements)).map(function () { return new Object(); });

javax.servlet.ServletException cannot be resolved to a type in spring web app

It seems to me that eclipse doesn't recognize the java ee web api (servlets, el, and so on). If you're using maven and don't want to configure eclipse with a specified server runtime, put the dependecy below in your web project pom:

<dependency>  
    <groupId>javax</groupId>    
    <artifactId>javaee-web-api</artifactId>    
    <version>7.0</version> <!-- Put here the version of your Java EE app, in my case 7.0 -->
    <scope>provided</scope>
</dependency>

Using jQuery Fancybox or Lightbox to display a contact form

Have a look at: Greybox

It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.

You will find many information on how to use Greybox and also some great examples. Cheers Kara

How to create circular ProgressBar in android?

It's easy to create this yourself

In your layout include the following ProgressBar with a specific drawable (note you should get the width from dimensions instead). The max value is important here:

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:max="500"
    android:progress="0"
    android:progressDrawable="@drawable/circular" />

Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius instead of innerRadiusRatio) and thickness values.

circular (Pre Lollipop OR API Level < 21)

   <shape
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
   </shape>

circular ( >= Lollipop OR API Level >= 21)

    <shape
        android:useLevel="true"
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
     </shape>

useLevel is "false" by default in API Level 21 (Lollipop) .

Start Animation

Next in your code use an ObjectAnimator to animate the progress field of the ProgessBar of your layout.

ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();

Stop Animation

progressBar.clearAnimation();

P.S. unlike examples above, it give smooth animation.

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

How can I get the current class of a div with jQuery?

var classname=$('#div1').attr('class')

How do I configure git to ignore some files locally?

From the relevant Git documentation:

Patterns which are specific to a particular repository but which do not need to be shared with other related repositories (e.g., auxiliary files that live inside the repository but are specific to one user's workflow) should go into the $GIT_DIR/info/exclude file.

The .git/info/exclude file has the same format as any .gitignore file. Another option is to set core.excludesFile to the name of a file containing global patterns.

Note, if you already have unstaged changes you must run the following after editing your ignore-patterns:

git update-index --assume-unchanged <file-list>

Note on $GIT_DIR: This is a notation used all over the git manual simply to indicate the path to the git repository. If the environment variable is set, then it will override the location of whichever repo you're in, which probably isn't what you want.


Edit: Another way is to use:

git update-index --skip-worktree <file-list>

Reverse it by:

git update-index --no-skip-worktree <file-list>

VSCode: How to Split Editor Vertically

The key bindings has been changed with version 1.20:

SHIFT+ALT+0 for Linux.

Presumably the same works for Windows also and CMD+OPT+0 for Mac.

Android Studio was unable to find a valid Jvm (Related to MAC OS)

  1. Install newest JDK (8u102 current)
  2. Set envirionment variable STUDIO_JDK (java_home outputs the Java home dir and sed strips two folders to get the jdk dir)

    launchctl setenv STUDIO_JDK `/usr/libexec/java_home -version 1.8 | sed 's/\/Contents\/Home//g'`

  3. Launch Android Studio like you would normally

Set STUDIO_JDK on every reboot

The above steps only works for the current session. Here is how to create a plist file in /Library/LaunchDaemons that runs the above command on every boot:

sudo defaults write /Library/LaunchDaemons/com.google.studiojdk Label STUDIO_JDK
sudo defaults write /Library/LaunchDaemons/com.google.studiojdk ProgramArguments -array /bin/launchctl setenv STUDIO_JDK `/usr/libexec/java_home | sed 's/\/Contents\/Home//g'`
sudo defaults write /Library/LaunchDaemons/com.google.studiojdk RunAtLoad -bool TRUE

Found out about the plist trick thanks to http://www.dowdandassociates.com/blog/content/howto-set-an-environment-variable-in-mac-os-x-launchd-plist/

Which is better: <script type="text/javascript">...</script> or <script>...</script>

Both will work but xhtml standard requires you to specify the type too:

<script type="text/javascript">..</script> 

<!ELEMENT SCRIPT - - %Script;          -- script statements -->
<!ATTLIST SCRIPT
  charset     %Charset;      #IMPLIED  -- char encoding of linked resource --
  type        %ContentType;  #REQUIRED -- content type of script language --
  src         %URI;          #IMPLIED  -- URI for an external script --
  defer       (defer)        #IMPLIED  -- UA may defer execution of script --
  >

type = content-type [CI] This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.

Notices the emphasis above.

http://www.w3.org/TR/html4/interact/scripts.html

Note: As of HTML5 (far away), the type attribute is not required and is default.

How do I turn a String into a InputStreamReader in java?

I also found the apache commons IOUtils class , so :

InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));

How can I keep Bootstrap popovers alive while being hovered?

I know I'm kinda late to the party but I was looking for a solution for this..and I bumped into this post. Here is my take on this, maybe it will help some of you.

The html part:

<button type="button" class="btn btn-lg btn-danger" data-content="test" data-placement="right" data-toggle="popover" title="Popover title" >Hover to toggle popover</button><br>
// with custom html stored in a separate element, using "data-target"
<button type="button" class="btn btn-lg btn-danger" data-target="#custom-html" data-placement="right" data-toggle="popover" >Hover to toggle popover</button>

<div id="custom-html" style="display: none;">
    <strong>Helloooo!!</strong>
</div>

The js part:

$(function () {
        let popover = '[data-toggle="popover"]';

        let popoverId = function(element) {
            return $(element).popover().data('bs.popover').tip.id;
        }

        $(popover).popover({
            trigger: 'manual',
            html: true,
            animation: false
        })
        .on('show.bs.popover', function() {
            // hide all other popovers  
            $(popover).popover("hide");
        })
        .on("mouseenter", function() {
            // add custom html from element
            let target = $(this).data('target');
            $(this).popover().data('bs.popover').config.content = $(target).html();

            // show the popover
            $(this).popover("show");
            
            $('#' + popoverId(this)).on("mouseleave", () => {
               $(this).popover("hide");
            });

        }).on("mouseleave", function() {
            setTimeout(() => {
                if (!$("#" + popoverId(this) + ":hover").length) {
                    $(this).popover("hide");
                }
            }, 100);
        });
    })

What does the ??!??! operator do in C?

It's a C trigraph. ??! is |, so ??!??! is the operator ||

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

How to list records with date from the last 10 days?

Just generalising the query if you want to work with any given date instead of current date:

SELECT Table.date
  FROM Table 
  WHERE Table.date > '2020-01-01'::date - interval '10 day'

How to use a DataAdapter with stored procedure and parameter

Short and sweet...

DataTable dataTable = new DataTable();
try
{
   using (var adapter = new SqlDataAdapter("StoredProcedureName", ConnectionString))
   {
       adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
       adapter.SelectCommand.Parameters.Add("@ParameterName", SqlDbType.Int).Value = 123;
       adapter.Fill(dataTable);
   };
}
catch (Exception ex)
{
    Logger.Error("Error occured while fetching records from SQL server", ex);
}

In git how is fetch different than pull and how is merge different than rebase?

Merge - HEAD branch will generate a new commit, preserving the ancestry of each commit history. History can become polluted if merge commits are made by multiple people who work on the same branch in parallel.

Rebase - Re-writes the changes of one branch onto another without creating a new commit. The code history is simplified, linear and readable but it doesn't work with pull requests, because you can't see what minor changes someone made.

I would use git merge when dealing with feature-based workflow or if I am not familiar with rebase. But, if I want a more a clean, linear history then git rebase is more appropriate. For more details be sure to check out this merge or rebase article.

Where/How to getIntent().getExtras() in an Android Fragment?

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.

Remove Trailing Spaces and Update in Columns in SQL Server

To remove Enter:

Update [table_name] set
[column_name]=Replace(REPLACE([column_name],CHAR(13),''),CHAR(10),'')

To remove Tab:

Update [table_name] set
[column_name]=REPLACE([column_name],CHAR(9),'')

How to check if a std::thread is still running?

An easy solution is to have a boolean variable that the thread sets to true on regular intervals, and that is checked and set to false by the thread wanting to know the status. If the variable is false for to long then the thread is no longer considered active.

A more thread-safe way is to have a counter that is increased by the child thread, and the main thread compares the counter to a stored value and if the same after too long time then the child thread is considered not active.

Note however, there is no way in C++11 to actually kill or remove a thread that has hanged.

Edit How to check if a thread has cleanly exited or not: Basically the same technique as described in the first paragraph; Have a boolean variable initialized to false. The last thing the child thread does is set it to true. The main thread can then check that variable, and if true do a join on the child thread without much (if any) blocking.

Edit2 If the thread exits due to an exception, then have two thread "main" functions: The first one have a try-catch inside which it calls the second "real" main thread function. This first main function sets the "have_exited" variable. Something like this:

bool thread_done = false;

void *thread_function(void *arg)
{
    void *res = nullptr;

    try
    {
        res = real_thread_function(arg);
    }
    catch (...)
    {
    }

    thread_done = true;

    return res;
}

How to hide code from cells in ipython notebook visualized with nbviewer?

I wrote some code that accomplishes this, and adds a button to toggle visibility of code.

The following goes in a code cell at the top of a notebook:

from IPython.display import display
from IPython.display import HTML
import IPython.core.display as di # Example: di.display_html('<h3>%s:</h3>' % str, raw=True)

# This line will hide code by default when the notebook is exported as HTML
di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)

# This line will add a button to toggle visibility of code blocks, for use with the HTML export version
di.display_html('''<button onclick="jQuery('.input_area').toggle(); jQuery('.prompt').toggle();">Toggle code</button>''', raw=True)

You can see an example of how this looks in NBviewer here.

Update: This will have some funny behavior with Markdown cells in Jupyter, but it works fine in the HTML export version of the notebook.

Android button background color

In addition to Mark Proctor's answer:

If you want to keep the default styling, but have a conditional coloring on the button, just set the backgroundTint property like so:

android:backgroundTint="@drawable/styles_mybutton"

Create the associated file /res/drawable/styles_mybutton.xml, then use the following template and change the colors as per your tastes:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Disabled state-->
    <item android:state_enabled="false"
        android:color="@android:color/white">
    </item>
    <!-- Default state-->
    <item
        android:color="#cfc">
    </item>
</selector>

Vertically align an image inside a div with responsive height

Use this css, as you already have the markup for it:

.img-container {
    position: absolute;
    top: 50%;
    left: 50%;
}

.img-container > img {
  margin-top:-50%;
  margin-left:-50%;  
}

Here is a working JsBin: http://jsbin.com/ihilUnI/1/edit

This solution only works for square images (because a percentage margin-top value depends on the width of the container, not the height). For random-size images, you can do the following:

.img-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); /* add browser-prefixes */
}

Working JsBin solution: http://jsbin.com/ihilUnI/2/edit

Remove all whitespace in a string

An alternative is to use regular expressions and match these strange white-space characters too. Here are some examples:

Remove ALL spaces in a string, even between words:

import re
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)

Remove spaces in the BEGINNING of a string:

import re
sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)

Remove spaces in the END of a string:

import re
sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)

Remove spaces both in the BEGINNING and in the END of a string:

import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)

Remove ONLY DUPLICATE spaces:

import re
sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))

(All examples work in both Python 2 and Python 3)

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

Setting your provisioning profile moved. It confounded me for a while until I found it also.

  1. Select your project file (to open target)
  2. Click on the "Build Settings" tab
  3. Scroll down to "Code Signing" and see the new "Provisioning Profile" section there.

enter image description here

How to uncheck a radio button?

Try this, this will do the trick:

        $(document).ready(function() {
           $("input[type='radio']").mousedown(function(e) {
                if ($(this).attr("checked") == true) {
                   setTimeout("$('input[id=" + $(this).attr('id') + "]').removeAttr('checked');", 200);}
                else {
                    return true
                }
            });
        });

OnclientClick and OnClick is not working at the same time?

From this article on web.archive.org :

The trick is to use the OnClientClick and UseSubmitBehavior properties of the button control. There are other methods, involving code on the server side to add attributes, but I think the simplicity of doing it this way is much more attractive:

<asp:Button runat="server" ID="BtnSubmit"  OnClientClick="this.disabled = true; this.value = 'Submitting...';"   UseSubmitBehavior="false"  OnClick="BtnSubmit_Click"  Text="Submit Me!" />

OnClientClick allows you to add client side OnClick script. In this case, the JavaScript will disable the button element and change its text value to a progress message. When the postback completes, the newly rendered page will revert the button back its initial state without any additional work.

The one pitfall that comes with disabling a submit button on the client side is that it will cancel the browser’s submit, and thus the postback. Setting the UseSubmitBehavior property to false tells .NET to inject the necessary client script to fire the postback anyway, instead of relying on the browser’s form submission behavior. In this case, the code it injects would be:

__doPostBack('BtnSubmit','')

This is added to the end of our OnClientClick code, giving us this rendered HTML:

<input type="button" name="BtnSubmit"  onclick="this.disabled = true; this.value ='Submitting...';__doPostBack('BtnSubmit','')"  value="Submit Me!" id="BtnSubmit" />

This gives a nice button disable effect and processing text, while the postback completes.

How to change the default charset of a MySQL table?

You can change the default with an alter table set default charset but that won't change the charset of the existing columns. To change that you need to use a alter table modify column.

Changing the charset of a column only means that it will be able to store a wider range of characters. Your application talks to the db using the mysql client so you may need to change the client encoding as well.

How to stop C++ console application from exiting immediately?

just use cin.ignore() right before return 0; twice

main()
  {
  //your codes 

  cin.ignore();
  cin.ignore();

  return 0;
  }

thats all

Android: Is it possible to display video thumbnails?

Try this it's working for me

RequestOptions requestOptions = new RequestOptions();
 Glide.with(getContext())
      .load("video_url")
      .apply(requestOptions)
      .thumbnail(Glide.with(getContext()).load("video_url"))
      .into("yourimageview");

Attach the Java Source Code

Just remove the JRE in Preferences>Java>Installed JRE and add the folder of your JDK. If you just add JDK but still leave JRE it won't work

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

Extract string between two strings in java

Your regex looks correct, but you're splitting with it instead of matching with it. You want something like this:

// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Add a "sort" to a =QUERY statement in Google Spreadsheets

You can use ORDER BY clause to sort data rows by values in columns. Something like

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C, D")

If you’d like to order by some columns descending, others ascending, you can add desc/asc, ie:

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C desc, D")

Listing all extras of an Intent

Sorry if this is too verbose or too late, but this was the only way I could find to get the job done. The most complicating factor was the fact that java does not have pass by reference functions, so the get---Extra methods need a default to return and cannot modify a boolean value to tell whether or not the default value is being returned by chance, or because the results were not favorable. For this purpose, it would have been nicer to have the method raise an exception than to have it return a default.

I found my information here: Android Intent Documentation.

    //substitute your own intent here
    Intent intent = new Intent();
    intent.putExtra("first", "hello");
    intent.putExtra("second", 1);
    intent.putExtra("third", true);
    intent.putExtra("fourth", 1.01);
    // convert the set to a string array

Set Documentation

    String[] anArray = {};
    Set<String> extras1 = (Set<String>) intent.getExtras().keySet();
    String[] extras = (String[]) extras1.toArray(anArray);
    // an arraylist to hold all of the strings
    // rather than putting strings in here, you could display them
    ArrayList<String> endResult = new ArrayList<String>();
    for (int i=0; i<extras.length; i++) {
        //try using as a String
        String aString = intent.getStringExtra(extras[i]);
        // is a string, because the default return value for a non-string is null
        if (aString != null) {
            endResult.add(extras[i] + " : " + aString);
        }
        // not a string
        else {
            // try the next data type, int
            int anInt = intent.getIntExtra(extras[i], 0);
            // is the default value signifying that either it is not an int or that it happens to be 0 
            if (anInt == 0) {
                // is an int value that happens to be 0, the same as the default value
                if (intent.getIntExtra(extras[i], 1) != 1) {
                    endResult.add(extras[i] + " : " + Integer.toString(anInt));
                }
                // not an int value
                // try double (also works for float)
                else {
                    double aDouble = intent.getDoubleExtra(extras[i], 0.0);
                    // is the same as the default value, but does not necessarily mean that it is not double
                    if (aDouble == 0.0) {
                        // just happens that it was 0.0 and is a double
                        if (intent.getDoubleExtra(extras[i], 1.0) != 1.0) {
                            endResult.add(extras[i] + " : " + Double.toString(aDouble));
                        }
                        // keep looking...
                        else {
                            // lastly check for boolean
                            boolean aBool = intent.getBooleanExtra(extras[i], false);
                            // same as default, but not necessarily not a bool (still could be a bool)
                            if (aBool == false) {
                                // it is a bool!
                                if (intent.getBooleanExtra(extras[i], true) != true) {
                                    endResult.add(extras[i] + " : " + Boolean.toString(aBool));
                                }
                                else {
                                    //well, the road ends here unless you want to add some more data types
                                }
                            }
                            // it is a bool
                            else {
                                endResult.add(extras[i] + " : " + Boolean.toString(aBool));
                            }
                        }
                    }
                    // is a double
                    else {
                        endResult.add(extras[i] + " : " + Double.toString(aDouble));
                    }
                }
            }
            // is an int value
            else {
                endResult.add(extras[i] + " : " + Integer.toString(anInt));
            }
        }
    }
    // to display at the end
    for (int i=0; i<endResult.size(); i++) {
        Toast.makeText(this, endResult.get(i), Toast.LENGTH_SHORT).show();
    }

jQuery window scroll event does not fire up

Your CSS is actually setting the rest of the document to not show overflow therefore the document itself isn't scrolling. The easiest fix for this is bind the event to the thing that is scrolling, which in your case is div#page.

So its easy as changing:

$(document).scroll(function() {  // OR  $(window).scroll(function() {
    didScroll = true;
});

to

$('div#page').scroll(function() {
    didScroll = true;
});

How to add 10 minutes to my (String) time?

You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.

String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());

Output :

14:10
14:20

How to determine the current shell I'm working on

echo $$ # Gives the Parent Process ID 
ps -ef | grep $$ | awk '{print $8}' # Use the PID to see what the process is.

From How do you know what your current shell is?.

Is there a typescript List<> and/or Map<> class/library?

It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.

Map:

class Map<T> {
    private items: { [key: string]: T };

    constructor() {
        this.items = {};
    }

    add(key: string, value: T): void {
        this.items[key] = value;
    }

    has(key: string): boolean {
        return key in this.items;
    }

    get(key: string): T {
        return this.items[key];
    }
}

List:

class List<T> {
    private items: Array<T>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(value);
    }

    get(index: number): T {
        return this.items[index];
    }
}

I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...

As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:

class ListItem<T> {
    private list: List<T>;
    private index: number;

    public value: T;

    constructor(list: List<T>, value: T, index: number) {
        this.list = list;
        this.index = index;
        this.value = value;
    }

    prev(): ListItem<T> {
        return this.list.get(this.index - 1);
    }

    next(): ListItem<T> {
        return this.list.get(this.index + 1);   
    }
}

class List<T> {
    private items: Array<ListItem<T>>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(new ListItem<T>(this, value, this.size()));
    }

    get(index: number): ListItem<T> {
        return this.items[index];
    }
}

Here too you're looking at untested code..

Hope this helps.


Edit - as this answer still gets some attention

Javascript has a native Map object so there's no need to create your own:

let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from somewhere.com. Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

What is the difference between encode/decode?

There are a few encodings that can be used to de-/encode from str to str or from unicode to unicode. For example base64, hex or even rot13. They are listed in the codecs module.

Edit:

The decode message on a unicode string can undo the corresponding encode operation:

In [1]: u'0a'.decode('hex')
Out[1]: '\n'

The returned type is str instead of unicode which is unfortunate in my opinion. But when you are not doing a proper en-/decode between str and unicode this looks like a mess anyway.

Storing money in a decimal column - what precision and scale?

If you are looking for a one-size-fits-all, I'd suggest DECIMAL(19, 4) is a popular choice (a quick Google bears this out). I think this originates from the old VBA/Access/Jet Currency data type, being the first fixed point decimal type in the language; Decimal only came in 'version 1.0' style (i.e. not fully implemented) in VB6/VBA6/Jet 4.0.

The rule of thumb for storage of fixed point decimal values is to store at least one more decimal place than you actually require to allow for rounding. One of the reasons for mapping the old Currency type in the front end to DECIMAL(19, 4) type in the back end was that Currency exhibited bankers' rounding by nature, whereas DECIMAL(p, s) rounded by truncation.

An extra decimal place in storage for DECIMAL allows a custom rounding algorithm to be implemented rather than taking the vendor's default (and bankers' rounding is alarming, to say the least, for a designer expecting all values ending in .5 to round away from zero).

Yes, DECIMAL(24, 8) sounds like overkill to me. Most currencies are quoted to four or five decimal places. I know of situations where a decimal scale of 8 (or more) is required but this is where a 'normal' monetary amount (say four decimal places) has been pro rata'd, implying the decimal precision should be reduced accordingly (also consider a floating point type in such circumstances). And no one has that much money nowadays to require a decimal precision of 24 :)

However, rather than a one-size-fits-all approach, some research may be in order. Ask your designer or domain expert about accounting rules which may be applicable: GAAP, EU, etc. I vaguely recall some EU intra-state transfers with explicit rules for rounding to five decimal places, therefore using DECIMAL(p, 6) for storage. Accountants generally seem to favour four decimal places.


PS Avoid SQL Server's MONEY data type because it has serious issues with accuracy when rounding, among other considerations such as portability etc. See Aaron Bertrand's blog.


Microsoft and language designers chose banker's rounding because hardware designers chose it [citation?]. It is enshrined in the Institute of Electrical and Electronics Engineers (IEEE) standards, for example. And hardware designers chose it because mathematicians prefer it. See Wikipedia; to paraphrase: The 1906 edition of Probability and Theory of Errors called this 'the computer's rule' ("computers" meaning humans who perform computations).

Express.js Response Timeout

Before you set your routes, add the code:

app.all('*', function(req, res, next) {
    setTimeout(function() {
        next();
    }, 120000); // 120 seconds
});

Servlet for serving static content

Checked for Tomcat 8.x: static resources work OK if root servlet map to "". For servlet 3.x it could be done by @WebServlet("")

How do you check that a number is NaN in JavaScript?

I use underscore's isNaN function because in JavaScript:

isNaN(undefined) 
-> true

At the least, be aware of that gotcha.

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

Adding a dictionary to another

foreach(var newAnimal in NewAnimals)
    Animals.Add(newAnimal.Key,newAnimal.Value)

Note: this throws an exception on a duplicate key.


Or if you really want to go the extension method route(I wouldn't), then you could define a general AddRange extension method that works on any ICollection<T>, and not just on Dictionary<TKey,TValue>.

public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
    if(target==null)
      throw new ArgumentNullException(nameof(target));
    if(source==null)
      throw new ArgumentNullException(nameof(source));
    foreach(var element in source)
        target.Add(element);
}

(throws on duplicate keys for dictionaries)

Bootstrap 3 truncate long text inside rows of a table in a responsive way

I'm using bootstrap.
I used css parameters.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

and bootstrap grid system parameters, like this.

<th class="col-sm-2">Name</th>

<td class="col-sm-2">hoge</td>

Dismissing a Presented View Controller

This is a lot of baloney. Delegation is fine when it is needed but if it makes the code more complex -- and it does -- then there needs to be a reason for it.

I'm sure Apple has its reasons. But it is clearer and more concise to simply have the presented VC do the dismiss unless there is a true reason for doing otherwise and no one here as of today has presented one that I can see.

Protocols are excellent when they're needed but object oriented design was never about having modules communicating unnecessarily with each other.

Tom Love (co-developer of Objective C) once commented that Objective C was "elegant", "small", "crisp" and "well-defined" (when comparing with C++). Easy for him to say. Delegation is a useful feature that seems to have been over-used "just because", and while I like working in the language, I dread the idea of felling compelled to use unnecessary syntax to make things more complex than they have to be.

How to change the default GCC compiler in Ubuntu?

As @Tommy suggested, you should use update-alternatives.
It assigns values to every software of a family, so that it defines the order in which the applications will be called.

It is used to maintain different versions of the same software on a system. In your case, you will be able to use several declinations of gcc, and one will be favoured.

To figure out the current priorities of gcc, type in the command pointed out by @tripleee's comment:

update-alternatives --query gcc

Now, note the priority attributed to gcc-4.4 because you'll need to give a higher one to gcc-3.3.
To set your alternatives, you should have something like this (assuming your gcc installation is located at /usr/bin/gcc-3.3, and gcc-4.4's priority is less than 50):

update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-3.3 50

--edit--

Finally, you can also use the interactive interface of update-alternatives to easily switch between versions. Type update-alternatives --config gcc to be asked to choose the gcc version you want to use among those installed.

--edit 2 --

Now, to fix the CXX environment variable systemwide, you need to put the line indicated by @DipSwitch's in your .bashrc file (this will apply the change only for your user, which is safer in my opinion):

echo 'export CXX=/usr/bin/gcc-3.3' >> ~/.bashrc

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

In my case, this has been resolved by going to control panel > java > security > then add url in the exception site list. Then apply. Test again the site and it should now allow you to run the local java.

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

Cut Java String at a number of character

StringUtils.abbreviate("abcdefg", 6);

This will give you the following result: abc...

Where 6 is the needed length, and "abcdefg" is the string that needs to be abbrevieted.

Why is there no Constant feature in Java?

There would be two ways to define constants - const and static final, with the exact same semantics. Furthermore static final describes the behaviour better than const

Pass value to iframe from a window

First, you need to understand that you have two documents: The frame and the container (which contains the frame).

The main obstacle with manipulating the frame from the container is that the frame loads asynchronously. You can't simply access it any time, you must know when it has finished loading. So you need a trick. The usual solution is to use window.parent in the frame to get "up" (into the document which contains the iframe tag).

Now you can call any method in the container document. This method can manipulate the frame (for example call some JavaScript in the frame with the parameters you need). To know when to call the method, you have two options:

  1. Call it from body.onload of the frame.

  2. Put a script element as the last thing into the HTML content of the frame where you call the method of the container (left as an exercise for the reader).

So the frame looks like this:

<script>
function init() { window.parent.setUpFrame(); return true; }
function yourMethod(arg) { ... }
</script>
<body onload="init();">...</body>

And the container like this:

<script>
function setUpFrame() { 
    var frame = window.frames['frame-id'];
    frame.yourMethod('hello');
}
</script>
<body><iframe name="frame-id" src="..."></iframe></body>

How can I get column names from a table in Oracle?

For MySQL, use

SELECT column_name 
FROM information_schema.columns 
WHERE 
table_schema = 'Schema' AND table_name = 'Table_Name'

how to start stop tomcat server using CMD?

This is what I used to start and stop tomcat 7.0.29, using ant 1.8.2. Works fine for me, but leaves the control in the started server window. I have not tried it yet, but I think if I change the "/K" in the startup sequence to "/C", it may not even do that.

<target name="tomcat-stop">
    <exec dir="${appserver.home}/bin" executable="cmd">
        <arg line="/C start cmd.exe /C shutdown.bat"/>
    </exec>
</target>



<target name="tomcat-start" depends="tomcat-stop" >
    <exec dir="${appserver.home}/bin" executable="cmd">
        <arg line="/K start cmd.exe /C startup.bat"/>
    </exec>

</target>

Simple Android RecyclerView example

Here's a much newer Kotlin solution for this which is much simpler than many of the answers written here, it uses anonymous class.

val items = mutableListOf<String>()

inner class ItemHolder(view: View): RecyclerView.ViewHolder(view) {
    var textField: TextView = view.findViewById(android.R.id.text1) as TextView
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    rvitems.layoutManager = LinearLayoutManager(context)
    rvitems.adapter = object : RecyclerView.Adapter<ItemHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
            return ItemHolder(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false))
        }

        override fun getItemCount(): Int {
            return items.size
        }

        override fun onBindViewHolder(holder: ItemHolder, position: Int) {
            holder.textField.text = items[position]
            holder.textField.setOnClickListener {
                Toast.makeText(context, "Clicked $position", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

I took the liberty to use android.R.layout.simple_list_item_1 as it's simpler. I wanted to simplify it even further and put ItemHolder as an inner class but couldn't quite figure out how to reference it in a type in the outer class parameter.

Angular: How to download a file from HttpClient?

Using Blob as a source for an img:

template:

<img [src]="url">

component:

 public url : SafeResourceUrl;

 constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
   this.getImage('/api/image.jpg').subscribe(x => this.url = x)
 }

 public getImage(url: string): Observable<SafeResourceUrl> {
   return this.http
     .get(url, { responseType: 'blob' })
     .pipe(
       map(x => {
         const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
         return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
       }),
     );
 }

Further reference about trusting save values

Why is "throws Exception" necessary when calling a function?

void show() throws Exception
{
    throw new Exception("my.own.Exception");
}

As there is checked exception in show() method , which is not being handled in that method so we use throws keyword for propagating the Exception.

void show2() throws Exception //Why throws is necessary here ?
{
show();
}

Since you are using the show() method in show2() method and you have propagated the exception atleast you should be handling here. If you are not handling the Exception here , then you are using throws keyword. So that is the reason for using throws keyword at the method signature.

How can I pass a Bitmap object from one activity to another

Compress and Send Bitmap

The accepted answer will crash when the Bitmap is too large. I believe it's a 1MB limit. The Bitmap must be compressed into a different file format such as a JPG represented by a ByteArray, then it can be safely passed via an Intent.

Implementation

The function is contained in a separate thread using Kotlin Coroutines because the Bitmap compression is chained after the Bitmap is created from an url String. The Bitmap creation requires a separate thread in order to avoid Application Not Responding (ANR) errors.

Concepts Used

  • Kotlin Coroutines notes.
  • The Loading, Content, Error (LCE) pattern is used below. If interested you can learn more about it in this talk and video.
  • LiveData is used to return the data. I've compiled my favorite LiveData resource in these notes.
  • In Step 3, toBitmap() is a Kotlin extension function requiring that library to be added to the app dependencies.

Code

1. Compress Bitmap to JPG ByteArray after it has been created.

Repository.kt

suspend fun bitmapToByteArray(url: String) = withContext(Dispatchers.IO) {
    MutableLiveData<Lce<ContentResult.ContentBitmap>>().apply {
        postValue(Lce.Loading())
        postValue(Lce.Content(ContentResult.ContentBitmap(
            ByteArrayOutputStream().apply {
                try {                     
                    BitmapFactory.decodeStream(URL(url).openConnection().apply {
                        doInput = true
                        connect()
                    }.getInputStream())
                } catch (e: IOException) {
                   postValue(Lce.Error(ContentResult.ContentBitmap(ByteArray(0), "bitmapToByteArray error or null - ${e.localizedMessage}")))
                   null
                }?.compress(CompressFormat.JPEG, BITMAP_COMPRESSION_QUALITY, this)
           }.toByteArray(), "")))
        }
    }

ViewModel.kt

//Calls bitmapToByteArray from the Repository
private fun bitmapToByteArray(url: String) = liveData {
    emitSource(switchMap(repository.bitmapToByteArray(url)) { lce ->
        when (lce) {
            is Lce.Loading -> liveData {}
            is Lce.Content -> liveData {
                emit(Event(ContentResult.ContentBitmap(lce.packet.image, lce.packet.errorMessage)))
            }
            is Lce.Error -> liveData {
                Crashlytics.log(Log.WARN, LOG_TAG,
                        "bitmapToByteArray error or null - ${lce.packet.errorMessage}")
            }
        }
    })
}

2. Pass image as ByteArray via an Intent.

In this sample it's passed from a Fragment to a Service. It's the same concept if being shared between two Activities.

Fragment.kt

ContextCompat.startForegroundService(
    context!!,
    Intent(context, AudioService::class.java).apply {
        action = CONTENT_SELECTED_ACTION
        putExtra(CONTENT_SELECTED_BITMAP_KEY, contentPlayer.image)
    })

3. Convert ByteArray back to Bitmap.

Utils.kt

fun ByteArray.byteArrayToBitmap(context: Context) =
    run {
        BitmapFactory.decodeByteArray(this, BITMAP_OFFSET, size).run {
            if (this != null) this
            // In case the Bitmap loaded was empty or there is an error I have a default Bitmap to return.
            else AppCompatResources.getDrawable(context, ic_coinverse_48dp)?.toBitmap()
        }
    }

How can I show/hide component with JSF?

check this below code. this is for dropdown menu. In this if we select others then the text box will show otherwise text box will hide.

function show_txt(arg,arg1)
{
if(document.getElementById(arg).value=='other')
{
document.getElementById(arg1).style.display="block";
document.getElementById(arg).style.display="none";
}
else
{
document.getElementById(arg).style.display="block";
document.getElementById(arg1).style.display="none";
}
}
The HTML code here :

<select id="arg" onChange="show_txt('arg','arg1');">
<option>yes</option>
<option>No</option>
<option>Other</option>
</select>
<input type="text" id="arg1" style="display:none;">

or you can check this link click here

Does Python have “private” variables in classes?

About sources (to change the access rights and thus bypass language encapsulation like java or C ++): You don't always have the sources and EVEN if you do, the sources are managed by a system that only allows certain programmers to access a source (in a professional context). Often, every programmer is responsible for certain classes and therefore knows what he can and cannot do. The source manager also locks the sources being modified and of course, manages the access rights of programmers.

So i trust more in software than in human, by experience. So convention is good but MULTIPLE protections are better, like access management (real private variable) + sources management.

How to get multiple selected values of select box in php?

Change:

<select name="select2" ...

To:

<select name="select2[]" ...

How can I scroll a div to be visible in ReactJS?

I'm just adding another bit of info for others searching for a Scroll-To capability in React. I had tied several libraries for doing Scroll-To for my app, and none worked from my use case until I found react-scrollchor, so I thought I'd pass it on. https://github.com/bySabi/react-scrollchor

How can I decrypt a password hash in PHP?

Use the password_verify() function

if (password_vertify($inputpassword, $row['password'])) {
  print "Logged in";
else {
    print "Password Incorrect";
}

Member '<method>' cannot be accessed with an instance reference

I know this is an old thread, but I just spent 3 hours trying to figure out what my issue was. I ordinarily know what this error means, but you can run into this in a more subtle way as well. My issue was my client class (the one calling a static method from an instance class) had a property of a different type but named the same as the static method. The error reported by the compiler was the same as reported here, but the issue was basically name collision.

For anyone else getting this error and none of the above helps, try fully qualifying your instance class with the namespace name. ..() so the compiler can see the exact name you mean.

Calling the base class constructor from the derived class constructor

but I can't initialize my derived class, I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ?? so I'm thinking maybe in the PetStore default constructor I can call Farm()... so any Idea ???

Don't panic.

Farm constructor will be called in the constructor of PetStore, automatically.

See the base class inheritance calling rules: What are the rules for calling the superclass constructor?

How do I get a plist as a Dictionary in Swift?

Simple struct to access plist file (Swift 2.0)

struct Configuration {      
  static let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")!
  static let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]

  static let someValue = dict["someKey"] as! String
}

Usage:

print("someValue = \(Configuration.someValue)")

Writing to a new file if it doesn't exist, and appending to a file if it does

Using the pathlib module (python's object-oriented filesystem paths)

Just for kicks, this is perhaps the latest pythonic version of the solution.

from pathlib import Path 

path = Path(f'{player}.txt')
path.touch()  # default exists_ok=True
with path.open('a') as highscore:
   highscore.write(f'Username:{player}')

'NoneType' object is not subscriptable?

Don't use list as a variable name for it shadows the builtin.

And there is no need to determine the length of the list. Just iterate over it.

def printer(data):
    for element in data:
        print(element[0])

Just an addendum: Looking at the contents of the inner lists I think they might be the wrong data structure. It looks like you want to use a dictionary instead.

Check date with todays date

Using Joda Time this can be simplified to:

DateMidnight startDate = new DateMidnight(startYear, startMonth, startDay);
if (startDate.isBeforeNow())
{
    // startDate is before now
    // do something...
}

How to check java bit version on Linux?

Go to this JVM online test and run it.

Then check the architecture displayed: x86_64 means you have the 64bit version installed, otherwise it's 32bit.

.NET: Simplest way to send POST with data and read response

I know this is an old thread, but hope it helps some one.

public static void SetRequest(string mXml)
{
    HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://dork.com/service");
    webRequest.Method = "POST";
    webRequest.Headers["SOURCE"] = "WinApp";

    // Decide your encoding here

    //webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentType = "text/xml; charset=utf-8";

    // You should setContentLength
    byte[] content = System.Text.Encoding.UTF8.GetBytes(mXml);
    webRequest.ContentLength = content.Length;

    var reqStream = await webRequest.GetRequestStreamAsync();
    reqStream.Write(content, 0, content.Length);

    var res = await httpRequest(webRequest);
}

How to set a parameter in a HttpServletRequest?

From your question, I think what you are trying to do is to store something (an object, a string...) to foward it then to another servlet, using RequestDispatcher(). To do this you don't need to set a paramater but an attribute using

void setAttribute(String name, Object o);

and then

Object getAttribute(String name);

adb command not found in linux environment

creating a symbolic link was the solution for me either. However before working I had to grant access and execute rights to the created symbolic links.

I am not sure if it was @eaykin's answer or @crazymacleod's that worked for me, as I did both before finding the above mentioned solution.

Thanks!

Android Min SDK Version vs. Target SDK Version

If you get some compile errors for example:

<uses-sdk
            android:minSdkVersion="10"
            android:targetSdkVersion="15" />

.

private void methodThatRequiresAPI11() {
        BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
                options.inSampleSize = 8;    // API Level 1
                options.inBitmap = bitmap;   // **API Level 11**
        //...
    }

You get compile error:

Field requires API level 11 (current min is 10): android.graphics.BitmapFactory$Options#inBitmap

Since version 17 of Android Development Tools (ADT) there is one new and very useful annotation @TargetApi that can fix this very easily. Add it before the method that is enclosing the problematic declaration:

@TargetApi
private void methodThatRequiresAPI11() {            
  BitmapFactory.Options options = new BitmapFactory.Options();
      options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
      options.inSampleSize = 8;    // API Level 1

      // This will avoid exception NoSuchFieldError (or NoSuchMethodError) at runtime. 
      if (Integer.valueOf(android.os.Build.VERSION.SDK) >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        options.inBitmap = bitmap;   // **API Level 11**
            //...
      }
    }

No compile errors now and it will run !

EDIT: This will result in runtime error on API level lower than 11. On 11 or higher it will run without problems. So you must be sure you call this method on an execution path guarded by version check. TargetApi just allows you to compile it but you run it on your own risk.

no module named zlib

By default when you configuring Python source, zlib module is disabled, so you can enable it using option --with-zlib when you configure it. So it becomes

./configure --with-zlib

Is there a method that tells my program to quit?

In Python 3 there is an exit() function:

elif choice == "q":
    exit()

How to find patterns across multiple lines using grep?

With silver searcher:

ag 'abc.*(\n|.)*efg'

similar to ring bearer's answer, but with ag instead. Speed advantages of silver searcher could possibly shine here.

Android, How can I Convert String to Date?

It could be a good idea to be careful with the Locale upon which c.getTime().toString(); depends.

One idea is to store the time in seconds (e.g. UNIX time). As an int you can easily compare it, and then you just convert it to string when displaying it to the user.

syntax error when using command line in python

Running from the command line means running from the terminal or DOS shell. You are running it from Python itself.

Sort objects in an array alphabetically on one property of the array

You have to pass a function that accepts two parameters, compares them, and returns a number, so assuming you wanted to sort them by ID you would write...

objArray.sort(function(a,b) {
    return a.id-b.id;
});
// objArray is now sorted by Id

How to embed HTML into IPython output?

Related: While constructing a class, def _repr_html_(self): ... can be used to create a custom HTML representation of its instances:

class Foo:
    def _repr_html_(self):
        return "Hello <b>World</b>!"

o = Foo()
o

will render as:

Hello World!

For more info refer to IPython's docs.

An advanced example:

from html import escape # Python 3 only :-)

class Todo:
    def __init__(self):
        self.items = []

    def add(self, text, completed):
        self.items.append({'text': text, 'completed': completed})

    def _repr_html_(self):
        return "<ol>{}</ol>".format("".join("<li>{} {}</li>".format(
            "?" if item['completed'] else "?",
            escape(item['text'])
        ) for item in self.items))

my_todo = Todo()
my_todo.add("Buy milk", False)
my_todo.add("Do homework", False)
my_todo.add("Play video games", True)

my_todo

Will render:

  1. ? Buy milk
  2. ? Do homework
  3. ? Play video games

How to redirect verbose garbage collection output to a file?

From the output of java -X:

    -Xloggc:<file>    log GC status to a file with time stamps

Documented here:

-Xloggc:filename

Sets the file to which verbose GC events information should be redirected for logging. The information written to this file is similar to the output of -verbose:gc with the time elapsed since the first GC event preceding each logged event. The -Xloggc option overrides -verbose:gc if both are given with the same java command.

Example:

    -Xloggc:garbage-collection.log

So the output looks something like this:

0.590: [GC 896K->278K(5056K), 0.0096650 secs]
0.906: [GC 1174K->774K(5056K), 0.0106856 secs]
1.320: [GC 1670K->1009K(5056K), 0.0101132 secs]
1.459: [GC 1902K->1055K(5056K), 0.0030196 secs]
1.600: [GC 1951K->1161K(5056K), 0.0032375 secs]
1.686: [GC 1805K->1238K(5056K), 0.0034732 secs]
1.690: [Full GC 1238K->1238K(5056K), 0.0631661 secs]
1.874: [GC 62133K->61257K(65060K), 0.0014464 secs]

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

What is the size of a boolean variable in Java?

On a side note...

If you are thinking about using an array of Boolean objects, don't. Use a BitSet instead - it has some performance optimisations (and some nice extra methods, allowing you to get the next set/unset bit).

AngularJS ui router passing data between states without URL

We can use params, new feature of the UI-Router:

API Reference / ui.router.state / $stateProvider

params A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.

See the part: "...or defines additional non-url parameters..."

So the state def would be:

$stateProvider
  .state('home', {
    url: "/home",
    templateUrl: 'tpl.html',
    params: { hiddenOne: null, }
  })

Few examples form the doc mentioned above:

// define a parameter's default value
params: {
  param1: { value: "defaultValue" }
}
// shorthand default values
params: {
  param1: "defaultValue",
  param2: "param2Default"
}

// param will be array []
params: {
  param1: { array: true }
}

// handling the default value in url:
params: {
  param1: {
    value: "defaultId",
    squash: true
} }
// squash "defaultValue" to "~"
params: {
  param1: {
    value: "defaultValue",
    squash: "~"
  } }

EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info

Here is an example of a state definition:

 $stateProvider
  .state('home', {
      url: "/home",
      params : { veryLongParamHome: null, },
      ...
  })
  .state('parent', {
      url: "/parent",
      params : { veryLongParamParent: null, },
      ...
  })
  .state('parent.child', { 
      url: "/child",
      params : { veryLongParamChild: null, },
      ...
  })

This could be a call using ui-sref:

<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
  })">home</a>

<a ui-sref="parent({ 
    veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
  })">parent</a>

<a ui-sref="parent.child({
    veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',  
    veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
  })">parent.child</a>

Check the example here

Using comma as list separator with AngularJS

Also:

angular.module('App.filters', [])
    .filter('joinBy', function () {
        return function (input,delimiter) {
            return (input || []).join(delimiter || ',');
        };
    });

And in template:

{{ itemsArray | joinBy:',' }}

What is the best way to access redux store outside a react component?

You can use store object that is returned from createStore function (which should be already used in your code in app initialization). Than you can use this object to get current state with store.getState() method or store.subscribe(listener) to subscribe to store updates.

You can even save this object to window property to access it from any part of application if you really want it (window.store = store)

More info can be found in the Redux documentation .

Dynamically update values of a chartjs chart

Showing realtime update chartJS

function add_data(chart, label, data) 
      {
        var today = new Date();
        var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
        myLineChart.data.datasets[0].data.push(Math.random() * 100);
        myLineChart.data.datasets[1].data.push(Math.random() * 100);
        myLineChart.data.labels.push(time)
        myLineChart.update();
      }
      setInterval(add_data, 10000); //milisecond

full code , you can download in description link

Cannot find vcvarsall.bat when running a Python script

THIS IS AN UP TO DATE ANSWER FOR WINDOWS USERS - VERY SIMPLE SOLUTION.

As pointed out by other, the problem is that python/cython etc. tries to find the same compiler they were built from, but this compiler does not exist on the computer. Most of the time, this compiler is a version of visual studio (2008, 2010 or 2013), but either such a compiler is not installed, or a newer version is installed and the system prevents from installing an older one. So, the solution is simple:

1) look at C:\Program Files (x86) and see if there is an installed version of Microsoft visual studio, and if it is newer than the version from which Python has been built. If not, install(/update to) the version from which Python has been built (see previous answers), or even a newest version and follow the next step.

2)If a newest version of Microsoft visual studio is already installed, we have to make Python/cython etc. believe that it is the version from which it has been built. And this is very simple: go to the the system environment variables and create the following variables, if they do not exist:

VS100COMNTOOLS

VS110COMNTOOLS

VS120COMNTOOLS

VS140COMNTOOLS

And set the field of these variables to

"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools" (if visual studio 2008 is installed), or "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools" (if visual studio 2010 is installed) or "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools" (if visual studio 2013 is installed) or "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools" (if visual studio 2015 is installed).

This solution works for 32 bit versions of python. It may also work for 64 bit version but I've not tested; most probably, for 64 bit versions, the following additional steps must be performed:

3)add the path "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC" to the %PATH% environment variable (change the number of the version of visual studio according to you version).

4) from the command line, run "vcvarsall.bat x86_amd64"

That's all.

How to set default value to all keys of a dict object in python?

In case you actually mean what you seem to ask, I'll provide this alternative answer.

You say you want the dict to return a specified value, you do not say you want to set that value at the same time, like defaultdict does. This will do so:

class DictWithDefault(dict):
    def __init__(self, default, **kwargs):
        self.default = default
        super(DictWithDefault, self).__init__(**kwargs)

    def __getitem__(self, key):
        if key in self:
            return super(DictWithDefault, self).__getitem__(key)
        return self.default

Use like this:

d = DictWIthDefault(99, x=5, y=3)
print d["x"]   # 5
print d[42]    # 99
42 in d        # False
d[42] = 3
42 in d        # True

Alternatively, you can use a standard dict like this:

d = {3: 9, 4: 2}
default = 99
print d.get(3, default)  # 9
print d.get(42, default) # 99

Substring in VBA

You can first find the position of the string in this case ":"

'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")

Then use Left(StringToCut, NumberOfCharacterToCut)

Result = Left(StringToSearch, position -1)

How do you run a script on login in *nix?

The script ~/.bash_profile is run on login.

Unicode (UTF-8) reading and writing to files in Python

Actually, this worked for me for reading a file with UTF-8 encoding in Python 3.2:

import codecs
f = codecs.open('file_name.txt', 'r', 'UTF-8')
for line in f:
    print(line)

How do you execute an arbitrary native command from a string?

Invoke-Expression, also aliased as iex. The following will work on your examples #2 and #3:

iex $command

Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:

$command = 'C:\somepath\someexe.exe somearg'
iex $command

However, if the exe is in quotes, you need the help of & to get it running, as in this example, as run from the commandline:

>> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"

And then in the script:

$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
iex "& $command"

Likely, you could handle nearly all cases by detecting if the first character of the command string is ", like in this naive implementation:

function myeval($command) {
    if ($command[0] -eq '"') { iex "& $command" }
    else { iex $command }
}

But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}, perhaps for specific exception types/messages, or examine the command string.

If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.

What is the best way to merge mp3 files?

Instead of using the command line to do

copy /b 1.mp3+2.mp3 3.mp3

you could instead use "The Rename" to rename all the MP3 fragments into a series of names that are in order based on some kind of counter. Then you could just use the same command line format but change it a little to:

copy /b *.mp3 output_name.mp3

That is assuming you ripped all of these fragment MP3's at the same time and they have the same audio settings. Worked great for me when I was converting an Audio book I had in .aa to a single .mp3. I had to burn all the .aa files to 9 CD's then rip all 9 CD's and then I was left with about 90 mp3's. Really a pain in the a55.

How to easily map c++ enums to strings

I use this solution which I reproduce below:

#define MACROSTR(k) #k

#define X_NUMBERS \
       X(kZero  ) \
       X(kOne   ) \
       X(kTwo   ) \
       X(kThree ) \
       X(kFour  ) \
       X(kMax   )

enum {
#define X(Enum)       Enum,
    X_NUMBERS
#undef X
} kConst;

static char *kConstStr[] = {
#define X(String) MACROSTR(String),
    X_NUMBERS
#undef X
};

int main(void)
{
    int k;
    printf("Hello World!\n\n");

    for (k = 0; k < kMax; k++)
    {
        printf("%s\n", kConstStr[k]);
    }

    return 0;
}

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

You can use strcmp:

break x:20 if strcmp(y, "hello") == 0

20 is line number, x can be any filename and y can be any variable.

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************  TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif

RegEx for validating an integer with a maximum length of 10 characters

[^0-9][+-]?[0-9]{1,10}[^0-9]

In words: Optional + or - followed by a digit, repeated one up to ten times. Note that most libraries have a shortcut for a digit: \d, hence the above could also be written as: \d{1,10}.

Save each sheet in a workbook to separate CSV files

A small modification to answer from Alex is turning on and off of auto calculation.

Surprisingly the unmodified code was working fine with VLOOKUP but failed with OFFSET. Also turning auto calculation off speeds up the save drastically.

Public Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven

' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

' Save the file in current director
OutputPath = ThisWorkbook.Path


If OutputPath <> "" Then
Application.Calculation = xlCalculationManual

' save for each sheet
For Each Sheet In Sheets

    OutputFile = OutputPath & Application.PathSeparator & Sheet.Name & ".csv"

    ' make a copy to create a new book with this sheet
    ' otherwise you will always only get the first sheet

    Sheet.Copy
    ' this copy will now become active
     ActiveWorkbook.SaveAs Filename:=OutputFile, FileFormat:=xlCSV,     CreateBackup:=False
    ActiveWorkbook.Close
Next

Application.Calculation = xlCalculationAutomatic

End If

Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

Exit Sub

Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
        "Source: " & Err.Source & " " & vbCrLf & _
        "Number: " & Err.Number & " " & vbCrLf & _
        "Description: " & Err.Description & " " & vbCrLf

GoTo Finally
End Sub

Python socket receive - incoming packets always have a different size

That's the nature of TCP: the protocol fills up packets (lower layer being IP packets) and sends them. You can have some degree of control over the MTU (Maximum Transfer Unit).

In other words: you must devise a protocol that rides on top of TCP where your "payload delineation" is defined. By "payload delineation" I mean the way you extract the unit of message your protocol supports. This can be as simple as "every NULL terminated strings".

How do I export a project in the Android studio?

Firstly, Add this android:debuggable="false" in the application tag of the AndroidManifest.xml.

You don't need to harcode android:debuggable="false" in your application tag. Infact for me studio complaints -

Avoid hardcoding the debug mode; leaving it out allows debug and release builds to automatically assign one less... (Ctrl+F1)

It's best to leave out the android:debuggable attribute from the manifest. If you do, then the tools will automatically insert android:debuggable=true when building an APK to debug on an emulator or device. And when you perform a release build, such as Exporting APK, it will automatically set it to false. If on the other hand you specify a specific value in the manifest file, then the tools will always use it. This can lead to accidentally publishing your app with debug information.

The accepted answer looks somewhat old. For me it asks me to select whether I want debug build or release build.

Go to Build->Generate Signed APK. Select your keystore, provide keystore password etc.

enter image description here

Now you should see a prompt to select release build or debug build.

For production always select release build!

enter image description here

And you are done. Signed APK exported.

enter image description here

PS : Don't forget to increment your versionCode in manifest file before uploading to playstore :)

Input type DateTime - Value format?

This article seems to show the valid types that are acceptable

<time>2009-11-13</time>
 <!-- without @datetime content must be a valid date, time, or precise datetime -->
<time datetime="2009-11-13">13<sup>th</sup> November</time>
 <!-- when using @datetime the content can be anything relevant -->
<time datetime="20:00">starting at 8pm</time>
 <!-- time example -->
<time datetime="2009-11-13T20:00+00:00">8pm on my birthday</time>
 <!-- datetime with time-zone example -->
<time datetime="2009-11-13T20:00Z">8pm on my birthday</time>
 <!-- datetime with time-zone “Z” -->

This one covers using it in the <input> field:

<input type="date" name="d" min="2011-08-01" max="2011-08-15"> This example of the HTML5 input type "date" combine with the attributes min and max shows how we can restrict the dates a user can input. The attributes min and max are not dependent on each other and can be used independently.

<input type="time" name="t" value="12:00"> The HTML5 input type "time" allows users to choose a corresponding time that is displayed in a 24hour format. If we did not include the default value of "12:00" the time would set itself to the time of the users local machine.

<input type="week" name="w"> The HTML5 Input type week will display the numerical version of the week denoted by a "W" along with the corresponding year.

<input type="month" name="m"> The HTML5 input type month does exactly what you might expect it to do. It displays the month. To be precise it displays the numerical version of the month along with the year.

<input type="datetime" name="dt"> The HTML5 input type Datetime displays the UTC date and time code. User can change the the time steps forward or backward in one minute increments. If you wish to display the local date and time of the user you will need to use the next example datetime-local

<input type="datetime-local" name="dtl" step="7200"> Because datetime steps through one minute at a time, you may want to change the default increment by using the attribute "step". In the following example we will have it increment by two hours by setting the attribute step to 7200 (60seconds X 60 minutes X 2).

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Building on @SotiriosDelimanolis's comment, here is a method to deal with URLs (such as file:...) and non-URLs (such as C:...), using Spring's FileSystemResource:

public FileSystemResource get(String file) {
    try {
        // First try to resolve as URL (file:...)
        Path path = Paths.get(new URL(file).toURI());
        FileSystemResource resource = new FileSystemResource(path.toFile());
        return resource;
    } catch (URISyntaxException | MalformedURLException e) {
        // If given file string isn't an URL, fall back to using a normal file 
        return new FileSystemResource(file);
    }
}

Can I call a function of a shell script from another shell script?

You can't directly call a function in another shell script.

You can move your function definitions into a separate file and then load them into your script using the . command, like this:

. /path/to/functions.sh

This will interpret functions.sh as if it's content were actually present in your file at this point. This is a common mechanism for implementing shared libraries of shell functions.

Implement division with bit-wise operator

All these solutions are too long. The base idea is to write the quotient (for example, 5=101) as 100 + 00 + 1 = 101.

public static Point divide(int a, int b) {

    if (a < b)
        return new Point(0,a);
    if (a == b)
        return new Point(1,0);
    int q = b;
    int c = 1;
    while (q<<1 < a) {
        q <<= 1;
        c <<= 1;
    }
    Point r = divide(a-q, b);
    return new Point(c + r.x, r.y);
}


public static class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int compare(Point b) {
        if (b.x - x != 0) {
            return x - b.x;
        } else {
            return y - b.y;
        }
    }

    @Override
    public String toString() {
        return " (" + x + " " + y + ") ";
    }
}

Convert wchar_t to char

Here's another way of doing it, remember to use free() on the result.

char* wchar_to_char(const wchar_t* pwchar)
{
    // get the number of characters in the string.
    int currentCharIndex = 0;
    char currentChar = pwchar[currentCharIndex];

    while (currentChar != '\0')
    {
        currentCharIndex++;
        currentChar = pwchar[currentCharIndex];
    }

    const int charCount = currentCharIndex + 1;

    // allocate a new block of memory size char (1 byte) instead of wide char (2 bytes)
    char* filePathC = (char*)malloc(sizeof(char) * charCount);

    for (int i = 0; i < charCount; i++)
    {
        // convert to char (1 byte)
        char character = pwchar[i];

        *filePathC = character;

        filePathC += sizeof(char);

    }
    filePathC += '\0';

    filePathC -= (sizeof(char) * charCount);

    return filePathC;
}

How do I get the name of the current executable in C#?

This should suffice:

Environment.GetCommandLineArgs()[0];

Centering FontAwesome icons vertically and horizontally

I just managed how to center icons and and making them a container instead of putting them into one.

.fas {
    position: relative;
    color: #EEE;
    font-size: 16px;
}
.fas:before {
    position: absolute;
    left: calc(50% - .5em);
    top: calc(50% - .5em);
}
.fas.fa-icon {
    width: 60px;
    height: 60px;
    color: white;
    background-color: black;
}

How to prettyprint a JSON file?

I think that's better to parse the json before, to avoid errors:

def format_response(response):
    try:
        parsed = json.loads(response.text)
    except JSONDecodeError:
        return response.text
    return json.dumps(parsed, ensure_ascii=True, indent=4)

Setting PHPMyAdmin Language

sounds like you downloaded the german xampp package instead of the english xampp package (yes, it's another download-link) where the language is set according to the package you loaded. to change the language afterwards, simply edit the config.inc.php and set:

$cfg['Lang'] = 'en-utf-8';

How to create a new figure in MATLAB?

While doing "figure(1), figure(2),..." will solve the problem in most cases, it will not solve them in all cases. Suppose you have a bunch of MATLAB figures on your desktop and how many you have open varies from time to time before you run your code. Using the answers provided, you will overwrite these figures, which you may not want. The easy workaround is to just use the command "figure" before you plot.

Example: you have five figures on your desktop from a previous script you ran and you use

figure(1);
plot(...)

figure(2);
plot(...)

You just plotted over the figures on your desktop. However the code

figure;
plot(...)

figure;
plot(...)

just created figures 6 and 7 with your desired plots and left your previous plots 1-5 alone.

Calculate AUC in R?

As mentioned by others, you can compute the AUC using the ROCR package. With the ROCR package you can also plot the ROC curve, lift curve and other model selection measures.

You can compute the AUC directly without using any package by using the fact that the AUC is equal to the probability that a true positive is scored greater than a true negative.

For example, if pos.scores is a vector containing a score of the positive examples, and neg.scores is a vector containing the negative examples then the AUC is approximated by:

> mean(sample(pos.scores,1000,replace=T) > sample(neg.scores,1000,replace=T))
[1] 0.7261

will give an approximation of the AUC. You can also estimate the variance of the AUC by bootstrapping:

> aucs = replicate(1000,mean(sample(pos.scores,1000,replace=T) > sample(neg.scores,1000,replace=T)))

How to view files in binary from bash?

hexdump -C yourfile.bin

unless you want to edit it of course. Most linux distros have hexdump by default (but obviously not all).

how to make a div to wrap two float divs inside?

This should do it:

<div id="wrap">
  <div id="nav"></div>
  <div id="content"></div>
  <div style="clear:both"></div>
</div>

Oracle JDBC intermittent Connection Issue

OracleXETNSListener - this service has to be started if it was disabled.

run -> services.msc 

and look out for that services

Select every Nth element in CSS

You need the correct argument for the nth-child pseudo class.

  • The argument should be in the form of an + b to match every ath child starting from b.

  • Both a and b are optional integers and both can be zero or negative.

    • If a is zero then there is no "every ath child" clause.
    • If a is negative then matching is done backwards starting from b.
    • If b is zero or negative then it is possible to write equivalent expression using positive b e.g. 4n+0 is same as 4n+4. Likewise 4n-1 is same as 4n+3.

Examples:

Select every 4th child (4, 8, 12, ...)

_x000D_
_x000D_
li:nth-child(4n) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select every 4th child starting from 1 (1, 5, 9, ...)

_x000D_
_x000D_
li:nth-child(4n+1) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select every 3rd and 4th child from groups of 4 (3 and 4, 7 and 8, 11 and 12, ...)

_x000D_
_x000D_
/* two selectors are required */_x000D_
li:nth-child(4n+3),_x000D_
li:nth-child(4n+4) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select first 4 items (4, 3, 2, 1)

_x000D_
_x000D_
/* when a is negative then matching is done backwards  */_x000D_
li:nth-child(-n+4) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

How to delete Tkinter widgets from a window?

One way you can do it, is to get the slaves list from the frame that needs to be cleared and destroy or "hide" them according to your needs. To get a clear frame you can do it like this:

from tkinter import *

root = Tk()

def clear():
    list = root.grid_slaves()
    for l in list:
        l.destroy()

Label(root,text='Hello World!').grid(row=0)
Button(root,text='Clear',command=clear).grid(row=1)

root.mainloop()

You should call grid_slaves(), pack_slaves() or slaves() depending on the method you used to add the widget to the frame.

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

Well, I totally agree with answers already exist on this point:

  • bootstrap.yml is used to save parameters that point out where the remote configuration is and Bootstrap Application Context is created with these remote configuration.

Actually, it is also able to store normal properties just the same as what application.yml do. But pay attention on this tricky thing:

  • If you do place properties in bootstrap.yml, they will get lower precedence than almost any other property sources, including application.yml. As described here.

Let's make it clear, there are two kinds of properties related to bootstrap.yml:

  • Properties that are loaded during the bootstrap phase. We use bootstrap.yml to find the properties holder (A file system, git repository or something else), and the properties we get in this way are with high precedence, so they cannot be overridden by local configuration. As described here.
  • Properties that are in the bootstrap.yml. As explained early, they will get lower precedence. Use them to set defaults maybe a good idea.

So the differences between putting a property on application.yml or bootstrap.yml in spring boot are:

  • Properties for loading configuration files in bootstrap phase can only be placed in bootstrap.yml.
  • As for all other kinds of properties, place them in application.yml will get higher precedence.

How can I check if a value is of type Integer?

To check if a String contains digit character which represent an integer, you can use Integer.parseInt().

To check if a double contains a value which can be an integer, you can use Math.floor() or Math.ceil().

How can I clear event subscriptions in C#?

Conceptual extended boring comment.

I rather use the word "event handler" instead of "event" or "delegate". And used the word "event" for other stuff. In some programming languages (VB.NET, Object Pascal, Objective-C), "event" is called a "message" or "signal", and even have a "message" keyword, and specific sugar syntax.

const
  WM_Paint = 998;  // <-- "question" can be done by several talkers
  WM_Clear = 546;

type
  MyWindowClass = class(Window)
    procedure NotEventHandlerMethod_1;
    procedure NotEventHandlerMethod_17;

    procedure DoPaintEventHandler; message WM_Paint; // <-- "answer" by this listener
    procedure DoClearEventHandler; message WM_Clear;
  end;

And, in order to respond to that "message", a "event handler" respond, whether is a single delegate or multiple delegates.

Summary: "Event" is the "question", "event handler (s)" are the answer (s).

How to get the last element of a slice?

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

Chrome blocks different origin requests

Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.

Bootstrap 3: Scroll bars

You need to use overflow option like below:

.nav{
    max-height: 300px;
    overflow-y: scroll; 
}

Change the height according to amount of items you need to show

Append date to filename in linux

a bit more convoluted solution that fully matches your spec

echo `expr $FILENAME : '\(.*\)\.[^.]*'`_`date +%d-%m-%y`.`expr $FILENAME : '.*\.\([^.]*\)'`

where first 'expr' extracts file name without extension, second 'expr' extracts extension

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

Radio Buttons "Checked" Attribute Not Working

Your code is right, try to debug your JQuery script to find the issue! If you're using FF you can install an extension to debug JS (and JQuery) it's called FireBug.

Horizontal list items

This fiddle shows how

http://jsfiddle.net/9th7X/

ul, li {
    display:inline
}

Great references on lists and css here:

http://alistapart.com/article/taminglists/

Countdown timer in React

You have to setState every second with the seconds remaining (every time the interval is called). Here's an example:

_x000D_
_x000D_
class Example extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = { time: {}, seconds: 5 };_x000D_
    this.timer = 0;_x000D_
    this.startTimer = this.startTimer.bind(this);_x000D_
    this.countDown = this.countDown.bind(this);_x000D_
  }_x000D_
_x000D_
  secondsToTime(secs){_x000D_
    let hours = Math.floor(secs / (60 * 60));_x000D_
_x000D_
    let divisor_for_minutes = secs % (60 * 60);_x000D_
    let minutes = Math.floor(divisor_for_minutes / 60);_x000D_
_x000D_
    let divisor_for_seconds = divisor_for_minutes % 60;_x000D_
    let seconds = Math.ceil(divisor_for_seconds);_x000D_
_x000D_
    let obj = {_x000D_
      "h": hours,_x000D_
      "m": minutes,_x000D_
      "s": seconds_x000D_
    };_x000D_
    return obj;_x000D_
  }_x000D_
_x000D_
  componentDidMount() {_x000D_
    let timeLeftVar = this.secondsToTime(this.state.seconds);_x000D_
    this.setState({ time: timeLeftVar });_x000D_
  }_x000D_
_x000D_
  startTimer() {_x000D_
    if (this.timer == 0 && this.state.seconds > 0) {_x000D_
      this.timer = setInterval(this.countDown, 1000);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  countDown() {_x000D_
    // Remove one second, set state so a re-render happens._x000D_
    let seconds = this.state.seconds - 1;_x000D_
    this.setState({_x000D_
      time: this.secondsToTime(seconds),_x000D_
      seconds: seconds,_x000D_
    });_x000D_
    _x000D_
    // Check if we're at zero._x000D_
    if (seconds == 0) { _x000D_
      clearInterval(this.timer);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return(_x000D_
      <div>_x000D_
        <button onClick={this.startTimer}>Start</button>_x000D_
        m: {this.state.time.m} s: {this.state.time.s}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Example/>, document.getElementById('View'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="View"></div>
_x000D_
_x000D_
_x000D_

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

JavaScript split String with white space

You could split the string on the whitespace and then re-add it, since you know its in between every one of the entries.

var string = "text to split";
    string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
    stringArray.push(string[i]);
    if(i != string.length-1){
        stringArray.push(" ");
    }
}

Update: Removed trailing space.

Resolving a Git conflict with binary files

To resolve by keeping the version in your current branch (ignore the version from the branch you are merging in), just add and commit the file:

git commit -a

To resolve by overwriting the version in your current branch with the version from the branch you are merging in, you need to retrieve that version into your working directory first, and then add/commit it:

git checkout otherbranch theconflictedfile
git commit -a

Explained in more detail

Adjusting HttpWebRequest Connection Timeout in C#

From the documentation of the HttpWebRequest.Timeout property:

A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.

Is it possible that your DNS query is the cause of the timeout?

How to add pandas data to an existing csv file?

You can append to a csv by opening the file in append mode:

with open('my_csv.csv', 'a') as f:
    df.to_csv(f, header=False)

If this was your csv, foo.csv:

,A,B,C
0,1,2,3
1,4,5,6

If you read that and then append, for example, df + 6:

In [1]: df = pd.read_csv('foo.csv', index_col=0)

In [2]: df
Out[2]:
   A  B  C
0  1  2  3
1  4  5  6

In [3]: df + 6
Out[3]:
    A   B   C
0   7   8   9
1  10  11  12

In [4]: with open('foo.csv', 'a') as f:
             (df + 6).to_csv(f, header=False)

foo.csv becomes:

,A,B,C
0,1,2,3
1,4,5,6
0,7,8,9
1,10,11,12

startForeground fail after upgrade to Android 8.1

Works properly on Andorid 8.1:

Updated sample (without any deprecated code):

public NotificationBattery(Context context) {
    this.mCtx = context;

    mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setContentTitle(context.getString(R.string.notification_title_battery))
            .setSmallIcon(R.drawable.ic_launcher)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setChannelId(CHANNEL_ID)
            .setOnlyAlertOnce(true)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setWhen(System.currentTimeMillis() + 500)
            .setGroup(GROUP)
            .setOngoing(true);

    mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_view_battery);

    initBatteryNotificationIntent();

    mBuilder.setContent(mRemoteViews);

    mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (AesPrefs.getBooleanRes(R.string.SHOW_BATTERY_NOTIFICATION, true)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, context.getString(R.string.notification_title_battery),
                    NotificationManager.IMPORTANCE_DEFAULT);
            channel.setShowBadge(false);
            channel.setSound(null, null);
            mNotificationManager.createNotificationChannel(channel);
        }
    } else {
        mNotificationManager.cancel(Const.NOTIFICATION_CLIPBOARD);
    }
}

Old snipped (it's a different app - not related to the code above):

@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
    Log.d(TAG, "onStartCommand");

    String CHANNEL_ONE_ID = "com.kjtech.app.N1";
    String CHANNEL_ONE_NAME = "Channel One";
    NotificationChannel notificationChannel = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                CHANNEL_ONE_NAME, IMPORTANCE_HIGH);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setShowBadge(true);
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.createNotificationChannel(notificationChannel);
    }

    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    Notification notification = new Notification.Builder(getApplicationContext())
            .setChannelId(CHANNEL_ONE_ID)
            .setContentTitle(getString(R.string.obd_service_notification_title))
            .setContentText(getString(R.string.service_notification_content))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(icon)
            .build();

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startForeground(START_FOREGROUND_ID, notification);

    return START_STICKY;
}

How to install the JDK on Ubuntu Linux

Have a look at OpenJDK. It is the standard JVM implementation on Linux.

Laravel Blade html image

In Laravel 5.x you can use laravelcollective/html and the syntax:

{!! Html::image('img/logo.png') !!}

How to run an EXE file in PowerShell with parameters with spaces and quotes

I tried all of the suggestions but was still unable to run msiexec.exe with parameters that contained spaces. So my solution ended up using System.Diagnostics.ProcessStartInfo:

# can have spaces here, no problems
$settings = @{
  CONNECTION_STRING = "... ..."
  ENTITY_CONTEXT = "... ..."
  URL = "..."
}

$settingsJoined = ($settings.Keys | % { "$_=""$($settings[$_])""" }) -join " "
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.WorkingDirectory = $ScriptDirectory
$pinfo.FileName = "msiexec.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "/l* install.log /i installer.msi $settingsJoined"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()

How to Clear Console in Java?

Try this code

import java.io.IOException;

public class CLS {
    public static void main(String... arg) throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    }
}

Now when the Java process is connected to a console, it will clear the console.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>).

You want to deserialize into a single RootObject.

Convert the first element of an array to a string in PHP

Convert an array to a string in PHP:

  1. Use the PHP join function like this:

    $my_array = array(4, 1, 8);
    
    print_r($my_array);
    Array
    (
        [0] => 4
        [1] => 1
        [2] => 8
    )
    
    $result_string = join(',', $my_array);
    echo $result_string;
    

    Which delimits the items in the array by comma into a string:

    4,1,8
    
  2. Or use the PHP implode function like this:

    $my_array = array(4, 1, 8);
    echo implode($my_array);
    

    Which prints:

    418
    
  3. Here is what happens if you join or implode key value pairs in a PHP array

    php> $keyvalues = array();
    
    php> $keyvalues['foo'] = "bar";
    
    php> $keyvalues['pyramid'] = "power";
    
    php> print_r($keyvalues);
    Array
    (
        [foo] => bar
        [pyramid] => power
    )
    
    php> echo join(',', $keyvalues);
    bar,power
    php> echo implode($keyvalues);
    barpower
    php>
    

using awk with column value conditions

Depending on the AWK implementation are you using == is ok or not.

Have you tried ~?. For example, if you want $1 to be "hello":

awk '$1 ~ /^hello$/{ print $3; }' <infile>

^ means $1 start, and $ is $1 end.

Fixed position but relative to container

Two HTML elements and pure CSS (modern browsers)

See this jsFiddle example. Resize and see how the fixed elements even move with the floated elements they are in. Use the inner-most scroll bar to see how the scroll would work on a site (fixed elements staying fixed).

As many here have stated, one key is not setting any positional settings on the fixed element (no top, right, bottom, or left values).

Rather, we put all the fixed elements (note how the last box has four of them) first in the box they are to be positioned off of, like so:

<div class="reference">
  <div class="fixed">Test</div>
  Some other content in.
</div>

Then we use margin-top and margin-left to "move" them in relation to their container, something like as this CSS does:

.fixed {
    position: fixed;
    margin-top: 200px; /* Push/pull it up/down */
    margin-left: 200px; /* Push/pull it right/left */
}

Note that because fixed elements ignore all other layout elements, the final container in our fiddle can have multiple fixed elements, and still have all those elements related to the top left corner. But this is only true if they are all placed first in the container, as this comparison fiddle shows that if dispersed within the container content, positioning becomes unreliable.

Whether the wrapper is static, relative, or absolute in positioning, it does not matter.

How to execute mongo commands through shell scripts?

In case you have authentication enabled:

mongo -u username -p password --authenticationDatabase auth_db_name < your_script.js

How to "pretty" format JSON output in Ruby on Rails


# example of use:
a_hash = {user_info: {type: "query_service", e_mail: "[email protected]", phone: "+79876543322"}, cars_makers: ["bmw", "mitsubishi"], car_models: [bmw: {model: "1er", year_mfc: 2006}, mitsubishi: {model: "pajero", year_mfc: 1997}]}
pretty_html = a_hash.pretty_html

# include this module to your libs:
module MyPrettyPrint
    def pretty_html indent = 0
        result = ""
        if self.class == Hash
            self.each do |key, value|
                result += "#{key}

: #{[Array, Hash].include?(value.class) ? value.pretty_html(indent+1) : value}

" end elsif self.class == Array result = "[#{self.join(', ')}]" end "#{result}" end end class Hash include MyPrettyPrint end class Array include MyPrettyPrint end

How do I return an int from EditText? (Android)

Set the digits attribute to true, which will cause it to only allow number inputs.

Then do Integer.valueOf(editText.getText()) to get an int value out.

What is the use of printStackTrace() method in Java?

printStackTrace() helps the programmer to understand where the actual problem occurred. It helps to trace the exception. it is printStackTrace() method of Throwable class inherited by every exception class. This method prints the same message of e object and also the line number where the exception occurred.

The following is an another example of print stack of the Exception in Java.

public class Demo {
   public static void main(String[] args) {
      try {
         ExceptionFunc();
      } catch(Throwable e) {
         e.printStackTrace();
      }
   }
   public static void ExceptionFunc() throws Throwable {
      Throwable t = new Throwable("This is new Exception in Java...");

      StackTraceElement[] trace = new StackTraceElement[] {
         new StackTraceElement("ClassName","methodName","fileName",5)
      };
      t.setStackTrace(trace);
      throw t;
   }
}

java.lang.Throwable: This is new Exception in Java... at ClassName.methodName(fileName:5)

How to convert string to boolean php

The answer by @GordonM is good. But it would fail if the $string is already true (ie, the string isn't a string but boolean TRUE)...which seems illogical.

Extending his answer, I'd use:

$test_mode_mail = ($string === 'true' OR $string === true));

Git Push ERROR: Repository not found

I faced same error after updating my ubuntu to next version

I just deleted my sshkey on github account and then re added an sshkey to that account.

Converting a view to Bitmap without displaying it in Android?

I think this is a bit better :

/**
 * draws the view's content to a bitmap. code initially based on :
 * http://nadavfima.com/android-snippet-inflate-a-layout-draw-to-a-bitmap/
 */
@Nullable
public static Bitmap drawToBitmap(final View viewToDrawFrom, int width, int height) {
    boolean wasDrawingCacheEnabled = viewToDrawFrom.isDrawingCacheEnabled();
    if (!wasDrawingCacheEnabled)
        viewToDrawFrom.setDrawingCacheEnabled(true);
    if (width <= 0 || height <= 0) {
        if (viewToDrawFrom.getWidth() <= 0 || viewToDrawFrom.getHeight() <= 0) {
            viewToDrawFrom.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            width = viewToDrawFrom.getMeasuredWidth();
            height = viewToDrawFrom.getMeasuredHeight();
        }
        if (width <= 0 || height <= 0) {
            final Bitmap bmp = viewToDrawFrom.getDrawingCache();
            final Bitmap result = bmp == null ? null : Bitmap.createBitmap(bmp);
            if (!wasDrawingCacheEnabled)
                viewToDrawFrom.setDrawingCacheEnabled(false);
            return result;
        }
        viewToDrawFrom.layout(0, 0, width, height);
    } else {
        viewToDrawFrom.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
        viewToDrawFrom.layout(0, 0, viewToDrawFrom.getMeasuredWidth(), viewToDrawFrom.getMeasuredHeight());
    }
    final Bitmap drawingCache = viewToDrawFrom.getDrawingCache();
    final Bitmap bmp = ThumbnailUtils.extractThumbnail(drawingCache, width, height);
    final Bitmap result = bmp == null || bmp != drawingCache ? bmp : Bitmap.createBitmap(bmp);
    if (!wasDrawingCacheEnabled)
        viewToDrawFrom.setDrawingCacheEnabled(false);
    return result;
}

Using the above code, you don't have to specify the size of the bitmap (use 0 for width&height) if you want to use the one of the view itself.

Also, if you wish to convert special views (SurfaceView, Surface or Window, for example) to a bitmap, you should consider using PixelCopy class instead. It requires API 24 and above though. I don't know how to do it before.

Find value in an array

You can go for array methods.

To see all array methods use methods function with array. For Example,

a = ["name", "surname"] 
a.methods

By the way you can use different method for checking value in array You can use a.include?("name").

How to read XML response from a URL in java?

For xml parsing of an inputstream you can do:

// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));

// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());

But to communicate over http from server to client I prefer using hessian library or springs http invoker lib

pandas DataFrame: replace nan values with average of columns

If you want to impute missing values with mean and you want to go column by column, then this will only impute with the mean of that column. This might be a little more readable.

sub2['income'] = sub2['income'].fillna((sub2['income'].mean()))

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[])

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

MVC4 input field placeholder

An alternative to using a plugin is using an editor template. What you need to do is to create a template file in Shared\EditorTemplates folder and call it String.cshtml. Then put this in that file:

@Html.TextBox("",ViewData.TemplateInfo.FormattedModelValue, 
    new { placeholder = ViewData.ModelMetadata.Watermark })

Then use it in your view like this:

@Html.EditorFor(m=>Model.UnitPercent)

The downside, this works for properties of type string, and you will have to create a template for each type that you want support for a watermark.

Real differences between "java -server" and "java -client"?

IIRC the server VM does more hotspot optimizations at startup so it runs faster but takes a little longer to start and uses more memory. The client VM defers most of the optimization to allow faster startup.

Edit to add: Here's some info from Sun, it's not very specific but will give you some ideas.

no suitable HttpMessageConverter found for response type

If you can't change server media-type response, you can extend GsonHttpMessageConverter to process additional support types

public class MyGsonHttpMessageConverter extends GsonHttpMessageConverter {
    public MyGsonHttpMessageConverter() {
        List<MediaType> types = Arrays.asList(
                new MediaType("text", "html", DEFAULT_CHARSET),
                new MediaType("application", "json", DEFAULT_CHARSET),
                new MediaType("application", "*+json", DEFAULT_CHARSET)
        );
        super.setSupportedMediaTypes(types);
    }
}