Tuesday, 4 February 2014

Median


Welcome Guys !!
Here I have posting a puzzle that I have encountered in a programming contest and I have made a successful submission :

The median of M numbers is defined as the middle number after sorting them in order if M is odd or the average number of the middle 2 numbers (again after sorting) if M is even. You have an empty number list at first. Then you can add or remove some number from the list. For each add or remove operation, output the median of numbers in the list.
Example :
For a set of m = 5 numbers, { 9, 2, 8, 4, 1 } the median is the third number in sorted set { 1, 2, 4, 8, 9 } which is 4. Similarly for set of m = 4, { 5, 2, 10, 4 }, the median is the average of second and the third element in the sorted set { 2, 4, 5, 10 } which is (4+5)/2 = 4.5  
Input:
The first line is an integer n indicates the number of operations. Each of the next n lines is either “a x” or “r x” which indicates the operation is add or remove.
Output:
For each operation: If the operation is add output the median after adding x in a single line. If the operation is remove and the number x is not in the list, output “Wrong!” in a single line. If the operation is remove and the number x is in the list, output the median after deleting x in a single line. (if the result is an integer DO NOT output decimal point. And if the result is a real number , DO NOT output trailing 0s.)
Note
When calculating median in even case if your output is 3.0 print only 3 and if it is 3.50 print only 3.5
Constraints:
0 < n <= 100,000
For each “a x” or “r x”, x will always be an integer which will fit in 32 bit signed integer.
Sample Input:
7  
r 1  
a 1  
a 2  
a 1  
r 1  
r 2  
r 1  
Sample Output:
Wrong!  
1  
1.5  
1  
1.5  
1  
Wrong!
Note: As evident from the last line of the input, if after remove operation the list becomes empty you have to print “Wrong!” ( quotes are for clarity ). 

SOLUTION :

#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
int x[1000000];
char operation[1000000];
int number[1000000],T;
int total_size=0;
int median;
bool isFound=true;
double median_list[1000000];
int median_counter=0;
int search_location(int num){
int loc;
int start=0;
int mid;
int end=total_size-1;
while(start<=end){
mid=(start+end)/2;
if(x[mid]==num)
return mid;
else  if(x[mid]>num){
end=mid-1;
}else{
start=mid+1;
}

}
return -1;
}

void remove_from(int num){
if(total_size==0){
}
else{
int loc=search_location(num);
//cout<<"Element found at location :"<<loc;
if(loc!=-1){
for(int i=loc;i<total_size-1;i++){
x[i]=x[i+1];
}
total_size-=1;
}else{
isFound=false;
}

}
}
void insert_into(int num) {

int i=total_size-1;
while(num<x[i] && i>=0){
x[i+1]=x[i];
i--;
}
x[i+1]=num;
    total_size+=1;
}
void find_median(){
double median;
if(total_size==0){
median=99999999999;
}
else if(isFound==false){
median=99999999999;
isFound=true;
}
else if(total_size%2==0){
median=((double)x[total_size/2]+(double)x[(total_size/2)-1])/2;
//cout<<"The median is : "<<median;
}else{
median=(double)x[total_size/2];
///cout<<"The median is : "<<median;
}
median_list[median_counter]=median;
median_counter+=1;
}
int main(void){
cin>>T;
for(int i=0;i<T;i++){
cin>>operation[i]>>number[i];
}
for(int i=0;i<T;i++){

if(operation[i]=='a'){
insert_into(number[i]);
find_median();
}else if(operation[i]=='r'){
remove_from(number[i]);
find_median();
}
}

    for(int i=0;i<median_counter;i++){
    if(median_list[i]==99999999999){
    cout<<"Wrong!"<<"\n";
    }else{
    if(median_list[i]-(long long)median_list[i]!=0){
    printf("%0.1lf\n",median_list[i]);
    }else{
    printf("%lld\n",(long long)median_list[i]);
    }
    }
   
    }
   return 0;
}

Saturday, 4 January 2014

Android : Facebook like Drawer Slider layout using ActionBarSherlock Supportive Library


Welcome Guys !!!

