HOW TO INSTALL/SET UP A WORDPRESS MULTISITE

In this tutorial we explain how you can install and set up a WordPress multisite to build a network of websites. We assume that you already installed a WordPress Single Site. Moreover we assume you have FTP access to the directory of your WordPress installation, as you need to change some files.

Table of Contents

1. Install WordPress Multisite – the Requirements

Before you start to install the WordPress multisite, please make sure that:

  • You already have a WordPress installation
  • Pretty Permalinks are activated. This means your URLs should not look like this http://example.com/?p=2345, but rather like this http://example.com/my-page
  • All plugins are deactivated
  • Important: you have a backup of your WordPress installation
  • You have FTP access to your WordPress installation

2. Allow Multisite in wp-config.php

The first step is to activate the Multisite feature in the file wp-config.php.

  1. Set up a FTP connection to your website.
  2. Open the file wp-config.php, which is is located in the main directory of your WordPress, and add the line
    define('WP_ALLOW_MULTISITE', true);
    above the line:
    /* That's all, stop editing! Happy blogging. */
    Define WP_ALLOW_MULTISITE in wp-config.php to enable the Multisite feature.
  3. Save the file wp-config.php.

Now you enabled the Multisite feature in your WordPress installation. But you haven’t finished yet. The next step is to install the network.

3. Install the WordPress Network

  1. Refresh the page in your browser and log in to your website.
  2. In the left sidebar under Tools you will find the menu tab Network Setup, where you can configure your WordPress Multisite.Install a WordPress Multisite – Settings page “Create a Network of WordPress Sites”
  3. Decide whether you want to use subdomains for the sites in your network (e.g. site1.example.com) or whether you want to have them installed in subfolders (e.g. example.com/site1).  This setting affects all the sites in your network, you cannot change that later on.  Do you need a site to be mapped to a top level domain (e.g. mydomain.com)? This is possible with domain mapping.
  4. Enter a name for your network in the field Network Title in the section Network Details.
  5. Enter the site admin’s e-mail address.
  6. Click the Install button.

4. Add some code to wp-config.php and .htaccess

WordPress will now provide you with two snippets of code, which you need to add to the wp-config.php and .htaccess files. Both files are located in the root directory of your WordPress.

  1. Set up a FTP connection to your website.
  2. Add the first code snippet to your wp-config.php directly above the line
    /* That's all, stop editing! Happy blogging. */
    The snippet looks like this, but adapted to your own site:
    define('MULTISITE', true);
    define('SUBDOMAIN_INSTALL', true);
    define('DOMAIN_CURRENT_SITE', 'My Website');
    define('PATH_CURRENT_SITE', '/');
    define('SITE_ID_CURRENT_SITE', 1);
    define('BLOG_ID_CURRENT_SITE', 1);
  3. Add the second code snippet to the .htaccess file and replace other WordPress rules.
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]

    # add a trailing slash to /wp-admin
    RewriteRule ^wp-admin$ wp-admin/ [R=301,L]

    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
    RewriteRule ^(.*\.php)$ $1 [L]
    RewriteRule . index.php [L]
  4. Save both files.

 

5. Menu network administration and the network settings

When you changed the wp-config.php and the .htaccess, log into your WordPress admin area again. In the upper admin bar, you now see the new menu Network Admin. It’s displayed always, so you can always enter the admin area of the network, no matter on which site of your network you are. We take a look at the sub menues later on.

Below the network administration, all sites of the network are listed to which you were added. By clicking on the names, you enter the backends of these sites.

The menu Network Admin of a WordPress multisite
The menu Network Admin of WordPress multisite

And here’s the explanation of the menu tabs in the network administration:

  • Dashboard: Here you can find the widget to add new users and new sites to your network.
  • Sites: On this tab, you can see all sites of your network – similar to the posts and pages. By moving the cursor over the websites, you see for example links to edit, display the dashboard, view, delete, archive or deactivate the sites. Note that you have fewer functions for the main page of your network, as this one always needs to exist and you cannot delete it.
  • Users: Here you can administer the users of your network. In contrast to a single site installation, you can assign the super admin user role. The super admin has access to all sites and can make changes within the whole network. If you want a user to have access to the sites of your network, you need to add the user to each site via the user administration of the sites.
  • Themes: The theme administration. Here you can install and uninstall themes and activate or deactivate them for the whole network.
  • Plugins: Here you can find all installed plugins. You can add new plugins or delete them, you can activate or deactivate them for the whole network.
  • Settings: On this tab you can find and edit the basic settings for your site, for example: the network name and the admin E-Mail address, you can allow user registrations, add new users to the site admins, you can make the themes and plugins menu available for site admins or set the standard language of your sites.

6. Add a new website to the network

