text:
package com.sprinjinc.bestfriend;

import android.app.ActionBar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;

import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.sprinjinc.bestfriend.adapter.FeedListAdapter;
import com.sprinjinc.bestfriend.app.AppController;
import com.sprinjinc.bestfriend.data.FeedItem;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;

import com.android.volley.Cache;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;

public class QuestionStreamActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    private static final String TAG = QuestionStreamActivity.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    FeedItem item;

    TextView textView_username_navHeader;
    TextView textView_email_navHeader;
    ImageView imageView_newImg;
    View navigationHeader;
    private ProgressDialog mProgressDialog;
    Uri status_image = null;

    public static String _username;
    String _emailAddress;
    int total_post;
    private final int GALLARY_REQUEST_CODE = 8725;
    final String storage_image_folder = "status_images";
    //boolean[] isLovedList = new boolean[total_post];

    private DatabaseReference mDatabaseRef;
    FirebaseStorage storage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_question_stream);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final Intent askMeIntent = new Intent(this, AskMeActivity.class);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(askMeIntent);
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        setTitle("");
        navigationView.setCheckedItem(R.id.nav_question_stream);

        imageView_newImg = (ImageView) findViewById(R.id.imageView_newImage);
        imageView_newImg.setVisibility(View.GONE);

        findViewById(R.id.imageButton_photoUpload).setOnClickListener(this);
        findViewById(R.id.imageButton_postDone).setOnClickListener(this);

        listView = (ListView) findViewById(R.id.list);

        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);

        // We first check for cached request
        /*Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Entry entry = cache.get(URL_FEED);
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonFeed(new JSONObject(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        } else {
            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                    URL_FEED, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    VolleyLog.d(TAG, "Response: " + response.toString());
                    if (response != null) {
                        parseJsonFeed(response);
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                }
            });

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
        }*/

        FirebaseUser currentFirebaseUser = HomeActivity.mFirebaseAuth.getCurrentUser();

        HomeActivity.database = FirebaseDatabase.getInstance();
        mDatabaseRef = HomeActivity.database.getReference();

        storage = FirebaseStorage.getInstance();

        navigationHeader = navigationView.getHeaderView(0);
        /*View view=navigationView.inflateHeaderView(R.layout.nav_header_main);*/
        textView_username_navHeader = (TextView) navigationHeader.findViewById(R.id.textView_username_navHeader);
        textView_email_navHeader = (TextView) navigationHeader.findViewById(R.id.textView_email_navHeader);

        navigationHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent personalAccountActivity = new Intent(QuestionStreamActivity.this, PersonalAccountActivity.class);
                startActivity(personalAccountActivity);
            }
        });

        showProgressDialog();

        //final String _uid = currentFirebaseUser.getUid();

        /*mDatabaseRef.child("users").child(currentFirebaseUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    User user = dataSnapshot.getValue(User.class);

                    /*_username = user.getUsername();
                    _emailAddress = user.getEmail();

                    textView_username_navHeader.setText(_username);
                    textView_email_navHeader.setText(_emailAddress);*---/

                    //Log.d(TAG, "User name: " + user.getName() + ", email " + user.getEmail());
                } else {
                   /*Toast.makeText(QuestionStreamActivity.this, "Failed to get user information.", Toast.LENGTH_SHORT).show();

                    _username = "Android Studio";
                    _emailAddress = "android.studio@android.com";*---/
                }

                hideProgressDialog();
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                //Log.w(TAG, "Failed to read value.", error.toException());
                Toast.makeText(QuestionStreamActivity.this, "Failed to read value.", Toast.LENGTH_SHORT).show();
                hideProgressDialog();
            }
        });*/

        /*mDatabaseRef.child("all_posts").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists())
                    getAllPosts((Map<String,Object>) dataSnapshot.getValue());
                else
                    Toast.makeText(QuestionStreamActivity.this, "Failed to get posts.", Toast.LENGTH_SHORT).show();

                hideProgressDialog();
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Toast.makeText(QuestionStreamActivity.this, "Failed to read value.", Toast.LENGTH_SHORT).show();

                hideProgressDialog();
            }
        });*/

        mDatabaseRef.child("users").child(currentFirebaseUser.getUid()).child("username").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    _username = dataSnapshot.getValue().toString();
                } else {
                   Toast.makeText(QuestionStreamActivity.this, "Failed to get username.", Toast.LENGTH_SHORT).show();

                    _username = "Anonymous";
                }

                textView_username_navHeader.setText(_username);

                hideProgressDialog();
            }

            @Override
            public void onCancelled(DatabaseError error) {
                Toast.makeText(QuestionStreamActivity.this, "Failed to read value.", Toast.LENGTH_SHORT).show();
                textView_username_navHeader.setText("Anonymous");
                hideProgressDialog();
            }
        });

        mDatabaseRef.child("users").child(currentFirebaseUser.getUid()).child("email").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    _emailAddress = dataSnapshot.getValue().toString();
                } else {
                    Toast.makeText(QuestionStreamActivity.this, "Failed to get email.", Toast.LENGTH_SHORT).show();

                    _emailAddress = "anonymous@android.com";
                }

                textView_email_navHeader.setText(_emailAddress);

                hideProgressDialog();
            }

            @Override
            public void onCancelled(DatabaseError error) {
                Toast.makeText(QuestionStreamActivity.this, "Failed to read value.", Toast.LENGTH_SHORT).show();
                textView_email_navHeader.setText("anonymous@android.com");
                hideProgressDialog();
            }
        });

        mDatabaseRef.child("post_count").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    total_post = Integer.parseInt(dataSnapshot.getValue().toString());

                    /*int i;

                    for (i = 1; i <= total_post; i++) {
                        mDatabaseRef.child("all_posts").child("post_" + String.valueOf(i)).addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                if (dataSnapshot.exists()) {
                                    //getAllPosts((Map<String,Object>) dataSnapshot.getValue());
                                } else
                                    Toast.makeText(QuestionStreamActivity.this, "Failed to get posts.", Toast.LENGTH_SHORT).show();

                                hideProgressDialog();
                            }

                            @Override
                            public void onCancelled(DatabaseError error) {
                                // Failed to read value
                                Toast.makeText(QuestionStreamActivity.this, "Failed to read value.", Toast.LENGTH_SHORT).show();

                                hideProgressDialog();
                            }
                        });
                    }*/
                } else
                    Toast.makeText(QuestionStreamActivity.this, "Failed to get total post number.", Toast.LENGTH_SHORT).show();

                hideProgressDialog();
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Toast.makeText(QuestionStreamActivity.this, "Failed to read value.", Toast.LENGTH_SHORT).show();
            }
        });

        mDatabaseRef.child("all_posts").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    //Map <String, Map <String, Object> > posts = new HashMap <>();

                    for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                        int id = Integer.parseInt(postSnapshot.child("id").getValue().toString());
                        //Toast.makeText(QuestionStreamActivity.this, "ID :: " + String.valueOf(id), Toast.LENGTH_SHORT).show();
                        int totalComments = Integer.parseInt(postSnapshot.child("totalComments").getValue().toString());
                        boolean lovedByCurrentUser = Boolean.valueOf(postSnapshot.child("lovedByCurrentUser").getValue().toString());
                        String name = postSnapshot.child("name").getValue().toString();
                        String status = postSnapshot.child("status").getValue().toString();
                        String timeStamp = postSnapshot.child("timeStamp").getValue().toString();

                        Map<String, Object> single_post = new HashMap<String, Object>();

                        single_post.put("id", id);
                        single_post.put("totalComments", totalComments);
                        single_post.put("lovedByCurrentUser", lovedByCurrentUser);
                        single_post.put("name", name);
                        single_post.put("status", status);
                        single_post.put("timeStamp", timeStamp);

                        getSinglePost(single_post);

                        //posts.put("post_" + String.valueOf(id), single_post);
                    }

                    listAdapter.notifyDataSetChanged();

                    //Toast.makeText(QuestionStreamActivity.this, "status of 2nd post :: " + posts.get("post_2").get("status").toString(), Toast.LENGTH_LONG).show();

                    //getAllPosts(posts);
                } else
                    Toast.makeText(QuestionStreamActivity.this, "Failed to get posts.", Toast.LENGTH_SHORT).show();

                hideProgressDialog();
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Toast.makeText(QuestionStreamActivity.this, "Failed to read value.", Toast.LENGTH_SHORT).show();

                hideProgressDialog();
            }
        });

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            int lastFirstVisibleItem;
            int lastLastVisibleItem;

            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int i;
                lastFirstVisibleItem = listView.getFirstVisiblePosition();
                lastLastVisibleItem = listView.getLastVisiblePosition();

                lastLastVisibleItem = ((lastLastVisibleItem == -1) ? 0 : lastLastVisibleItem);
                lastFirstVisibleItem = ((lastFirstVisibleItem == -1) ? 0 : lastFirstVisibleItem);

                lastFirstVisibleItem = firstVisibleItem;
                lastLastVisibleItem = listView.getLastVisiblePosition();
            }

            public void onScrollStateChanged(AbsListView view, int scrollState) {
                int i;

                for (i = 0; i < total_post; i++) {
                    final int position = i;

                    ImageButton love_btn = (ImageButton) (getViewByPosition(i, listView).findViewById(R.id.imageButton_love));
                    love_btn.setImageResource(R.drawable.love_button_not_clicked);

                    int postID = (int) love_btn.getTag(R.id.loveButtonCurrentItemID);

                    mDatabaseRef.child("loves").child("post_" + String.valueOf(postID)).child(_username).addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            // If child exists, it means the user loved the status.
                            if (dataSnapshot.exists()) {
                                ImageButton love_btn = (ImageButton) (getViewByPosition(position, listView).findViewById(R.id.imageButton_love));
                                love_btn.setImageResource(R.drawable.love_button_clicked);

                            } else {
                                ImageButton love_btn = (ImageButton) (getViewByPosition(position, listView).findViewById(R.id.imageButton_love));
                                love_btn.setImageResource(R.drawable.love_button_not_clicked);
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError error) {
                            // Failed to read value
                            // Toast.makeText(activity.getApplicationContext(), "Failed to read value.", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                /*if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {

                }*/
            }
        });

    }

    /*private void showLoved(final int position) {
        ImageView love_btn = (ImageView) (getViewByPosition(position, listView).findViewById(R.id.imageButton_love));
        love_btn.setImageResource(R.drawable.love_button_not_clicked);

        //Toast.makeText(QuestionStreamActivity.this, "Came here at least!", Toast.LENGTH_SHORT).show();

        mDatabaseRef.child("loves").child("post_" + String.valueOf(position + 1)).child(_username).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // If child exists, it means the user loved the status.
                if (dataSnapshot.exists()) {
                    //FeedItem item = (FeedItem) getViewByPosition(position - 1, listView);
                    FeedItem item = (FeedItem) listView.getItemAtPosition(position);
                    item.setLovedByCurrentUser(true);

                    //Toast.makeText(QuestionStreamActivity.this, item.getName() + " :: " + "Loved item position : " + String.valueOf(position - 1), Toast.LENGTH_SHORT).show();

                    ImageView love_btn = (ImageView) (getViewByPosition(position, listView).findViewById(R.id.imageButton_love));
                    love_btn.setImageResource(R.drawable.love_button_clicked);
                } else {
                    FeedItem item = (FeedItem) listView.getItemAtPosition(position);
                    item.setLovedByCurrentUser(false);

                    ImageView love_btn = (ImageView) (getViewByPosition(position, listView).findViewById(R.id.imageButton_love));
                    love_btn.setImageResource(R.drawable.love_button_not_clicked);

                    //Toast.makeText(QuestionStreamActivity.this, item.getName() + " :: " + String.valueOf(position - 1) + ".", Toast.LENGTH_SHORT).show();
                    //Toast.makeText(QuestionStreamActivity.this, "It does not exist for position " + String.valueOf(position - 1) + ".", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                // Toast.makeText(activity.getApplicationContext(), "Failed to read value.", Toast.LENGTH_SHORT).show();
            }
        });
    }*/

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
            //Toast.makeText(QuestionStreamActivity.this, getFragmentManager().getBackStackEntryAt(0).toString(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.personal_account, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_share) {
            Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            String shareBodyText = "Bestfriend is a great app! :D";
            sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Bestfriend App");
            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
            startActivity(Intent.createChooser(sharingIntent, "Sharing Option"));

            return true;
        } else if (id == R.id.action_exit) {
            /*FragmentManager fm = getSupportFragmentManager();

            for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
                fm.popBackStack();
            }
            fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);*/

            super.onBackPressed();

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /*
    --- This method comes with the code of "if (id == R.id.action_share)" in the upper method.
    --- For details, http://www.viralandroid.com/2016/05/adding-share-action-to-android-app.html

    public void shareText(View view) {
        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("text/plain");
        String shareBodyText = "Your shearing message goes here";
        intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject/Title");
        intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
        startActivity(Intent.createChooser(intent, "Choose sharing method"));
    }*/

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_ask_me) {
            Intent askMeIntent = new Intent(this, AskMeActivity.class);
            startActivity(askMeIntent);

        } else if (id == R.id.nav_question_stream) {
            // Do nothing

        } else if (id == R.id.nav_about) {
            Intent aboutUsIntent = new Intent(this, AboutUsActivity.class);
            startActivity(aboutUsIntent);

        } else if (id == R.id.nav_support) {
            Intent supportIntent = new Intent(this, SupportActivity.class);
            startActivity(supportIntent);

        } else if (id == R.id.nav_sign_out) {
            signOut();

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void signOut() {
        HomeActivity.mFirebaseAuth.signOut();
        //updateUI(null);
        Intent signOutIntent = new Intent(this, HomeActivity.class);
        signOutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(signOutIntent);
    }

    /*
        If anything is clicked on current activity ------------------------------------------------
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id) {
            case R.id.imageButton_postDone:
                // First upload the image if there's any
                if (status_image != null) {
                    StorageReference profileImageRef;

                    // Create a storage reference from our app
                    profileImageRef = storage.getReference(storage_image_folder + "/" + "image_for_post_" + String.valueOf(total_post + 1) + ".png");

                    showProgressDialog();
                    Toast.makeText(QuestionStreamActivity.this, "Updating post...", Toast.LENGTH_LONG).show();
                    UploadTask uploadTask = profileImageRef.putFile(status_image);

                    // Register observers to listen for when the download is done or if it fails
                    uploadTask.addOnFailureListener(QuestionStreamActivity.this, new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            // Handle unsuccessful uploads
                            hideProgressDialog();
                            Toast.makeText(QuestionStreamActivity.this, "Updating failed.", Toast.LENGTH_LONG).show();

                            /*FirebaseUser user = HomeActivity.mFirebaseAuth.getCurrentUser();
                            updateUI(user);*/
                        }
                    }).addOnSuccessListener(QuestionStreamActivity.this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                            hideProgressDialog();

                            Uri downloadUrl = taskSnapshot.getDownloadUrl();

                            // Now update database
                            long unixTimeInMilis = System.currentTimeMillis();

                            uploadStatus(total_post + 1, _username, downloadUrl.toString(),
                                    ((EditText) findViewById(R.id.editText_newStatus)).getText().toString(), String.valueOf(unixTimeInMilis), null);

                            total_post++;

                            DatabaseReference postCountRef = HomeActivity.database.getReference();;
                            postCountRef.child("post_count").setValue(total_post);

                            Toast.makeText(QuestionStreamActivity.this, "Status updated.", Toast.LENGTH_LONG).show();

                            status_image = null;
                            imageView_newImg.setVisibility(View.GONE);
                            ((EditText) findViewById(R.id.editText_newStatus)).setText("");

                            /*FirebaseUser user = HomeActivity.mFirebaseAuth.getCurrentUser();
                            updateUI(user);*/
                        }
                    });
                } else {
                    long unixTimeInMilis = System.currentTimeMillis();

                    uploadStatus(total_post + 1, _username, null,
                            ((EditText) findViewById(R.id.editText_newStatus)).getText().toString(), String.valueOf(unixTimeInMilis), null);

                    total_post++;

                    DatabaseReference postCountRef = HomeActivity.database.getReference();
                    postCountRef.child("post_count").setValue(total_post);

                    Toast.makeText(QuestionStreamActivity.this, "Status updated.", Toast.LENGTH_LONG).show();

                    status_image = null;
                    imageView_newImg.setVisibility(View.GONE);
                    ((EditText) findViewById(R.id.editText_newStatus)).setText("");
                }

                break;

            case R.id.imageButton_photoUpload:
                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                photoPickerIntent.setType("image/*");
                startActivityForResult(photoPickerIntent, GALLARY_REQUEST_CODE);

                break;
        }
    }

    private void uploadStatus(int id, String name, String image, String status, String timeStamp, String url) {
        // creating feeditem object
        FeedItem newStatus = new FeedItem(id, name, image, status, timeStamp, url);

        // pushing feeditem to 'posts' node
        mDatabaseRef = HomeActivity.database.getReference("all_posts");
        mDatabaseRef.child("post_" + String.valueOf(total_post + 1)).setValue(newStatus);

        feedItems.add(0, newStatus);
        ((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();

        smoothScrollToPositionFromTop(listView, 0);
    }

    public static void smoothScrollToPositionFromTop(final AbsListView view, final int position) {
        View child = getChildAtPosition(view, position);
        // There's no need to scroll if child is already at top or view is already scrolled to its end
        if ((child != null) && ((child.getTop() == 0) || ((child.getTop() > 0) && !view.canScrollVertically(1)))) {
            return;
        }

        view.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(final AbsListView view, final int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE) {
                    view.setOnScrollListener(null);

                    // Fix for scrolling bug
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            view.setSelection(position);
                        }
                    });
                }
            }

            @Override
            public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount,
                                 final int totalItemCount) { }
        });

        // Perform scrolling to position
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                view.smoothScrollToPositionFromTop(position, 0);
            }
        });
    }

    public static View getChildAtPosition(final AdapterView view, final int position) {
        final int index = position - view.getFirstVisiblePosition();
        if ((index >= 0) && (index < view.getChildCount())) {
            return view.getChildAt(index);
        } else {
            return null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLARY_REQUEST_CODE)
            if (resultCode == Activity.RESULT_OK) {
                status_image = data.getData();
                imageView_newImg.setVisibility(View.VISIBLE);
                imageView_newImg.setImageURI(status_image);
                /*imageView_newImg
                        .setResponseObserver(new FeedImageView.ResponseObserver() {
                            @Override
                            public void onError() {
                            }

                            @Override
                            public void onSuccess() {
                            }
                        });*/
            } else if (resultCode == Activity.RESULT_CANCELED) {
                status_image = null;
                imageView_newImg.setVisibility(View.GONE);
            }
    }

    /*private void getAllPosts(Map<String, Map<String, Object> > users) {

        //iterate through each user, ignoring their UID
        //for (Map.Entry<String, Map > entry : users.entrySet()){

        int i;

        for (i = 1; i <= users.size(); i++) {

            //Get user map
            Map singleUser = (Map) users.get("post_" + i);

            item = new FeedItem();

            item.setId( Integer.parseInt(singleUser.get("id").toString()) );
            item.setName(singleUser.get("name").toString());

            // Image might be null sometimes
            String image = singleUser.containsKey("image") ? singleUser.get("image").toString() : null;
            item.setImage(image);

            item.setStatus(singleUser.get("status").toString());
            item.setTimeStamp(singleUser.get("timeStamp").toString());

            // url might be null sometimes
            String feedUrl = singleUser.containsKey("url") ? singleUser.get("url").toString() : null;
            item.setUrl(feedUrl);

            feedItems.add(0, item);
        }

        listAdapter.notifyDataSetChanged();
    }*/

    private void getSinglePost(Map<String, Object> single_post) {

        //iterate through each user, ignoring their UID
        //for (Map.Entry<String, Map > entry : users.entrySet()){

        //Get user map

        item = new FeedItem();

        item.setId( Integer.parseInt(single_post.get("id").toString()) );
        item.setName(single_post.get("name").toString());

        // Image might be null sometimes
        String image = single_post.containsKey("image") ? single_post.get("image").toString() : null;
        item.setImage(image);

        item.setStatus(single_post.get("status").toString());
        item.setTimeStamp(single_post.get("timeStamp").toString());

        // url might be null sometimes
        String feedUrl = single_post.containsKey("url") ? single_post.get("url").toString() : null;
        item.setUrl(feedUrl);

        feedItems.add(0, item);
    }

    /*private static Map<String, Object> sortByValue(Map<String, Object> unsortMap) {

        // 1. Convert Map to List of Map
        List<Map.Entry<String, Object>> list =
                new LinkedList<Map.Entry<String, Object>>(unsortMap.entrySet());

        // 2. Sort list with Collections.sort(), provide a custom Comparator
        //    Try switch the o1 o2 position for a different order
        Collections.sort(list, new Comparator<Map.Entry<String, Object>>() {
            public int compare(Map.Entry<String, Object> o1,
                               Map.Entry<String, Object> o2) {
                return (o1.getValue().toString()).compareTo(o2.getValue().toString());
            }
        });

        // 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap
        Map<String, Object> sortedMap = new LinkedHashMap<String, Object>();
        for (Map.Entry<String, Object> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        /*
        //classic iterator example
        for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext(); ) {
            Map.Entry<String, Integer> entry = it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }*-------------------------------/

        return sortedMap;
    }*/

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage(getString(R.string.loading));
            mProgressDialog.setIndeterminate(true);
            //mProgressDialog.setCanceledOnTouchOutside(false);
        }

        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.hide();
        }
    }

    public void love_clicked(final View view) {
        /*ImageButton imageButton_love = (ImageButton) view;

        if (imageButton_love.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.love_button_not_clicked).getConstantState()) {
            imageButton_love.setImageResource(R.drawable.love_button_clicked);
        } else {
            imageButton_love.setImageResource(R.drawable.love_button_not_clicked);
        }*/

        // Get the comments
        /*mDatabaseRef.child("comments").child("comments_for_post_" + post_id).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int id = Integer.parseInt(view.getTag(R.id.loveButtonCurrentItemID).toString());

                if(dataSnapshot.exists()){
                    listView_comment.setVisibility(View.VISIBLE);
                    getAllComments((Map<String, String>) dataSnapshot.getValue());
                } else {
                    listView_comment.setVisibility(View.GONE);
                }
                hideProgressDialog();
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Toast.makeText(CommentActivity.this, "Failed to read value.", Toast.LENGTH_SHORT).show();
            }
        });*/
    }

    public View getViewByPosition(int pos, ListView listView) {
        final int firstListItemPosition = listView.getFirstVisiblePosition();
        final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

        if (pos < firstListItemPosition || pos > lastListItemPosition ) {
            return listView.getAdapter().getView(pos, null, listView);
            //return null;
        } else {
            final int childIndex = pos - firstListItemPosition;
            return listView.getChildAt(childIndex);
        }
    }

    public void comment_clicked(View view) {
        int id = (int) view.getTag(R.id.commentButtonCurrentItemID);
        // We have to state that are intention is to open another Activity. We do so
        // by passing a Context and the Activity that we want to open
        Intent commentActivityIntent = new Intent(this, CommentActivity.class);

        // To send data use putExtra with a String name followed by its value
        commentActivityIntent.putExtra("post_id", id);
        startActivity(commentActivityIntent);
    }

    public void share_clicked(View view) {
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBodyText = (String) view.getTag(R.id.commentButtonCurrentItemStatus);
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Bestfriend status");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
        startActivity(Intent.createChooser(sharingIntent, "Sharing Option"));
    }
}