Most of the application users of android are fascinated with the layout the application uses. The more attractive and ease-to-use layout the application will have, it will affect the downloads on Play Store in same fashion.
Today i am going to write an article about a most popular kind of layout Android Developers are using.
This layout is recently used my many big applications like Facebook , Google Play Store.
I am going to build a simple application that will have a basic demonstration of the layout.

Before starting you will need a external support library for ActionBar. This will enable to use actionbar for lower version of android.
the support library can be downloaded form GitHub or I have uploaded it on mediafire .. i am going to give you the link for it :
                                            Download ActionBarSherlock
Download it and unzip it on desktop :
Now you need to import this library into your workspace :

for importing : 
Click File -> Import -> Expand General -> Select existing android project into workspace -> Browse for the unzipped file -> (Note) Cheak the copy to workspace cheakbox -> Click ok -> clean the Project

Create a new project and include this as a supporting library. To add this as a supporting library try following steps:
Project -> Right click -> properties -> Android -> add -> Select actionbarsherlock -> OK



The basic look up of the application layout  that we are going to develop is  :


Now it is all set .... let work with some development logic.

The classes would be listed here with proper comment. If the source code  of the application is need ... it will be provided by email .... 

Mail Me at : ajayjaiswalhi@gmail.com

MainActivity.java

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;


import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.v4.view.GravityCompat;
public class MainActivity extends SherlockFragmentActivity {
// Declare Variable
    DrawerLayout mDrawerLayout;
    ListView mDrawerList;
    ActionBarDrawerToggle mDrawerToggle;
    MenuListAdapter mMenuAdapter;
    String[] title;
    String[] subtitle;
    int[] icon;
    Fragment fragment1 = new Fragment1();
    Fragment fragment2 = new Fragment2();
    Fragment fragment3 = new Fragment3();
    Fragment fragment4 = new Fragment4();
    Fragment fragment5 = new Fragment5();
    AlertDialog alertDialog=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drawer_main);

        // Generate title
        title = new String[] { "Preface", "About Us",
                "Comtemporary Quiz", "About Author", "Reading Material","Key Notes" };

        // Generate subtitle
        subtitle = new String[] { "What this book is about ??", "Who we are ??",
                "Cheak what we learned ??","Behind the book ??","Learn and smile !!" ,"Zip something new !!",};

        // Generate icon
        icon = new int[] { R.drawable.action_about, R.drawable.action_settings,
                R.drawable.collections_cloud, R.drawable.about_author, R.drawable.book, R.drawable.key_notes };

        // Locate DrawerLayout in drawer_main.xml
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        // Locate ListView in drawer_main.xml
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // Set a custom shadow that overlays the main content when the drawer
        // opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
                GravityCompat.START);

        // Pass results to MenuListAdapter Class
        mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);

        // Set the MenuListAdapter to the ListView
        mDrawerList.setAdapter(mMenuAdapter);

        // Capture button clicks on side menu
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // Enable ActionBar app icon to behave as action to toggle nav drawer
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#662523")));
        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open,
                R.string.drawer_close) {

            public void onDrawerClosed(View view) {
                // TODO Auto-generated method stub
                super.onDrawerClosed(view);
            }

            public void onDrawerOpened(View drawerView) {
                // TODO Auto-generated method stub
                super.onDrawerOpened(drawerView);
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.main, menu);
       return true;
   
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {

            if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                mDrawerLayout.openDrawer(mDrawerList);
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
this.finish();
}

@Override
public void onBackPressed() {
// TODO Auto-generated method stub

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

// set title
alertDialogBuilder.setTitle("Exit Application");

alertDialogBuilder
.setMessage(" Do you want to exit ?? ")
.setCancelable(true)
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
MainActivity.this.finish();


}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
// create alert dialog
alertDialog = alertDialogBuilder.create();
alertDialog.show();
// set dialog message


}

// The click listener for ListView in the navigation drawer
    private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // Locate Position
        switch (position) {
        case 0:
            ft.replace(R.id.content_frame, fragment4);
            break;
        case 1:
            ft.replace(R.id.content_frame, fragment2);
            break;
        case 2:
            ft.replace(R.id.content_frame, fragment3);
            break;
        case 3:
            ft.replace(R.id.content_frame, fragment1);
            break;
        case 4:
            ft.replace(R.id.content_frame, fragment5);
            break;
        case 5:
            ft.replace(R.id.content_frame, fragment5);
            break;
        }
        ft.commit();
        mDrawerList.setItemChecked(position, true);
        // Close drawer
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}