A WordPress multisite with only one website doesn’t really make sense. To a WordPress multisite, you can add as many websites as you want – always and any time, so, it needn’t be at the beginning. To enhance your website with a new site, take the following steps:

  1. Go to My Sites → Network Admin → Sites and click Add new.Add a new website to a multisite
  2. Enter the desired website address. In this case, we decided for a network with sub directories. The domain is already given, we just add the sub diretory.Settings for the new website in the multisite network
  3. Define a title of the website. This one is displayed at several positions in your network, for example in the backend as website name in My Sites, but maybe also in the frontend or in meta data like the page title.
  4. Choose a language for the new website.
  5. Choose the admin e-mail address which must be different than the one for the whole network. If there is no user with this e-mail yet, a new user with admin role for this site will be created.
  6. Click the button Add Site. Your new site is to be created and will be displayed in My Sites  → Network Admin → SitesHowever, in order to let others than the current admin administer this new site, you need to add them as user with admin role to this site.

7. Install Plugins and Themes in the WordPress multisite

Install or uninstall plugins or themes in a WordPress multisite network is something only the super admin can do. The site admins within the network can only activate or deactivate them. Well, and site admins can only activate and deactivate plugins in case the super admin checked the box Enable administration menus in the network administration in Settings → Network Settings.

Enable administration menus
Enable administration menus to allow admins to enable/disable plugins.

You can find the plugins administration for the whole network under Network Admin → Plugins, the themes administration under Network Admin → Themes.

Install plugins in a multisite
Install plugins in a multisite and make them available for the whole network

For the site admin, the whole thing looks like the next picture.

The plugins administration as site admin in a WordPress multisite
The plugins administration as site admin in a WordPress multisite

Hint: The admin can activate and deactivate plugins, but he cannot install or uninstall them.

For one of the plugins in our example you can read Network Only. This means the plugin is available only for all sites or for no site. Moreover, it’s the super admin only who can set the settings of this specific plugin, you need to make them in the network administration.

You can find further help to set up your multisite in our documentation category WordPress Multisite 1×1. In case you are setting up a multilingual website, take a look at: MultilingualPress getting started.


– And now about local –


A WordPress multisite can be the answer to managing multiple WordPress websites easily. Once you install WordPress multisite on your server, there’ll be no need to replicate administrative tasks on the backend of a number of individual sites. The sites can all be managed from a single dashboard.

Multisite dashboard

What is WordPress multisite exactly? A multisite is a network of two or more sites that operate off a single WordPress install. All the sites on a multisite setup will use the same WP database, WP directory and WP configuration file. In such a setup, the management of the WordPress install is in the hands of a “Network Administrator”. And the administration of the individual sites on the network is left to the care of the respective Site Admins.

How to Install WordPress Multisite on a Local Server

To begin with, make certain that you have administrator rights to access your computer’s file system. This is because you’ll need privileges to create directories and edit files.

We’ll presume that you’ve installed WordPress on your computer already. But just in case you need help with this, you can always look into our earlier guide.

Note. This is a required step. In order to follow through and install WordPress multisite on your local computer, you first need to have a standard WordPress installation running. Again, please check out our other guide – it’s a step-by-step tutorial, quite easy to follow.

To install WordPress multisite locally and create a network of any number of sites on your own computer, follow these steps:

Before you start:

Choice of URL: Now’s the time to decide whether to install additional sites in a sub-directory or under a sub-domain. It’s important to realize that you cannot change this later.

  • A sub-domain URL for the individual sites will read: site1.YOURSITE.comsite2.YOURSITE.com
  • A sub-directory URL for the individual sites will read: YOURSITE.com/site1YOURSITE.com/site2

On a live server, you can install both under a sub-domain or a sub-directory. Installing a sub-domain on a local host is a little more technical. It involves configuring the XAMPP application to create a sub-domain and then registering it in the operating system software files. In this post, we’ll deal with only a sub-directory installation on the local server.

Enabling the Multisite Feature

1. Adding the multisite feature:

Firstly, open your wp-config.php file and find the line, ‘/* That’s all, stop editing! Happy blogging. */‘ towards the end. Just above this phrase, add this piece of code:

define('WP_ALLOW_MULTISITE', true);

Then save and close the file.

2. Setting up your network:

At this point, you should see a new item in your WordPress dashboard. Specifically, go to Tools > Network Setup. Once there, choose either sub-domains or sub directories.

If you’re going with a sub-domain network on a live server, you’ll need to obtain something called a wild card DNS from your hosting service provider. Since, we’re only doing a sub-directory install on a local server, you do not need any permissions. Fill in the details and then click on install.

Install WordPress Multisite

A few lines of code will be generated, and you need to add them in your wp-config.php file and in your .htaccess file.