text:
using System.Web.Mvc;
using Nop.Core.Infrastructure;

namespace Nop.Web.Framework.UI
{
    /// <summary>
    /// Layout extensions
    /// </summary>
    public static class LayoutExtensions
    {
        /// <summary>
        /// Add title element to the <![CDATA[<head>]]>
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Title part</param>
        public static void AddTitleParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder  = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AddTitleParts(part);
        }
        /// <summary>
        /// Append title element to the <![CDATA[<head>]]>
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Title part</param>
        public static void AppendTitleParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder  = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AppendTitleParts(part);
        }
        /// <summary>
        /// Generate all title parts
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="addDefaultTitle">A value indicating whether to insert a default title</param>
        /// <param name="part">Title part</param>
        /// <returns>Generated string</returns>
        public static MvcHtmlString NopTitle(this HtmlHelper html, bool addDefaultTitle = true, string part = "")
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            html.AppendTitleParts(part);
            return MvcHtmlString.Create(html.Encode(pageHeadBuilder.GenerateTitle(addDefaultTitle)));
        }

        /// <summary>
        /// Add meta description element to the <![CDATA[<head>]]>
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Meta description part</param>
        public static void AddMetaDescriptionParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AddMetaDescriptionParts(part);
        }
        /// <summary>
        /// Append meta description element to the <![CDATA[<head>]]>
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Meta description part</param>
        public static void AppendMetaDescriptionParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AppendMetaDescriptionParts(part);
        }
        /// <summary>
        /// Generate all description parts
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Meta description part</param>
        /// <returns>Generated string</returns>
        public static MvcHtmlString NopMetaDescription(this HtmlHelper html, string part = "")
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            html.AppendMetaDescriptionParts(part);
            return MvcHtmlString.Create(html.Encode(pageHeadBuilder.GenerateMetaDescription()));
        }

        /// <summary>
        /// Add meta keyword element to the <![CDATA[<head>]]>
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Meta keyword part</param>
        public static void AddMetaKeywordParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AddMetaKeywordParts(part);
        }
        /// <summary>
        /// Append meta keyword element to the <![CDATA[<head>]]>
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Meta keyword part</param>
        public static void AppendMetaKeywordParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AppendMetaKeywordParts(part);
        }
        /// <summary>
        /// Generate all keyword parts
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Meta keyword part</param>
        /// <returns>Generated string</returns>
        public static MvcHtmlString NopMetaKeywords(this HtmlHelper html, string part = "")
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            html.AppendMetaKeywordParts(part);
            return MvcHtmlString.Create(html.Encode(pageHeadBuilder.GenerateMetaKeywords()));
        }

        /// <summary>
        /// Add script element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Script part</param>
        /// <param name="excludeFromBundle">A value indicating whether to exclude this script from bundling</param>
        /// <param name="isAsync">A value indicating whether to add an attribute "async" or not for js files</param>
        public static void AddScriptParts(this HtmlHelper html, string part, bool excludeFromBundle = false, bool isAsync = false)
        {
            AddScriptParts(html, ResourceLocation.Head, part, excludeFromBundle, isAsync);
        }
        /// <summary>
        /// Add script element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="location">A location of the script element</param>
        /// <param name="part">Script part</param>
        /// <param name="excludeFromBundle">A value indicating whether to exclude this script from bundling</param>
        /// <param name="isAsync">A value indicating whether to add an attribute "async" or not for js files</param>
        public static void AddScriptParts(this HtmlHelper html, ResourceLocation location, string part, bool excludeFromBundle = false, bool isAsync = false)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AddScriptParts(location, part, excludeFromBundle, isAsync);
        }
        /// <summary>
        /// Append script element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Script part</param>
        /// <param name="excludeFromBundle">A value indicating whether to exclude this script from bundling</param>
        /// <param name="isAsync">A value indicating whether to add an attribute "async" or not for js files</param>
        public static void AppendScriptParts(this HtmlHelper html, string part, bool excludeFromBundle = false, bool isAsync = false)
        {
            AppendScriptParts(html, ResourceLocation.Head, part, excludeFromBundle, isAsync);
        }
        /// <summary>
        /// Append script element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="location">A location of the script element</param>
        /// <param name="part">Script part</param>
        /// <param name="excludeFromBundle">A value indicating whether to exclude this script from bundling</param>
        /// <param name="isAsync">A value indicating whether to add an attribute "async" or not for js files</param>
        public static void AppendScriptParts(this HtmlHelper html, ResourceLocation location, string part, bool excludeFromBundle = false, bool isAsync = false)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AppendScriptParts(location, part, excludeFromBundle, isAsync);
        }
        /// <summary>
        /// Generate all script parts
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="urlHelper">URL Helper</param>
        /// <param name="location">A location of the script element</param>
        /// <param name="bundleFiles">A value indicating whether to bundle script elements</param>
        /// <returns>Generated string</returns>
        public static MvcHtmlString NopScripts(this HtmlHelper html, UrlHelper urlHelper,
            ResourceLocation location, bool? bundleFiles = null)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            return MvcHtmlString.Create(pageHeadBuilder.GenerateScripts(urlHelper, location, bundleFiles));
        }

        /// <summary>
        /// Add CSS element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">CSS part</param>
        /// <param name="excludeFromBundle">A value indicating whether to exclude this script from bundling</param>
        public static void AddCssFileParts(this HtmlHelper html, string part, bool excludeFromBundle = false)
        {
            AddCssFileParts(html, ResourceLocation.Head, part, excludeFromBundle);
        }
        /// <summary>
        /// Add CSS element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="location">A location of the script element</param>
        /// <param name="part">CSS part</param>
        /// <param name="excludeFromBundle">A value indicating whether to exclude this script from bundling</param>
        public static void AddCssFileParts(this HtmlHelper html, ResourceLocation location, string part, bool excludeFromBundle = false)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AddCssFileParts(location, part, excludeFromBundle);
        }
        /// <summary>
        /// Append CSS element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">CSS part</param>
        /// <param name="excludeFromBundle">A value indicating whether to exclude this script from bundling</param>
        public static void AppendCssFileParts(this HtmlHelper html, string part, bool excludeFromBundle = false)
        {
            AppendCssFileParts(html, ResourceLocation.Head, part, excludeFromBundle);
        }
        /// <summary>
        /// Append CSS element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="location">A location of the script element</param>
        /// <param name="part">CSS part</param>
        /// <param name="excludeFromBundle">A value indicating whether to exclude this script from bundling</param>
        public static void AppendCssFileParts(this HtmlHelper html, ResourceLocation location, string part, bool excludeFromBundle = false)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AppendCssFileParts(location, part, excludeFromBundle);
        }
        /// <summary>
        /// Generate all CSS parts
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="urlHelper">URL Helper</param>
        /// <param name="location">A location of the script element</param>
        /// <param name="bundleFiles">A value indicating whether to bundle script elements</param>
        /// <returns>Generated string</returns>
        public static MvcHtmlString NopCssFiles(this HtmlHelper html, UrlHelper urlHelper,
            ResourceLocation location, bool? bundleFiles = null)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            return MvcHtmlString.Create(pageHeadBuilder.GenerateCssFiles(urlHelper, location, bundleFiles));
        }

        /// <summary>
        /// Add canonical URL element to the <![CDATA[<head>]]>
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Canonical URL part</param>
        public static void AddCanonicalUrlParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AddCanonicalUrlParts(part);
        }
        /// <summary>
        /// Append canonical URL element to the <![CDATA[<head>]]>
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Canonical URL part</param>
        public static void AppendCanonicalUrlParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AppendCanonicalUrlParts(part);
        }
        /// <summary>
        /// Generate all canonical URL parts
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">Canonical URL part</param>
        /// <returns>Generated string</returns>
        public static MvcHtmlString NopCanonicalUrls(this HtmlHelper html, string part = "")
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            html.AppendCanonicalUrlParts(part);
            return MvcHtmlString.Create(pageHeadBuilder.GenerateCanonicalUrls());
        }

        /// <summary>
        /// Add any custom element to the <![CDATA[<head>]]> element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">The entire element. For example, <![CDATA[<meta name="msvalidate.01" content="123121231231313123123" />]]></param>
        public static void AddHeadCustomParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AddHeadCustomParts(part);
        }
        /// <summary>
        /// Append any custom element to the <![CDATA[<head>]]> element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">The entire element. For example, <![CDATA[<meta name="msvalidate.01" content="123121231231313123123" />]]></param>
        public static void AppendHeadCustomParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AppendHeadCustomParts(part);
        }
        /// <summary>
        /// Generate all custom elements
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <returns>Generated string</returns>
        public static MvcHtmlString NopHeadCustom(this HtmlHelper html)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            return MvcHtmlString.Create(pageHeadBuilder.GenerateHeadCustom());
        }

        /// <summary>
        /// Add CSS class to the <![CDATA[<head>]]> element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">CSS class</param>
        public static void AddPageCssClassParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AddPageCssClassParts(part);
        }
        /// <summary>
        /// Append CSS class to the <![CDATA[<head>]]> element
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">CSS class</param>
        public static void AppendPageCssClassParts(this HtmlHelper html, string part)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.AppendPageCssClassParts(part);
        }
        /// <summary>
        /// Generate all title parts
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="part">CSS class</param>
        /// <param name="includeClassElement">A value indicating whether to include "class" attributes</param>
        /// <returns>Generated string</returns>
        public static MvcHtmlString NopPageCssClasses(this HtmlHelper html, string part = "", bool includeClassElement = true)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            html.AppendPageCssClassParts(part);
            var classes = pageHeadBuilder.GeneratePageCssClasses();

            if (string.IsNullOrEmpty(classes))
                return null;

            var result = includeClassElement ? string.Format("class=\"{0}\"", classes) : classes;
            return MvcHtmlString.Create(result);
        }

        /// <summary>
        /// Specify system name of admin menu item that should be selected (expanded)
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="systemName">System name</param>
        public static void SetActiveMenuItemSystemName(this HtmlHelper html, string systemName)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            pageHeadBuilder.SetActiveMenuItemSystemName(systemName);
        }
        /// <summary>
        /// Get system name of admin menu item that should be selected (expanded)
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <returns>System name</returns>
        public static string GetActiveMenuItemSystemName(this HtmlHelper html)
        {
            var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
            return pageHeadBuilder.GetActiveMenuItemSystemName();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import * as sinon from 'sinon';
import DataGridColumn from "@beakerx/tableDisplay/dataGrid/column/DataGridColumn";
import {expect} from "chai";
import {BeakerXDataGrid} from "@beakerx/tableDisplay/dataGrid/BeakerXDataGrid";
import modelStateMock from "../mock/modelStateMock";
import ColumnManager from "@beakerx/tableDisplay/dataGrid/column/ColumnManager";
import cellConfigMock from "../mock/cellConfigMock";
import createStore from "@beakerx/tableDisplay/dataGrid/store/BeakerXDataStore";
import {COLUMN_TYPES} from "@beakerx/tableDisplay/dataGrid/column/enums";

describe('ColumnManager', () => {
  let dataGrid;
  let dataStore;
  let columnManager;

  before(() => {
    dataStore = createStore(modelStateMock);
    dataGrid = new BeakerXDataGrid({}, dataStore);
    columnManager = dataGrid.columnManager;
  });

  after(() => {
    dataGrid.destroy();
  });

  it('should create index column', () => {
    expect(columnManager.columns).to.have.property(`${COLUMN_TYPES.index}`);
    expect(columnManager.columns[COLUMN_TYPES.index]).to.have.length(1);
    expect(columnManager.columns[COLUMN_TYPES.index][0]).to.be.an.instanceof(DataGridColumn);
  });

  it('should create body column', () => {
    expect(columnManager.columns).to.have.property(`${COLUMN_TYPES.body}`);
    expect(columnManager.columns[COLUMN_TYPES.body]).to.have.length(2);
    expect(columnManager.columns[COLUMN_TYPES.body][0]).to.be.an.instanceof(DataGridColumn);
  });

  it('should return column', () => {
    expect(columnManager.getColumn(cellConfigMock)).to.equal(columnManager.columns[COLUMN_TYPES.body][0]);
  });

  it('should return column by column name', () => {
    expect(columnManager.getColumnByName('test')).to.equal(columnManager.columns[COLUMN_TYPES.body][0]);
  });

  it('should implement destroy method', () => {
    const destroyStub = sinon.stub(columnManager, 'destroyAllColumns');

    columnManager.destroy();
    expect(destroyStub.calledOnce).to.be.true;
    destroyStub.restore();
  });
});


text:
/*
  Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"

/*
  Forward declarations.
*/
static MagickBooleanType
  WriteMASKImage(const ImageInfo *,Image *,ExceptionInfo *);

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d M A S K I m a g e                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadMASKImage returns the image mask associated with the image.
%
%  The format of the ReadMASKImage method is:
%
%      Image *ReadMASKImage(const ImageInfo *image_info,
%        ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadMASKImage(const ImageInfo *image_info,
  ExceptionInfo *exception)
{
  Image
    *image;

  ImageInfo
    *read_info;

  /*
    Initialize Image structure.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  read_info=CloneImageInfo(image_info);
  SetImageInfoBlob(read_info,(void *) NULL,0);
  (void) CopyMagickString(read_info->magick,"MIFF",MagickPathExtent);
  image=ReadImage(read_info,exception);
  read_info=DestroyImageInfo(read_info);
  if (image != (Image *) NULL)
    {
      MagickBooleanType
        status;

      status=GrayscaleImage(image,image->intensity,exception);
      if (status == MagickFalse)
        image=DestroyImage(image);
    }
  return(GetFirstImageInList(image));
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e g i s t e r M A S K I m a g e                                         %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  RegisterMASKImage() adds attributes for the MASK image format to
%  the list of supported formats.  The attributes include the image format
%  tag, a method to read and/or write the format, whether the format
%  supports the saving of more than one frame to the same file or blob,
%  whether the format supports native in-memory I/O, and a brief
%  description of the format.
%
%  The format of the RegisterMASKImage method is:
%
%      size_t RegisterMASKImage(void)
%
*/
ModuleExport size_t RegisterMASKImage(void)
{
  MagickInfo
    *entry;

  entry=AcquireMagickInfo("MASK","MASK","Image Clip Mask");
  entry->decoder=(DecodeImageHandler *) ReadMASKImage;
  entry->encoder=(EncodeImageHandler *) WriteMASKImage;
  (void) RegisterMagickInfo(entry);
  return(MagickImageCoderSignature);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   U n r e g i s t e r M A S K I m a g e                                     %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  UnregisterMASKImage() removes format registrations made by the
%  MASK module from the list of supported formats.
%
%  The format of the UnregisterMASKImage method is:
%
%      UnregisterMASKImage(void)
%
*/
ModuleExport void UnregisterMASKImage(void)
{
  (void) UnregisterMagickInfo("MASK");
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   W r i t e M A S K I m a g e                                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  WriteMASKImage() writes an image mask to a file.
%
%  The format of the WriteMASKImage method is:
%
%      MagickBooleanType WriteMASKImage(const ImageInfo *image_info,
%        Image *image,ExceptionInfo *exception)
%
%  A description of each parameter follows.
%
%    o image_info: the image info.
%
%    o image:  The image.
%
%    o exception: return any errors or warnings in this structure.
%
*/

static Image *MaskImage(const Image *image,ExceptionInfo *exception)
{
  CacheView
    *image_view,
    *mask_view;

  Image
    *mask_image;

  MagickBooleanType
    status;

  ssize_t
    y;

  mask_image=CloneImage(image,image->columns,image->rows,MagickTrue,
    exception);
  if (mask_image == (Image *) NULL)
    return((Image *) NULL);
  if (SetImageStorageClass(mask_image,DirectClass,exception) == MagickFalse)
    {
      mask_image=DestroyImage(mask_image);
      return((Image *) NULL);
    }
  mask_image->alpha_trait=UndefinedPixelTrait;
  (void) SetImageColorspace(mask_image,GRAYColorspace,exception);
  /*
    Mask image.
  */
  status=MagickTrue;
  image_view=AcquireVirtualCacheView(image,exception);
  mask_view=AcquireAuthenticCacheView(mask_image,exception);
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    register const Quantum
      *magick_restrict p;

    register Quantum
      *magick_restrict q;

    register ssize_t
      x;

    if (status == MagickFalse)
      continue;
    p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
    q=QueueCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1,
      exception);
    if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
      {
        status=MagickFalse;
        continue;
      }
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      SetPixelChannel(mask_image,GrayPixelChannel,0,q);
      SetPixelChannel(mask_image,GrayPixelChannel,GetPixelWriteMask(image,p),q);
      p+=GetPixelChannels(image);
      q+=GetPixelChannels(mask_image);
    }
    if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse)
      status=MagickFalse;
  }
  mask_view=DestroyCacheView(mask_view);
  image_view=DestroyCacheView(image_view);
  if (status == MagickFalse)
    mask_image=DestroyImage(mask_image);
  return(mask_image);
}

static MagickBooleanType WriteMASKImage(const ImageInfo *image_info,
  Image *image,ExceptionInfo *exception)
{
  Image
    *mask_image;

  ImageInfo
    *write_info;

  MagickBooleanType
    status;

  mask_image=MaskImage(image,exception);
  if (mask_image == (Image *) NULL)
    return(MagickFalse);
  (void) CopyMagickString(mask_image->filename,image->filename,
    MagickPathExtent);
  write_info=CloneImageInfo(image_info);
  *write_info->magick='\0';
  (void) SetImageInfo(write_info,1,exception);
  if ((*write_info->magick == '\0') ||
      (LocaleCompare(write_info->magick,"MASK") == 0))
    (void) FormatLocaleString(mask_image->filename,MagickPathExtent,"miff:%s",
      write_info->filename);
  status=WriteImage(write_info,mask_image,exception);
  mask_image=DestroyImage(mask_image);
  write_info=DestroyImageInfo(write_info);
  return(status);
}


text:
[![Build Status](https://travis-ci.org/dylanmckay/rurust.svg?branch=master)](https://travis-ci.org/dylanmckay/rurust)
[![Crates.io](https://img.shields.io/crates/v/rurust.svg)](https://crates.io/crates/rurust)
[![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)

A Rust wrapper over the MRI Ruby VM.

[Documentation](https://crates.fyi/crates/rurust/0.1.1)

Allows you to create a Ruby VM, `eval` code, plug classes,
define modules, and insert C functions into the environment.

For a more high level library, take a look at [plugger](https://github.com/dylanmckay/plugger-ruby).

## Examples

### A simple REPL

``` rust
extern fn callable_from_ruby() {
    println!("Hello World!");
}

fn main() {
    let mut vm = rurust::VM::new().unwrap();

    vm.class("Rust").
        method("hello_world", callable_from_ruby as *const _, 0).
        method("foo", callable_from_ruby as *const _, 0).
        build();

    loop {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();

        let result = vm.eval(&line);
        println!("{:?}", result);
    }
}

```


text:
package main

import (
	"fmt"
	"os"
)

var cmdSubmitUnit = &Command{
	Name:    "submit",
	Summary: "Upload one or more units to the cluster without starting them",
	Usage:   "UNIT...",
	Description: `Upload one or more units to the cluster without starting them. Useful
for validating units before they are started.

This operation is idempotent; if a named unit already exists in the cluster, it will not be resubmitted.

Submit a single unit:
	fleetctl submit foo.service

Submit a directory of units with glob matching:
	fleetctl submit myservice/*`,
	Run: runSubmitUnits,
}

func init() {
	cmdSubmitUnit.Flags.BoolVar(&sharedFlags.Sign, "sign", false, "DEPRECATED - this option cannot be used")
}

func runSubmitUnits(args []string) (exit int) {
	if err := lazyCreateUnits(args); err != nil {
		fmt.Fprintf(os.Stderr, "Error creating units: %v\n", err)
		exit = 1
	}
	return
}


text:
<md-sidenav class="md-sidenav-left md-whiteframe-z2 layout-padding" md-is-locked-open="1">

</md-sidenav>
<md-content md-scroll-y layout-padding flex>

                Account Type

</md-content>


text:
import React, { Component, PropTypes } from 'react'
import TodoList from './TodoList'
import AddTodo from './AddTodo'
import './Favorite.scss'
import Title from '../../../components/Title'

export default class Favorite extends Component {
  // constructor(props) {
  //   super(props)
  // }

  componentDidMount() {
    this.props.getNodesTodo();
  }

  render() {
    const {addTodo, completeTodo, nodes} = this.props
    return (
      <div>
        <Title title='新番推荐'/>
        <TodoList
            onTodoClick={
                index => completeTodo(index)
            }
            nodes={nodes}
        />
      </div>
    )
  }
}
// <AddTodo
//     onAddClick={
//         text => addTodo(text)
//     }
// />

Favorite.propTypes = {
  nodes        : PropTypes.array.isRequired,
  completeTodo : PropTypes.func.isRequired,
  addTodo      : PropTypes.func.isRequired,
  getNodesTodo : PropTypes.func.isRequired
}


text:
var group__analogy__lib__level2 =
[
    [ "Asynchronous acquisition API", "group__analogy__lib__async2.html", "group__analogy__lib__async2" ],
    [ "Software calibration API", "group__analogy__lib__calibration.html", "group__analogy__lib__calibration" ],
    [ "Math API", "group__analogy__lib__math.html", "group__analogy__lib__math" ],
    [ "Range / conversion API", "group__analogy__lib__rng2.html", "group__analogy__lib__rng2" ],
    [ "Synchronous acquisition API", "group__analogy__lib__sync2.html", "group__analogy__lib__sync2" ]
];


text:
namespace pecar {

class Interact
{

};

}


text:
package util

import (
	"crypto"
	"errors"
	"io"

	"github.com/google/go-pkcs11/pkcs11"
)

// Cred returns a Key wrapping the first valid certificate in the pkcs11 module
// matching a given slot and label.
func Cred(pkcs11Module string, slotUint32Str string, label string, userPin string) (*Key, error) {
	module, err := pkcs11.Open(pkcs11Module)
	if err != nil {
		return nil, err
	}
	slotUint32, err := ParseHexString(slotUint32Str)
	if err != nil {
		return nil, err
	}
	kslot, err := module.Slot(slotUint32, pkcs11.Options{PIN: userPin})
	if err != nil {
		return nil, err
	}

	certs, err := kslot.Objects(pkcs11.Filter{Class: pkcs11.ClassCertificate, Label: label})
	if err != nil {
		return nil, err
	}
	cert, err := certs[0].Certificate()
	if err != nil {
		return nil, err
	}
	x509, err := cert.X509()
	if err != nil {
		return nil, err
	}
	var kchain [][]byte
	kchain = append(kchain, x509.Raw)

	pubKeys, err := kslot.Objects(pkcs11.Filter{Class: pkcs11.ClassPublicKey, Label: label})
	if err != nil {
		return nil, err
	}
	pubKey, err := pubKeys[0].PublicKey()
	if err != nil {
		return nil, err
	}

	privkeys, err := kslot.Objects(pkcs11.Filter{Class: pkcs11.ClassPrivateKey, Label: label})
	if err != nil {
		return nil, err
	}
	privKey, err := privkeys[0].PrivateKey(pubKey)
	if err != nil {
		return nil, err
	}
	ksigner, ok := privKey.(crypto.Signer)
	if !ok {
		return nil, errors.New("PrivateKey does not implement crypto.Signer")
	}

	return &Key{
		slot:   kslot,
		signer: ksigner,
		chain:  kchain,
	}, nil
}

// Key is a wrapper around the pkcs11 module and uses it to
// implement signing-related methods.
type Key struct {
	slot   *pkcs11.Slot
	signer crypto.Signer
	chain  [][]byte
}

// CertificateChain returns the credential as a raw X509 cert chain. This
// contains the public key.
func (k *Key) CertificateChain() [][]byte {
	return k.chain
}

// Close releases resources held by the credential.
func (k *Key) Close() {
	k.slot.Close()
}

// Public returns the corresponding public key for this Key.
func (k *Key) Public() crypto.PublicKey {
	return k.signer.Public()
}

// Sign signs a message.
func (k *Key) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
	return k.signer.Sign(nil, digest, opts)
}


text:
require 'test/unit'
require 'rubygems'
require 'shoulda'
require File.join(File.dirname(__FILE__), '..', 'rubycf')

# mocks for testing encoding
class HashEncodeableClass
  def initialize(value)
    @value = value
  end

  def to_hash
    @value
  end
end

class ArrayEncodeableClass
  def initialize(value)
    @value = value
  end

  def to_a
    @value
  end
end

class UnencodableClass
end


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=emulateIE7" />
    <title>Coverage for /Users/ramonserranolopez/SourceTree/PracticaVerificacion/venv/lib/python2.7/site-packages/requests/packages/chardet/__init__.py: 27%</title>
    <link rel="stylesheet" href="style.css" type="text/css">

Coverage for /Users/ramonserranolopez/SourceTree/PracticaVerificacion/venv/lib/python2.7/site-packages/requests/packages/chardet/__init__.py :
            27%

            11 statements
            3 run
            8 missing
            0 excluded

Hot-keys on this page

        r
        m
        x
        p   toggle line displays

        j
        k   next/prev highlighted chunk

        0   (zero) top of page

        1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

######################## BEGIN LICENSE BLOCK ########################

# This library is free software; you can redistribute it and/or

# modify it under the terms of the GNU Lesser General Public

# License as published by the Free Software Foundation; either

# version 2.1 of the License, or (at your option) any later version.

#

# This library is distributed in the hope that it will be useful,

# but WITHOUT ANY WARRANTY; without even the implied warranty of

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU

# Lesser General Public License for more details.

#

# You should have received a copy of the GNU Lesser General Public

# License along with this library; if not, write to the Free Software

# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA

# 02110-1301  USA

######################### END LICENSE BLOCK #########################

__version__ = "2.3.0"

from sys import version_info

def detect(aBuf):

    if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or

            (version_info >= (3, 0) and not isinstance(aBuf, bytes))):

        raise ValueError('Expected a bytes object, not a unicode object')

    from . import universaldetector

    u = universaldetector.UniversalDetector()

    u.reset()

    u.feed(aBuf)

    u.close()

    return u.result

            « index     coverage.py v4.0.3,
            created at 2016-06-01 05:35


text:
import json
from os.path import dirname, join, exists
from time import strftime
from datetime import datetime
import unittest
from teamcity import is_running_under_teamcity
from teamcity.unittestpy import TeamcityTestRunner

from onelogin.saml2.metadata import OneLogin_Saml2_Metadata
from onelogin.saml2.settings import OneLogin_Saml2_Settings

class OneLogin_Saml2_Metadata_Test(unittest.TestCase):
    settings_path = join(dirname(dirname(dirname(dirname(__file__)))), 'settings')

    def loadSettingsJSON(self, filename='settings1.json'):
        filename = join(self.settings_path, filename)
        if exists(filename):
            stream = open(filename, 'r')
            settings = json.load(stream)
            stream.close()
            return settings
        else:
            raise Exception('Settings json file does not exist')

    def file_contents(self, filename):
        f = open(filename, 'r')
        content = f.read()
        f.close()
        return content

    def testBuilder(self):
        """
        Tests the builder method of the OneLogin_Saml2_Metadata
        """
        settings = OneLogin_Saml2_Settings(self.loadSettingsJSON())
        sp_data = settings.get_sp_data()
        security = settings.get_security_data()
        organization = settings.get_organization()
        contacts = settings.get_contacts()

        metadata = OneLogin_Saml2_Metadata.builder(
            sp_data, security['authnRequestsSigned'],
            security['wantAssertionsSigned'], None, None, contacts,
            organization
        )

        self.assertIsNotNone(metadata)

        self.assertIn('<md:SPSSODescriptor', metadata)
        self.assertIn('entityID="http://stuff.com/endpoints/metadata.php"', metadata)
        self.assertIn('AuthnRequestsSigned="false"', metadata)
        self.assertIn('WantAssertionsSigned="false"', metadata)

        self.assertIn('<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"', metadata)
        self.assertIn('Location="http://stuff.com/endpoints/endpoints/acs.php"', metadata)
        self.assertIn('<md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"', metadata)
        self.assertIn('Location="http://stuff.com/endpoints/endpoints/sls.php"', metadata)

        self.assertIn('<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified</md:NameIDFormat>', metadata)

        self.assertIn('<md:OrganizationName xml:lang="en-US">sp_test</md:OrganizationName>', metadata)
        self.assertIn('<md:ContactPerson contactType="technical">', metadata)
        self.assertIn('<md:GivenName>technical_name</md:GivenName>', metadata)

        security['authnRequestsSigned'] = True
        security['wantAssertionsSigned'] = True
        del sp_data['singleLogoutService']['url']

        metadata2 = OneLogin_Saml2_Metadata.builder(
            sp_data, security['authnRequestsSigned'],
            security['wantAssertionsSigned']
        )

        self.assertIsNotNone(metadata2)
        self.assertIn('<md:SPSSODescriptor', metadata2)

        self.assertIn('AuthnRequestsSigned="true"', metadata2)
        self.assertIn('WantAssertionsSigned="true"', metadata2)

        self.assertNotIn('<md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"', metadata2)
        self.assertNotIn(' Location="http://stuff.com/endpoints/endpoints/sls.php"/>', metadata2)

        metadata3 = OneLogin_Saml2_Metadata.builder(
            sp_data, security['authnRequestsSigned'],
            security['wantAssertionsSigned'],
            '2014-10-01T11:04:29Z',
            'P1Y',
            contacts,
            organization
        )
        self.assertIsNotNone(metadata3)
        self.assertIn('<md:SPSSODescriptor', metadata3)
        self.assertIn('cacheDuration="P1Y"', metadata3)
        self.assertIn('validUntil="2014-10-01T11:04:29Z"', metadata3)

        # Test no validUntil, only cacheDuration:
        metadata4 = OneLogin_Saml2_Metadata.builder(
            sp_data, security['authnRequestsSigned'],
            security['wantAssertionsSigned'],
            '',
            86400 * 10,  # 10 days
            contacts,
            organization
        )
        self.assertIsNotNone(metadata4)
        self.assertIn('<md:SPSSODescriptor', metadata4)
        self.assertIn('cacheDuration="PT864000S"', metadata4)
        self.assertNotIn('validUntil', metadata4)

        # Test no cacheDuration, only validUntil:
        metadata5 = OneLogin_Saml2_Metadata.builder(
            sp_data, security['authnRequestsSigned'],
            security['wantAssertionsSigned'],
            '2014-10-01T11:04:29Z',
            '',
            contacts,
            organization
        )
        self.assertIsNotNone(metadata5)
        self.assertIn('<md:SPSSODescriptor', metadata5)
        self.assertNotIn('cacheDuration', metadata5)
        self.assertIn('validUntil="2014-10-01T11:04:29Z"', metadata5)

        datetime_value = datetime.now()
        metadata6 = OneLogin_Saml2_Metadata.builder(
            sp_data, security['authnRequestsSigned'],
            security['wantAssertionsSigned'],
            datetime_value,
            'P1Y',
            contacts,
            organization
        )
        self.assertIsNotNone(metadata5)
        self.assertIn('<md:SPSSODescriptor', metadata6)
        self.assertIn('cacheDuration="P1Y"', metadata6)
        parsed_datetime = strftime(r'%Y-%m-%dT%H:%M:%SZ', datetime_value.timetuple())
        self.assertIn('validUntil="%s"' % parsed_datetime, metadata6)

    def testBuilderAttributeConsumingService(self):
        settings = OneLogin_Saml2_Settings(self.loadSettingsJSON('settings4.json'))
        sp_data = settings.get_sp_data()
        security = settings.get_security_data()
        organization = settings.get_organization()
        contacts = settings.get_contacts()

        metadata = OneLogin_Saml2_Metadata.builder(
            sp_data, security['authnRequestsSigned'],
            security['wantAssertionsSigned'], None, None, contacts,
            organization
        )
        self.assertIn("""        <md:AttributeConsumingService index="1">
            <md:ServiceName xml:lang="en">Test Service</md:ServiceName>
            <md:ServiceDescription xml:lang="en">Test Service</md:ServiceDescription>
            <md:RequestedAttribute Name="urn:oid:2.5.4.42" FriendlyName="givenName" \>
            <md:RequestedAttribute Name="urn:oid:2.5.4.4" FriendlyName="sn" \>
            <md:RequestedAttribute Name="urn:oid:2.16.840.1.113730.3.1.241" FriendlyName="displayName" \>
            <md:RequestedAttribute Name="urn:oid:0.9.2342.19200300.100.1.3" FriendlyName="mail" \>
            <md:RequestedAttribute Name="urn:oid:0.9.2342.19200300.100.1.1" FriendlyName="uid" \>
        </md:AttributeConsumingService>""", metadata)

    def testSignMetadata(self):
        """
        Tests the signMetadata method of the OneLogin_Saml2_Metadata
        """
        settings = OneLogin_Saml2_Settings(self.loadSettingsJSON())
        sp_data = settings.get_sp_data()
        security = settings.get_security_data()

        metadata = OneLogin_Saml2_Metadata.builder(
            sp_data, security['authnRequestsSigned'],
            security['wantAssertionsSigned']
        )

        self.assertIsNotNone(metadata)

        cert_path = settings.get_cert_path()
        key = self.file_contents(join(cert_path, 'sp.key'))
        cert = self.file_contents(join(cert_path, 'sp.crt'))

        signed_metadata = OneLogin_Saml2_Metadata.sign_metadata(metadata, key, cert)

        self.assertIn('<md:SPSSODescriptor', signed_metadata)
        self.assertIn('entityID="http://stuff.com/endpoints/metadata.php"', signed_metadata)
        self.assertIn('AuthnRequestsSigned="false"', signed_metadata)
        self.assertIn('WantAssertionsSigned="false"', signed_metadata)

        self.assertIn('<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"', signed_metadata)
        self.assertIn('Location="http://stuff.com/endpoints/endpoints/acs.php"', signed_metadata)
        self.assertIn('<md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"', signed_metadata)
        self.assertIn(' Location="http://stuff.com/endpoints/endpoints/sls.php"/>', signed_metadata)

        self.assertIn('<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified</md:NameIDFormat>', signed_metadata)

        self.assertIn('<ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>', signed_metadata)
        self.assertIn('<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>', signed_metadata)
        self.assertIn('<ds:Reference', signed_metadata)
        self.assertIn('<ds:KeyInfo><ds:X509Data>\n<ds:X509Certificate>', signed_metadata)

        try:
            OneLogin_Saml2_Metadata.sign_metadata('', key, cert)
            self.assertTrue(False)
        except Exception as e:
            self.assertIn('Empty string supplied as input', e.message)

    def testAddX509KeyDescriptors(self):
        """
        Tests the addX509KeyDescriptors method of the OneLogin_Saml2_Metadata
        """
        settings = OneLogin_Saml2_Settings(self.loadSettingsJSON())
        sp_data = settings.get_sp_data()

        metadata = OneLogin_Saml2_Metadata.builder(sp_data)
        self.assertNotIn('<md:KeyDescriptor use="signing"', metadata)
        self.assertNotIn('<md:KeyDescriptor use="encryption"', metadata)

        metadata_without_descriptors = OneLogin_Saml2_Metadata.add_x509_key_descriptors(metadata, None)
        self.assertNotIn('<md:KeyDescriptor use="signing"', metadata_without_descriptors)
        self.assertNotIn('<md:KeyDescriptor use="encryption"', metadata_without_descriptors)

        metadata_without_descriptors = OneLogin_Saml2_Metadata.add_x509_key_descriptors(metadata, '')
        self.assertNotIn('<md:KeyDescriptor use="signing"', metadata_without_descriptors)
        self.assertNotIn('<md:KeyDescriptor use="encryption"', metadata_without_descriptors)

        cert_path = settings.get_cert_path()
        cert = self.file_contents(join(cert_path, 'sp.crt'))

        metadata_with_descriptors = OneLogin_Saml2_Metadata.add_x509_key_descriptors(metadata, cert)
        self.assertIn('<md:KeyDescriptor use="signing"', metadata_with_descriptors)
        self.assertIn('<md:KeyDescriptor use="encryption"', metadata_with_descriptors)

        try:
            OneLogin_Saml2_Metadata.add_x509_key_descriptors('', cert)
            self.assertTrue(False)
        except Exception as e:
            self.assertIn('Error parsing metadata', e.message)

        base_path = dirname(dirname(dirname(dirname(__file__))))
        unparsed_metadata = self.file_contents(join(base_path, 'data', 'metadata', 'unparsed_metadata.xml'))
        try:
            metadata_with_descriptors = OneLogin_Saml2_Metadata.add_x509_key_descriptors(unparsed_metadata, cert)
            self.assertFalse(True)
        except Exception as e:
            self.assertIn('Error parsing metadata', e.message)

if __name__ == '__main__':
    if is_running_under_teamcity():
        runner = TeamcityTestRunner()
    else:
        runner = unittest.TextTestRunner()
    unittest.main(testRunner=runner)


text:
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>

    <title>Usage Patterns For Client-Side URI parameters</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">

<link charset="utf-8" type="text/css" rel="stylesheet" href="http://www.w3.org/StyleSheets/TR/W3C-WG-NOTE">

Usage Patterns For Client-Side URI parameters

<acronym title="World Wide Web Consortium">W3C</acronym> Working Group Note 9 February 2012

This version:

http://www.w3.org/TR/2012/NOTE-hash-in-uri-20120209/

Latest published version:

http://www.w3.org/TR/hash-in-uri/

Previous version:

http://www.w3.org/TR/2009/WD-hash-in-uri-20090415/

Editor:

T. V. Raman, Google,  <raman@google.com>

Copyright © 2012 <acronym title="World Wide Web Consortium">W3C</acronym>® (<acronym title="Massachusetts Institute of Technology">MIT</acronym>, <acronym title="European Research Consortium for Informatics and Mathematics">ERCIM</acronym>, Keio), All Rights Reserved. <acronym title="World Wide Web Consortium">W3C</acronym> liability, trademark and document use rules apply.

Abstract

This document is a placeholder to indicate that a document which had
previously been a workding draft on the Recommendation Track is no longer
being developed on the Recommendation Track. Instead, a TAG Finding has been
published, based in part on the content of the working draft. The Finding is
not on the Recommendation Track.

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current <acronym title="World Wide Web Consortium">W3C</acronym> publications and the latest revision of this technical report can be found in the <acronym title="World Wide Web Consortium">W3C</acronym> technical reports index at http://www.w3.org/TR/.

This document was published by the TAG as a Note. If you wish to make comments regarding this document, please send them to www-tag@w3.org (subscribe, archives). All feedback is welcome.

Publication as a Working Group Note does not imply endorsement by the <acronym title="World Wide Web Consortium">W3C</acronym> Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 <acronym title="World Wide Web Consortium">W3C</acronym> Patent Policy. <acronym title="World Wide Web Consortium">W3C</acronym> maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the <acronym title="World Wide Web Consortium">W3C</acronym> Patent Policy.

1. Usage Patterns For Client-Side URI parameters

The publication of this document as a Working Group Note signals the
suspension of efforts to publish a Recommendation
based on the previous Working Draft.
Related work, evolved in part from the working
draft, has been published as a TAG Finding named "Identifying
Application State". Subsequent versions of this TAG Finding, if any,
will be published at that same URI: http://www.w3.org/2001/tag/doc/IdentifyingApplicationState.
This document will NOT be updated.