===========================================================

Create 5 fragment java classes corresponding to every fragment that will be loaded

Fargment1.java

import com.actionbarsherlock.app.SherlockFragment;
import android.os.Bundle;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
public class Fragment1 extends SherlockFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment1, container, false);
        String htmlAsAString="<html>" +
        "<body>" +
                       "Hello World !!"
        "</body>"+
        "</html>";
        TextView description=(TextView) rootView.findViewById(R.id.authordescription);
        description.setText(Html.fromHtml(htmlAsAString));
        TextView author=(TextView) rootView.findViewById(R.id.welcomeauthor);
        author.setText(Html.fromHtml("<b><u>About the Author</u></b>"));
        description.setMovementMethod(new ScrollingMovementMethod());
        return rootView;
    }
 
}



=======================================================
Create an xml for the MainActivity.java :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

   

</RelativeLayout>



=======================================================

Create XML Layouts corresponding to each and every fragment 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:background="#A33421"
   >
    
    <!-- GUI Code goes here -->

</RelativeLayout>

=========================================================

Create a layout that will hold the list for the sidemenu drawer (drawer_main.xml)

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#802220"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />

</android.support.v4.widget.DrawerLayout>


===============================================================

Create a layout to flat each and every item of the darwer that is going to be slided over (drawer_list_item.xml) :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="?attr/spinnerDropDownItemStyle"
    android:layout_width="match_parent"
    android:layout_height="?attr/dropdownListPreferredItemHeight"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:adjustViewBounds="true" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center_vertical|left"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/title"
            style="?attr/spinnerDropDownItemStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true" />

        <TextView
            android:id="@+id/subtitle"
            style="?attr/spinnerDropDownItemStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:textAppearance="?attr/textAppearanceSmall" />
    </LinearLayout>

</LinearLayout>

================================================================

Create a MenuListAdapter.java class to inflat the drawer with the layouts created above. This adapter will populate the items in the sidemenu drawers :

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MenuListAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    String[] mTitle;
    String[] mSubTitle;
    int[] mIcon;
    LayoutInflater inflater;

    public MenuListAdapter(Context context, String[] title, String[] subtitle,
            int[] icon) {
        this.context = context;
        this.mTitle = title;
        this.mSubTitle = subtitle;
        this.mIcon = icon;
    }

    @Override
    public int getCount() {
        return mTitle.length;
    }

    @Override
    public Object getItem(int position) {
        return mTitle[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView txtTitle;
        TextView txtSubTitle;
        ImageView imgIcon;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(R.layout.drawer_list_item, parent,
                false);

        // Locate the TextViews in drawer_list_item.xml
        txtTitle = (TextView) itemView.findViewById(R.id.title);
        txtSubTitle = (TextView) itemView.findViewById(R.id.subtitle);

        // Locate the ImageView in drawer_list_item.xml
        imgIcon = (ImageView) itemView.findViewById(R.id.icon);

        // Set the results into TextViews
        txtTitle.setText(mTitle[position]);
        txtSubTitle.setText(mSubTitle[position]);

        // Set the results into ImageView
        imgIcon.setImageResource(mIcon[position]);

        return itemView;
    }

}


===================================================

All set... all Go ... !! 
Compile and run the application .

In case you have any problem write me a mail at : ajayjaiswalhi@gmail.com
or you can post your problem at the facebook page : https://www.facebook.com/codegeekstuffs


Thank you !!




PHP – MySQL Connectivity


Welocome Guys !!

It is Saturday , after a long week of hard work , we are having weekend. I am also going to have fun.
Anyway before that i am going to write an article about the the problem which the any new PHP developer often face when he go for a database application.

Any PHP developer often  come across situation to connect to a database to make its  application more interactive.

diagrama-backup-mysql-php

PHP – MySQL Connectivity