After inserting the code, save the files. With this, WordPress Multisite is now successfully installed.

To access your Network Admin Dashboard, you’ll have to login afresh.

3. Adding sites to your network:

At this point, you can start creating sites and adding them to your network by clicking through My Sites > Network Admin > Sites > Add New:

Fill in the details for the individual sites, such as Address, Title and email. Then Click Add Site.

In the same manner, you can add as many sites as you want. You’ll see all the sites in your Network under All Sites.

4. Add themes and plugins:

With multisite in place, a Network Admin can install themes and plugins on multisite. These themes and plugins can be activated across the entire network, or selectively on a per-site basis.

When To Use / Install WordPress Multisite?

In general, multisite works well for a group of sites that fall into a hierarchical framework. Think government and its various departments, a university and its different schools, any national / world organization and its numerous chapters.

It’s also a good fit for a group of related sites that share common resources. For instance, a network of parallel or allied blogs.

To understand this better, check out Harvard Blogs, a free service for the benefit of the Harvard community. Anyone with an email at harvard.edu can create a blog on this WordPress install. Bloggers can simply concentrate on creating and managing content for their blogs, while enjoying the common resources offered by multisite – themes, widgets, multimedia material, spam protection and more.

In short, WordPress multisite helps you manage all your blogs from a single dashboard. You’ll need to install themes, plugins and updates just once and then activate them as required. Not only that, you’ll also save on time and server space. And, if you’re up to handling the technicalities, you can even monetize the network by offering to host other sites on your network.

When WordPress Multisite is Not The Solution?

Does all this mean that WordPress multisite is the best solution for anyone who runs multiple blogs? Of course not. While multisite offers great convenience, it does have some downside to it as well. Individual sites are restricted in their choice of themes, plugins and hosting service. Moreover, not all plugins are multisite compatible, and this can somewhat limit your choice of plugins.

Again, any downtime at the server end will cause the entire network to go down. And, if it happens that any one site on the network experiences a spurt in traffic, it may affect the speed of the other sites in the network.

It’s also important to note that detaching a site from the network or migrating the whole multisite setup sometime in the future may require professional help. And therefore, switching to a multisite arrangement should be done after much careful thought.

Install WordPress multisite: To Conclude

You can use a local multisite as a testing site for any changes to your WordPress install or to test compatibility of any new themes or plugins. You can also work on any project locally, before you push it up to a live server.





Source: multilingualpress.org

ArrayList class in Java

java.util 
Class ArrayList<E>

takođe pogledati i : https://www.tutorialspoint.com/java/util/arraylist_add_index.htm

java.lang.Object   java.util.AbstractCollection<E>       java.util.AbstractList<E>           java.util.ArrayList<E> 

All Implemented Interfaces:SerializableCloneableIterable<E>, Collection<E>, List<E>, RandomAccessDirect Known Subclasses:AttributeListRoleListRoleUnresolvedList


public class ArrayList<E>extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, Serializable

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedListimplementation.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be “wrapped” using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

   List list = Collections.synchronizedList(new ArrayList(...));

The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.Since:1.2See Also:CollectionListLinkedListVectorSerialized Form


Field Summary
Fields inherited from class java.util.AbstractList
modCount
Constructor Summary
ArrayList() 
          Constructs an empty list with an initial capacity of ten.
ArrayList(Collection<? extends E> c) 
          Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.
ArrayList(int initialCapacity) 
          Constructs an empty list with the specified initial capacity.
Method Summary
 booleanadd(E e) 
          Appends the specified element to the end of this list.
 voidadd(int index, E element) 
          Inserts the specified element at the specified position in this list.
 booleanaddAll(Collection<? extends E> c) 
          Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator.
 booleanaddAll(int index, Collection<? extends E> c) 
          Inserts all of the elements in the specified collection into this list, starting at the specified position.
 voidclear() 
          Removes all of the elements from this list.
 Objectclone() 
          Returns a shallow copy of this ArrayList instance.
 booleancontains(Object o) 
          Returns true if this list contains the specified element.
 voidensureCapacity(int minCapacity) 
          Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
 Eget(int index) 
          Returns the element at the specified position in this list.
 intindexOf(Object o) 
          Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
 booleanisEmpty() 
          Returns true if this list contains no elements.
 intlastIndexOf(Object o) 
          Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
 Eremove(int index) 
          Removes the element at the specified position in this list.
 booleanremove(Object o) 
          Removes the first occurrence of the specified element from this list, if it is present.
protected  voidremoveRange(int fromIndex, int toIndex) 
          Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
 Eset(int index, E element) 
          Replaces the element at the specified position in this list with the specified element.
 intsize() 
          Returns the number of elements in this list.
 Object[]toArray() 
          Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[]toArray(T[] a) 
          Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
 voidtrimToSize() 
          Trims the capacity of this ArrayList instance to be the list’s current size.
Methods inherited from class java.util.AbstractList
equalshashCodeiteratorlistIteratorlistIteratorsubList
Methods inherited from class java.util.AbstractCollection
containsAllremoveAllretainAlltoString
Methods inherited from class java.lang.Object
finalizegetClassnotifynotifyAllwaitwaitwait
Methods inherited from interface java.util.List
containsAllequalshashCodeiteratorlistIteratorlistIteratorremoveAllretainAllsubList
Constructor Detail

ArrayList

public ArrayList(int initialCapacity)

Constructs an empty list with the specified initial capacity.Parameters:initialCapacity – the initial capacity of the listThrows:IllegalArgumentException – if the specified initial capacity is negative


ArrayList

public ArrayList()

Constructs an empty list with an initial capacity of ten.


ArrayList

public ArrayList(Collection<? extends E> c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.Parameters:c – the collection whose elements are to be placed into this listThrows:NullPointerException – if the specified collection is null

Method Detail

trimToSize

public void trimToSize()

Trims the capacity of this ArrayList instance to be the list’s current size. An application can use this operation to minimize the storage of an ArrayListinstance.


ensureCapacity

public void ensureCapacity(int minCapacity)

Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.Parameters:minCapacity – the desired minimum capacity


size

public int size()

Returns the number of elements in this list.Specified by:size in interface Collection<E>Specified by:size in interface List<E>Specified by:size in class AbstractCollection<E>Returns:the number of elements in this list


isEmpty

public boolean isEmpty()

Returns true if this list contains no elements.Specified by:isEmpty in interface Collection<E>Specified by:isEmpty in interface List<E>Overrides:isEmpty in class AbstractCollection<E>Returns:true if this list contains no elements


contains

public boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that(o==null ? e==null : o.equals(e)).Specified by:contains in interface Collection<E>Specified by:contains in interface List<E>Overrides:contains in class AbstractCollection<E>Parameters:o – element whose presence in this list is to be testedReturns:true if this list contains the specified element


indexOf

public int indexOf(Object o)

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.Specified by:indexOf in interface List<E>Overrides:indexOf in class AbstractList<E>Parameters:o – element to search forReturns:the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element


lastIndexOf

public int lastIndexOf(Object o)

Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.Specified by:lastIndexOf in interface List<E>Overrides:lastIndexOf in class AbstractList<E>Parameters:o – element to search forReturns:the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element


clone

public Object clone()

Returns a shallow copy of this ArrayList instance. (The elements themselves are not copied.)Overrides:clone in class ObjectReturns:a clone of this ArrayList instanceSee Also:Cloneable


toArray

public Object[] toArray()

Returns an array containing all of the elements in this list in proper sequence (from first to last element).

The returned array will be “safe” in that no references to it are maintained by this list. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array.

This method acts as bridge between array-based and collection-based APIs.Specified by:toArray in interface Collection<E>Specified by:toArray in interface List<E>Overrides:toArray in class AbstractCollection<E>Returns:an array containing all of the elements in this list in proper sequenceSee Also:Arrays.asList(Object[])


toArray

public <T> T[] toArray(T[] a)

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the collection is set to null. (This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.)Specified by:toArray in interface Collection<E>Specified by:toArray in interface List<E>Overrides:toArray in class AbstractCollection<E>Parameters:a – the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.Returns:an array containing the elements of the listThrows:ArrayStoreException – if the runtime type of the specified array is not a supertype of the runtime type of every element in this listNullPointerException – if the specified array is null


get

public E get(int index)

Returns the element at the specified position in this list.Specified by:get in interface List<E>Specified by:get in class AbstractList<E>Parameters:index – index of the element to returnReturns:the element at the specified position in this listThrows:IndexOutOfBoundsException – if the index is out of range (index < 0 || index >= size())


set

public E set(int index,
             E element)

Replaces the element at the specified position in this list with the specified element.Specified by:set in interface List<E>Overrides:set in class AbstractList<E>Parameters:index – index of the element to replaceelement – element to be stored at the specified positionReturns:the element previously at the specified positionThrows:IndexOutOfBoundsException – if the index is out of range (index < 0 || index >= size())


add

public boolean add(E e)

Appends the specified element to the end of this list.Specified by:add in interface Collection<E>Specified by:add in interface List<E>Overrides:add in class AbstractList<E>Parameters:e – element to be appended to this listReturns:true (as specified by Collection.add(E))


add

public void add(int index,
                E element)

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).Specified by:add in interface List<E>Overrides:add in class AbstractList<E>Parameters:index – index at which the specified element is to be insertedelement – element to be insertedThrows:IndexOutOfBoundsException – if the index is out of range (index < 0 || index > size())