Interacting with MySQL makes PHP a far more powerful tool. In this tutorial we will go through some of the most common ways PHP interacts with MySQL. To follow along with what we are doing, you will need to create a database table by executing this command:


 CREATE TABLE friends (name VARCHAR(30), fav_color VARCHAR(30), fav_food VARCHAR(30), pet VARCHAR(30)); 
 INSERT INTO friends VALUES ( "Rose", "Pink", "Tacos", "Cat" ), ( "Bradley", "Blue", "Potatoes", "Frog" ), ( "Marie", "Black", "Popcorn", "Dog" ), ( "Ann", "Orange", "Soup", "Cat" ) 
This will create a table for us to work with, that has friends’ names, favorite colors, favorite foods, and pets.
The first thing we need to do in our PHP file is connect to the database. We do that using this code:

 <?php 
 // Connects to your Database 
 mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); 
 mysql_select_db("Database_Name") or die(mysql_error()); 
 ?> 
Of course you will replace server, username, password, and Database_Name with the information relevant to your site. If you are unsure what these values are, contact your hosting provider.

Enjoy Coding !!
Have a nice week end !! :) :)
Email-me at : ajayjaiswalhi@gmail.com

Thursday, 2 January 2014

Android : Application to convert the read text to speech using the featured ANDROID TextToSpeech class.(API > 1.6)


Welcome Friends !!

I am Ajay Jaiswal . I am going to talk something that always amuses us ... letting the mobile devices to speak and talk to us . While sending any sms or email we want something that is very flexible and we don't have to type for a long message and then send them.
We want something that can interpret what we are saying and convert them into the regular text that we could have typed. We want a application that can convert our speech into text and in return convert a text into speech and talk with us.

Here i am going to write such article that enable us to do so. Android provide us a lot big way to what we want and build awesome cool applications.
Android provide us a whole bunch of library and classes for this text to speech and sppech to text conversion.
It provide us  the class :

                                     public class TextToSpeech extends object

The whole more detail about the class and its various method and constants can be found on the Android Developer Dashboard.

A TextToSpeech instance can only be used to synthesize text once it has completed its initialization. Implement the TextToSpeech.OnInitListener to be notified of the completion of the initialization.
When you are done using the TextToSpeech instance, call the shutdown() method to release the native resources used by the TextToSpeech engine.

I am going to build up a simple application illustrating the use of this feature. The idea could be used for developing many cool and awesome applications.
The source code need or the demo .apk if asked for will be provided through email.

For any queries or source code you can email me at : ajayjaiswalhi@gmail.com

For running this application we need to have TextToSpeech support for our android device. The application could be tested on the usual android emulator. 
If TextToSpeech support is not provided in your device you will have a log message that Locale / Language not supported.
You need to update your device by installing TTS service form Google Play Store.


1. Create a new project by going to File ⇒ New Android Project. and fill required details.
2. Implement your main Activity class from TextToSpeech.OnInitListener

public class AndroidTextToSpeechActivity extends Activity implements TextToSpeech.OnInitListener {

==>> You  need to import following classes 

import java.util.Locale;
 
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


The whole source code for the application is :

public class AndroidTextToSpeechActivity extends Activity implements
        TextToSpeech.OnInitListener {
    /** Called when the activity is first created. */
 
    private TextToSpeech tts;
    private Button btnSpeak;
    private EditText txtText;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        tts = new TextToSpeech(this, this);
 
        btnSpeak = (Button) findViewById(R.id.btnSpeak);
 
        txtText = (EditText) findViewById(R.id.txtText);
 
        // button on click event
        btnSpeak.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                speakOut();
            }
 
        });
    }
 
    @Override
    public void onDestroy() {
        // Don't forget to shutdown tts!
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }
 
    @Override
    public void onInit(int status) {
 
        if (status == TextToSpeech.SUCCESS) {
 
            int result = tts.setLanguage(Locale.US);
 
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "This Language is not supported");
            } else {
                btnSpeak.setEnabled(true);
                speakOut();
            }
 
        } else {
            Log.e("TTS", "Initilization Failed!");
        }
 
    }
 
    private void speakOut() {
 
        String text = txtText.getText().toString();
 
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
}


4. Now run your project and test your app by entering some text in input filed.

Changing Language
You can change language to speak by using setLanguage() function. Lot of languages are supported like Canada, French, Chinese, Germany etc.

tts.setLanguage(Locale.CHINESE); // Chinese language