remove

public E remove(int index)

Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).Specified by:remove in interface List<E>Overrides:remove in class AbstractList<E>Parameters:index – the index of the element to be removedReturns:the element that was removed from the listThrows:IndexOutOfBoundsException – if the index is out of range (index < 0 || index >= size())


remove

public boolean remove(Object o)

Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).Specified by:remove in interface Collection<E>Specified by:remove in interface List<E>Overrides:remove in class AbstractCollection<E>Parameters:o – element to be removed from this list, if presentReturns:true if this list contained the specified element


clear

public void clear()

Removes all of the elements from this list. The list will be empty after this call returns.Specified by:clear in interface Collection<E>Specified by:clear in interface List<E>Overrides:clear in class AbstractList<E>


addAll

public boolean addAll(Collection<? extends E> c)

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this list, and this list is nonempty.)Specified by:addAll in interface Collection<E>Specified by:addAll in interface List<E>Overrides:addAll in class AbstractCollection<E>Parameters:c – collection containing elements to be added to this listReturns:true if this list changed as a result of the callThrows:NullPointerException – if the specified collection is nullSee Also:AbstractCollection.add(Object)


addAll

public boolean addAll(int index,
                      Collection<? extends E> c)

Inserts all of the elements in the specified collection into this list, starting at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection’s iterator.Specified by:addAll in interface List<E>Overrides:addAll in class AbstractList<E>Parameters:index – index at which to insert the first element from the specified collectionc – collection containing elements to be added to this listReturns:true if this list changed as a result of the callThrows:IndexOutOfBoundsException – if the index is out of range (index < 0 || index > size())NullPointerException – if the specified collection is null


removeRange

protected void removeRange(int fromIndex,
                           int toIndex)

Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. Shifts any succeeding elements to the left (reduces their index). This call shortens the list by (toIndex – fromIndex) elements. (If toIndex==fromIndex, this operation has no effect.)Overrides:removeRange in class AbstractList<E>Parameters:fromIndex – index of first element to be removedtoIndex – index after last element to be removedThrows:IndexOutOfBoundsException – if fromIndex or toIndex out of range (fromIndex < 0 || fromIndex >= size() || toIndex > size() || toIndex < fromIndex)

Video Optimization for the Web

What bitrate should I use when encoding my video? 
How do I optimize my video for the web?

Derek Stanley

In this article we will go over some recommendations for compressing your videos for delivery through the Amazon S3 servers.

A scenario you might be familiar with is that you have filmed and edited your content into a package that meets your needs, but once you go to view your video on your website it takes forever to load or the video stutters during playback. This problem is not necessarily a bad encoding, but it could be the result of not encoding your video to a targeted connection speed.

In an ideal world you would be able to load your uncompressed video directly onto the web and end users would be able to view the file. Unfortunately, the quantity of data present along with the bandwidth limitations of your clients, makes this an impossibility at this point in time.

To reduce the data being pushed through your video you will have to perform a compression using a codec, which was covered in our previous article here:

My video has no sound or picture, am I using the right codec? What is a codec anyway?

Which Container and Codec Should I Use?

As previously mentioned in the article linked above the container is simply a way of packaging together the audio and video stream while delineating how they are compressed.

What bitrate should I use when encoding my video? How do I optimize my video for the web?

When choosing between the MP4, MOV, FLV, WMV and AVI containers, MP4 is the best option. The complexity of the MOV container can cause devices to stall when playing video. The FLV container is only supported by the Flash plugin, which is not supported by the new HTML5 standard and Apple mobile devices such as the iPhone. The WMV container requires specialized plugins and is generally only supported by Microsoft products such the Zune, or Silverlight. The AVI container is not meant for web distribution, as it is targeted at desktop players (it is also not supported for web playback through our own players, but it is listed here to clear any confusion on the container).

The MP4 container is almost universally supported: Apple, Microsoft, Flash, and HTML5 all offer support for MP4 (there are some outliers). On top of that MP4 can use the H.264 video codec and the AAC audio codec, compatibility wise they are the best choices for compressing your video. H.264 video is supported by just about any player, browser, plugin and device available. It also offers one of the best algorithms for compressing your video on top of being freely available.

How Exactly Do You Encode For A Targeted Connection Speed?

File size is probably the first idea that pops in your head, but you shouldn’t be thinking so much about the file size as the overall bitrate. As long as the viewer’s connection can keep up with the file’s bitrate, it will stream (progressive download or streaming) without stuttering.

File size = bitrate (kilobits per second) x duration

Bitrate is a measurement of the number of bits that are transmitted over a set length of time. Your overall bitrate is a combination of your video stream and audio stream in your file with the majority coming from your video stream.

What bitrate should I use when encoding my video? How do I optimize my video for the web?

A simplified analogy is to think about how water is pumped out of a well and how long it will take for water to travel from the well to a faucet. No matter how powerful the pump there will always be a delay because the water has to travel through the pipes connected to the faucet. Your video is the water, while the pump represent the speed of the Amazon s3 server. The connection speed of your end user is the diameter of the pipe. The length of the pipes can be thought as the distance from the server. The pipe is going to bottleneck the water increasing the time it will take to get out the other side. In essence, that is the major problem you face with the streaming of videos online, you have to account for the delay.

If you know the average connection speed of your clients you can set your overall bitrate to be under their download speed to achieve a streaming playback. You should encode at a bitrate below their connection speed because this will help to take into account miscellaneous ambient traffic, distance from the server, and other elements loading into the same webpage.

For example, taking the US broadband average of 3.9 Mbps (as of January 2010) you would probably want to encode somewhere between 2,000 and 3,000 Kbps. (1 Megabit equals 1,000 Kilobits most encoders measure bitrate in Kilobits). What this means is that every second of the video there is 2,000 kilobits required before that second can be displayed. Converting bits to bytes (8 bits equals 1 byte) you can see this is 250 kilobytes a second or 15 megabytes per minute.

Depending on the codec in use and the container this can be a very limiting number. The problem is further extended if you have varying connection speeds across your user base, which is most often the case. If you are only serving one version of your video, you will find yourself pandering to the lowest common denominator. AT&T for example (In the US) guarantees only a download speed up to 1.5Mbps with their starting DSL package.

Cutting Back On The Video Stream

If you have your target bitrate, but are having trouble achieving an acceptable quality video, you will have to cut back in some aspect. The contributing factors that will lead to a higher video bitrate are the amount of pixels (the resolution of the video), the frame rate, and the amount of motion present. If your video is already filmed there is not much you can do about the motion in the video, but in your planning stages you can think ahead.

1. Resolution

The easiest change can come from lowering the number of pixels displayed by simply lowering the resolution of the file. If you are playing your video in a 320 x 240 player on your website and you do not expect the end user to enlarge the video, then there is no reason to have a file with a higher resolution. Even if your camera records at 1080p, it does not mean you cannot scale down to a smaller size to save on bitrate. Although, it should be noted that you want to maintain the image aspect ratio when resizing. Most videos are filmed in either 16:9 or 4:3, changing this ratio can lead to a squishing or stretching effect that is unsightly.

For better quality to bitrate ratio, also remember to keep your resolution in a value evenly divisible by 16, but do not alter a resolution to make it a multiple of 16 unless you over-crop, which will cause you to lose part of your image. Under-cropping or adding a black border around your image will decrease encoding efficiency. Scaling will just degrade the image.

2. Frame Rate

The frame rate is how many unique consecutive images are displayed per second in the video to give the illusion of movement. The human visual system does not see in terms of frames; it works with a continuous flow of light information. Basically this means that the rate at which a video has the appearance of judder (non-smooth motion) is different based on a person to person basis along with the colors (or color of light or actions) in the video.

Around 24 frames per second, the typical film rate which often gives a “cinematic feel,” is where most video creators land and is also a point that most human eyes are fooled into perceiving motion. This is not a standard of course, if your video is a screen cast you can get to frame rates as low as 5fps. On the other hand, large shifts between a pure white or pure black screens can have a perceivable fault below 30fps and footage of video games can often require 60fps to maintain smoothness. Television standards such as PAL (common in Europe and some parts of Asia) uses 25fps, while NTSC standard (used in the US and Japan) uses 29.97fps. Generally you should never exceed the frame rate of the source video. Obviously, the best results will be achieved if the frame rate is kept the same as your original source.

Unfortunately, to lower the bitrate you may have to choose a lower frame rate. Like most of these settings it is best to play around with the encoding to find a setting that looks best for your video. In order to do that it is advisable to consider the amount of action on screen. “Talking head videos” (a tripod shot recording a person talking at the screen) for example does not require a high frame rate because the motion is most likely subdued. While a video of a skate boarder will require at least 24fps to maintain smoothness. When you lower your frame rate make sure to accomplish it in even increments (such as splitting the amount in half) to avoid de-syncing of the video and audio streams.

3. Constant versus Variable

One option you will notice when you go to encode your videos is a selection for VBR (Variable Bit Rate encoding) or CBR (Constant Bit Rate encoding). As a general rule VBR is for progressive or standard downloads and CBR is for use when using a streaming cloudfront.

VBR allows you to set a maximum and minimum bitrate. The compression algorithm then tries to efficiently compress the data dipping into the minimum bitrate when there is little to no motion on screen and spiking to the maximum defined rate when the motion is prevalent. This helps to give you a smaller overall file size, but the unpredictable spikes in bitrate can choke the playback of streaming videos.

CBR is used when a predictable flat bit rate is needed. The flat bitrate throughout the entire file comes at the price of efficiency for the codec. Usually resulting in a larger file, but smoother playback.

However these rules are not universal. Depending on your video you might want to use a VBR for a streaming playback if the spikes do not exceed your target user’s connection speed. For example if there is only one high motion scene in a video, you will be wasting bandwidth on a constant bitrate throughout the entire file and may better serve your user’s by using a variable bitrate. In any case try experimenting with the two settings to find what works best for your video.

4. Quality versus Streaming

If you are not sure what your target connection speed is and you are not shooting to stream your videos, but do not want an abundant amount of bandwidth cost from Amazon, one method that works really well in determining a good bitrate is the Kush Gauge. To find a decent bitrate simply multiply the target pixel count by the frame rate; then multiply the result by a factor of 1, 2 or 4, depending on the amount of motion in the video; and then multiply that result by 0.07 to get the bit rate in bps. Divide your result by 1,000 to get a kbps estimate or by 1,000,000 to get a Mbps estimate.Kush gauge: pixel count x motion factor x 0.07 ÷ 1000 = bit rate in kbps
(frame width x height = pixel count) and motion factor is 1,2 or 4

Screencast example
For example if your video is a low motion 5fps screen cast in a 1280 x 720 frame size you would have a formula like this:

1280 x 720 = 921,600 pixel count 
5 frames per second 
1 = Low Motion 

(921,600 x 5) x 1 x 0.07 = 322,560 bps / 1000 = 322 kbps bitrate

High action video example
Another example on the other side of the spectrum would be a 24 fps high action shot of an action scene with multiple quick cuts in a 1920 x 1080 frame size:

1920 x 1080 = 2,073,600 pixel count 
24 frames per second 
4 = High Motion 

(2,073,600 x 24) x 4 x 0.07 = 13,934,592 bps / 1000 = 13,934 kbps bitrate

For streaming this example would be a bad idea, unless your target audience lives in South Korea. If you do decide to offer a super high quality file, be sure to also encode a lower quality streaming video for clients that may not have the fastest broadband available.

When using this gauge with a variable bitrate (VBR), 75% of the resulting bitrate can be used for the minimum rate and 150% for the maximum rate.

If you do not want to do the math this bitrate calculator will give you a similar result:

http://www.adobe.com/jp/devnet/flash/apps/flv_bitrate_calculator.html

5. Starting Points

If you are completely lost right now and having trouble deciding what your video bitrate should be here are some starting points for you to experiment with for a streaming connection:

Output sizeBitrateFilesize
320×240 pixels400 kbps3MB / minute
480×270 pixels700 kbps5MB / minute
1024 x 576 pixels1500 kbps11MB / minute
1280×720 pixels2500 kbps19MB / minute
1920×1080 pixels4000 kbps30MB / minute

In general though we recommend a bitrate of around 2 – 2.5 Mbps, which takes into account the average worldwide broadband connections. Once again we do however suggest you experiment with different settings and see how they work for you.

6. The Other Side of the Equation

Once you have your video bitrate defined, you will still have to decide how to set the encoding for your audio. Most of the settings are straight forward because they can be copied from your source file, but if your file is slightly above your targeted bitrate you can make some small cutbacks on the audio. Even at extremely low bit rates, reasonable audio quality can be achieved.

First you need to figure out if you are going to encode with Mono or Stereo. If your source video was filmed in mono there is no reason to encode in stereo. You can however reduce a stereo stream to mono and it is generally advisable if the video is a simple speech. Talking head videos are usually good candidates for selecting mono over stereo.

For your sampling frequency it is suggested that you maintain around 44.1 kHz for most of your videos or 22.05 kHZ if once again you are recording only a simple speech. Anything below 22.05 kHz will begin to degrade and distort low volume sounds such as breathing to the point where it is noticeable. While above 44.1 kHz is mainly for audio focused projects.

In the end you will probably be looking at 96 – 164kbps for a stereo music tracks, for the same track in mono, bit rates as low as 56 – 80kbps may still be acceptable. If you are once again dealing with speech only tracks you can probably even get comprehensible sound as low as 16 – 24 kbps.

Parting advice

Overall there is no set guideline as to what your video’s compression should be. Do not expect to find a simple universal number to input. For every video this is a decision based on your client’s connection speed and the quality you want to maintain for your file.

Source: https://www.ezs3.com/public/What_bitrate_should_I_use_when_encoding_my_video_How_do_I_optimize_my_video_for_the_web.cfm

Java – How to Use Comparator?

Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines precisely what sorted order means.

The Comparator interface defines two methods: compare( ) and equals( ). The compare( ) method, shown here, compares two elements for order −

The compare Method

int compare(Object obj1, Object obj2)

obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.

By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison.

The equals Method

The equals( ) method, shown here, tests whether an object equals the invoking comparator −

boolean equals(Object obj)

obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false.

Overriding equals( ) is unnecessary, and most simple comparators will not do so.

Example

import java.util.*;

class Dog implements Comparator<Dog>, Comparable<Dog> {
   private String name;
   private int age;
   Dog() {
   }

   Dog(String n, int a) {
      name = n;
      age = a;
   }

   public String getDogName() {
      return name;
   }

   public int getDogAge() {
      return age;
   }

   // Overriding the compareTo method
   public int compareTo(Dog d) {
      return (this.name).compareTo(d.name);
   }

   // Overriding the compare method to sort the age 
   public int compare(Dog d, Dog d1) {
      return d.age - d1.age;
   }
}

public class Example {

   public static void main(String args[]) {
      // Takes a list o Dog objects
      List<Dog> list = new ArrayList<Dog>();

      list.add(new Dog("Shaggy", 3));
      list.add(new Dog("Lacy", 2));
      list.add(new Dog("Roger", 10));
      list.add(new Dog("Tommy", 4));
      list.add(new Dog("Tammy", 1));
      Collections.sort(list);   // Sorts the array list

      for(Dog a: list)   // printing the sorted list of names
         System.out.print(a.getDogName() + ", ");

      // Sorts the array list using comparator
      Collections.sort(list, new Dog());
      System.out.println(" ");
      
      for(Dog a: list)   // printing the sorted list of ages
         System.out.print(a.getDogName() +"  : "+ a.getDogAge() + ", ");
   }
}

This will produce the following result −

Output

Lacy, Roger, Shaggy, Tammy, Tommy,
Tammy  : 1, Lacy  : 2, Shaggy  : 3, Tommy  : 4, Roger  : 10,

Note − Sorting of the Arrays class is as the same as the Collections.

Java – How to Use Iterator?

Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.

Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.

In general, to use an iterator to cycle through the contents of a collection, follow these steps −

  • Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method.
  • Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
  • Within the loop, obtain each element by calling next( ).

For collections that implement List, you can also obtain an iterator by calling ListIterator.

The Methods Declared by Iterator

Sr.No. Method & Description
1 boolean hasNext( )Returns true if there are more elements. Otherwise, returns false.
2 Object next( )Returns the next element. Throws NoSuchElementException if there is not a next element.
3 void remove( )Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).

The Methods Declared by ListIterator

Sr.No. Method & Description
1 void add(Object obj)Inserts obj into the list in front of the element that will be returned by the next call to next( ).
2 boolean hasNext( )Returns true if there is a next element. Otherwise, returns false.
3 boolean hasPrevious( )Returns true if there is a previous element. Otherwise, returns false.
4 Object next( )Returns the next element. A NoSuchElementException is thrown if there is not a next element.
5 int nextIndex( )Returns the index of the next element. If there is not a next element, returns the size of the list.
6 Object previous( )Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.
7 int previousIndex( )Returns the index of the previous element. If there is not a previous element, returns -1.
8 void remove( )Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.
9 void set(Object obj)Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).

Example

Here is an example demonstrating both Iterator and ListIterator. It uses an ArrayList object, but the general principles apply to any type of collection.

Of course, ListIterator is available only to those collections that implement the List interface. Live Demo

import java.util.*;
public class IteratorDemo {

   public static void main(String args[]) {
      // Create an array list
      ArrayList al = new ArrayList();
      
      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");

      // Use iterator to display contents of al
      System.out.print("Original contents of al: ");
      Iterator itr = al.iterator();
      
      while(itr.hasNext()) {
         Object element = itr.next();
         System.out.print(element + " ");
      }
      System.out.println();
      
      // Modify objects being iterated
      ListIterator litr = al.listIterator();
      
      while(litr.hasNext()) {
         Object element = litr.next();
         litr.set(element + "+");
      }
      System.out.print("Modified contents of al: ");
      itr = al.iterator();
      
      while(itr.hasNext()) {
         Object element = itr.next();
         System.out.print(element + " ");
      }
      System.out.println();

      // Now, display the list backwards
      System.out.print("Modified list backwards: ");
      
      while(litr.hasPrevious()) {
         Object element = litr.previous();
         System.out.print(element + " ");
      }
      System.out.println();
   }
}

This will produce the following result −

Output

Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+

Source: https://www.tutorialspoint.com/java/java_using_iterator.htm