Pages

Thursday, October 4, 2012

[OSX] Show full path in Finder window

Enter the command
defaults write com.apple.finder _FXShowPosixPathInTitle -bool YES

Enter this to activate the effect
killall Finder

Wednesday, August 22, 2012

[Ubuntu] RDP clients in Ubuntu

The most recommended is remmina, which could be installed by
sudo apt-get install remmina
but when I used it, the color turn blue, which should be a bug.

another choice: PAC
sudo add-apt-repository "deb http://archive.getdeb.net/ubuntu oneiric-getdeb apps"
wget -q -O- http://archive.getdeb.net/getdeb-archive.key | sudo apt-key add -
sudo aptitude install pac

see the reference below to know better about how to install it.


reference:
http://linuxaria.com/recensioni/4-linux-programs-to-open-a-remote-desktop-on-windows?lang=en

Tuesday, August 21, 2012

[Ubuntu] Install oracle-java in Ubuntu

Install the oracle-java by apt-get


#for 12.04 + java7
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

Switch the java to oracle-java

sudo update-java-alternatives -s java-7-oracle

Thursday, June 7, 2012

[OSX] Convert BIG5 file to UTF8

I have been trying to transform my works from Windows to OSX.  However, in a addition to a powerful text editor (like Notepad++ on Windows), the most difficult things to me is how to open the files encoding in BIG5 which is what Windows uses for encoding traditional Chinese.

The simplest way to convert the Big5 files to utf8 might be using an embedded converter.

Open Terminal and type this
iconv -f big5 -t utf8 [your_input_file] > [your_output_file]


EDIT: I have found some useful text editors to do conversion.

In general:
1. Enable Big5 encoding character set in preference.
2. Open the Big5 files using the interface.
3. Save the file as UTF8.

TextWrangler
1. Enable Big5
2. File->Open..., read as Big5
3. File->Save as..., Encoding UTF8

A simpler way:
1. Enable Big5
2. Drag and drop
3. File->Reopen Using Encoding..., Big5
    (Or, click on the toolbar below text editing area)
4. Save


Fraiser(Smultron)
Similar to TextWrangler, open the file using Big5, then
Text->Reload Text Using Encoding..., UTF8,
and save.

Thursday, May 17, 2012

[Eclipse] Change Android application name in Eclipse

I had tried to change the application name by modified the Manefist.xml directly. But it led me a lot off error.

To fix this, I recommend you do it with the interface:

1. Right click on your project
2. Down to "Android Tools"
3. Click on "Rename Application Package"


And this is called "refactoring", that is, automatically adjust all the reference that related to your modification.

[Eclipse] Project has no project.properties file! Edit the project properties to set one.

When you import a project into Eclipse and get a error message like this:

Project has no project.properties file! Edit the project properties to set one.

To solve it, just restart the Eclipse IDE.

Thursday, April 12, 2012

[Andriod] Custom dialog with gridview

Task: To improve the user-experience, I 'd like to make a dialog contains options with icons and text, and manage them in grid rather than column of options.


key components: AlertDialog, LayoutInflater, GridView, Adapter


General Conception

step  1: Put custom view in the dialog - Dialog, LayoutInflater.
step  2: Manage your grid of options - GridView, Adapter.

Technical Conception

step  1: Use LayoutInflater to load the custom layout, which contains your GridView.
step  2: Use your own Adapter to manage your GridView.
step  3: Define the behavior when users choose one of the options.
step  4: Use AlertDialog.Builder to set the view to the dialog as custom layout.


Practical steps 

 File used in this tutorial:

1. customdialog.xml: That is what will be shown in your dialog, add a GridView here.
2. customcontent.xml: The format of every option in your grid, put an ImageView with any icon and a TextView under it.
note:  You can choose another arrangement you want, I put the text under a icon here
3. customIconGridActivity.java: Your main activity.
4. main.xml: put a button to launch the function
5. Icons your wish to show on your options, store them under res/drawable
    In this tutorial, I put three picture:cat.png, yao.png, and spider.png under res/drawable-mdpi

As a tutorial, I add all the object with Eclipse GUI and keep the default id such as imageView1, textView1, etc.
   


Code

customIconGridActivity.java
-------------------------------------

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/*
 *
step  1: Use LayoutInflater to load the custom layout, which contains your GridView.
step  2: Use your own Adapter to manage your GridView.
step  3: Define the behavior when users choose one of the options.
step  4: Use AlertDialog.Builder  to set the view to the dialog as custom layout.
 */
public class CustomIconGridActivity extends Activity {
    Context m_context = this;
    Dialog  m_dialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        Button myButton = (Button) findViewById(R.id.button1);
        myButton.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {
                // TODO Auto-generated method stub
                showDialog(0);
            }
      
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        //step 1:Load custom dialog layout
        LayoutInflater myInflater = LayoutInflater.from(m_context);
        View myView = myInflater.inflate(R.layout.customdialog, null);
      
      
        GridView gv = (GridView) myView.findViewById(R.id.gridView1);
        //step 2: Set self-defined ImageAdaper to our gridview
        gv.setAdapter(new ImageAdapter(m_context));
              
        //step 3: Set up the behavior when user touches an item in the grid
        gv.setOnItemClickListener(new GridView.OnItemClickListener(){

            public void onItemClick(AdapterView<?> parent, View v,int position, long id)
            {
              
                // TODO Auto-generated method stub
                Toast.makeText(v.getContext(), "Position is "+position, Toast.LENGTH_SHORT).show();
                //remove this statement if you want keep the dialog after user touched
                m_dialog.dismiss();
            }
          
        });
      
        //step 4: Set the custom view to the AlertDialog      
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("choose a context");
        builder.setView(myView);
      
        m_dialog = builder.create();
      
        return m_dialog;
    }
  
 
  
    public class ImageAdapter extends BaseAdapter {   
        private Context mContext;
        private LayoutInflater mInflater;
        public ImageAdapter(Context c) { 
            mInflater = LayoutInflater.from(c);
            mContext = c;   
        }   
        public int getCount() {   
            return mThumbIds.length;   
        }   
        public Object getItem(int position) {   
            return null;   
        }   
        public long getItemId(int position) {   
            return 0;   
        }   
        // create a new ImageView for each item referenced by the index

        public View getView(int position, View convertView, ViewGroup parent) {
            //ViewHolder is a self-defined class, and every instance is consisted of an icon and a text
            ViewHolder holder;
            if (convertView == null) {  // if it's not recycled,   

                convertView = mInflater.inflate(R.layout.customcontent, null);
                //convertView.setLayoutParams(new GridView.LayoutParams(90, 90));
                holder = new ViewHolder();
              
                //set any text and pic on the views, they will be replaced later
                holder.title = (TextView) convertView.findViewById(R.id.textView1);
                holder.icon = (ImageView )convertView.findViewById(R.id.imageView1);
              
                convertView.setTag(holder);
              
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.icon.setAdjustViewBounds(true);
            //holder.icon.setScaleType(ImageView.ScaleType.CENTER_CROP);   
            holder.icon.setPadding(8, 8, 8, 8);
            holder.title.setText(categoryContent[position]);
            holder.icon.setImageResource(mThumbIds[position]);
            return convertView;   
        }   
        class ViewHolder {
            TextView title;
            ImageView icon;
        }
        // references to our images   
        private Integer[] mThumbIds = {   
                R.drawable.spider, R.drawable.yao,R.drawable.cat, 
                R.drawable.spider, R.drawable.yao,R.drawable.cat,
                R.drawable.yao
        };


        private String[] categoryContent = {   
                "spider0", "yao1", "cat2",
                "spider3", "yao4", "cat5",
                "yao6"

        };

    }
  
}



reference: http://iserveandroid.blogspot.com/2010/12/custom-gridview-in-dialog.html

Monday, April 9, 2012

[Android] List file with filter

I have posted another article on Java, but it fails with I apply it on Android, so I use this in my Android apps.




import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileHelper

{

    public static List<File> fetchFileList(String directoryName, final String fileExtension)

    {


        List<File> fileList = new ArrayList<File>();

        File fileDirectory = new File(directoryName);

       
       
        getDirectoryContent(fileList, fileDirectory, fileExtension);

        return fileList;

    }


    private static void getDirectoryContent(List<File> fileList, File fileDirectory, String fileExtension)

    {

        if (fileDirectory.exists())
        {

            try
            {
                for (File file : fileDirectory.listFiles())

                {

                    //Log.i("FileHelper processing file:", file.getAbsolutePath());

                    if (file.isDirectory())

                        getDirectoryContent(fileList, file, fileExtension);

                    else

                    {

                        String fileName = file.getName();

                        if (fileName.endsWith(fileExtension.toLowerCase()) || fileName.endsWith(fileExtension.toUpperCase()))

                            fileList.add(file);

                    }

                }
            }
            catch(Exception e)
            {
                System.out.println("error at: " + fileDirectory);
            }
           
        }
    }

}

[Note] Online material about CS

I have not found a better way to sync bookmarks on all machines, so I just write down the links here as a note.


http://tomkuo139.blogspot.com/
http://blog.roodo.com/rocksaying
http://www.componentowl.com/blog/2012/02/zen-coder-vs-distraction-junkie/

(OO)
http://milikao.pixnet.net/blog/post/543592
(Design pattern)
http://caterpillar.onlyfun.net/Gossip/DesignPattern/DesignPattern.htm

Android

http://blog.csdn.net/hellogv/article/details/5994952#comments

(AlarmService)
http://android-er.blogspot.com/2010/10/simple-example-of-alarm-service-using.html

(grid view w/ text)
http://tomkuo139.blogspot.com/2010/01/android-gridview-text.html
(Android grid view w/ icons)
http://iserveandroid.blogspot.com/2010/12/custom-gridview-in-dialog.html
(Android ListView w/ icons)
http://blog.joomla.org.tw/android/178-ListView%E4%B9%8B%E4%B8%80%EF%BC%9AAdapter%E4%BB%8B%E7%B4%B9%E8%88%87%E4%BD%BF%E7%94%A8.html

http://blog.sina.com.cn/s/blog_5da93c8f0100wwrd.html

http://blog.csdn.net/hellogv/article/details/4567095

Python 

(sqlite3)
http://www.dreamincode.net/forums/topic/210154-sqlite3-in-python/

Saturday, April 7, 2012

[Python] Load json into dict and vice versa

##Load json to dict
f = open('myFile.json','r').read()
#objs is stored in dict form data
obj = json.loads(f)


##Save dict to a json file
testDic = {'a':123,'b':2}
#print type(testDic)
f = open('test2.json', 'w')
json.dump(testDic, f, indent=4)

[Python] Install matplotlib on OSX via MacPort

OS: OSX 10.07(Lion)
Python version: 2.7.1

Install numpy:
1. run the SuperPack Installer
Or
2.
sudo port install py27-numpy
(I recommend install py27-scipy too)


Install iPython:
sudo port install py27-ipython

Install matplotlib:
sudo port install py27-matplotlib

MacPort put the programs under /opt/local/bin or /opt/local/sbin for default
Make sure the path is included in your PATH:
vi ~/.bash_profile

Add this if not found
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
and I also add this:
alias ipython=ipython-2.7


****NOTE***
Because MacPort install everything under /opt/local/, where is not the system's default directory.
then if you type python, it would fire the system python under /usr/bin/, not the MacPort version
thus, you can't import matplotlib

Please add these to set MacPort python as default
sudo port select --set python python27

or an naive way:
add this in ~/.bach_profile
alias python=/opt/local/bin/python27

One more thing, if you use Pydev in Eclipse, do not forget to change the python interpreter
Preference->PyDev->InterpreterPython-> 
add a new interpreter, find it under /opt/bin/, and put it at the top as highest first choice. 

%%sample code
from pylab import *
a = [[1,2],[100,400]]
plot(a)
savefig('test.png')

reference: http://astrofrog.github.com/macports-python/

Tuesday, March 27, 2012

[Android] Create a dialog with list and EditText

You may have been able to create a dialog with list using AlertDialog,

you may also find some articles to make a dialog with a EditText.

But how if we can combine them?

I mean, isn't it better that we can create the dialog with several choices and  an "Other" choice to let the user enter their own answer in some cases?


In fact, the workaround is more simpler than I was thought, I just implement the onCreateDialog method to create a AlertDialog with several choices, and create another AlertDialog with another View contains an EditText if the user choose the "Other".

Here is my example:
I want to record the users' activity with time.
------------------------------------------------------------
public class WriteTagActivity extends Activity {
    private final String sOutFile = "XXX.txt";
    private final Context m_context = this;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //do some pre-process here
}

      
        Button tagButton = (Button) findViewById(R.id.tagButton);
        tagButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               
                showDialog(0);
            }

        });
       
    }
   
    private void writeTag(String tag)
    {
        long curTime = System.currentTimeMillis() / 1000;

       
        String sCurTime = Long.toString(curTime);
        try {
            FileWriter fout = new FileWriter(sOutFile,true);
            fout.write(sCurTime + "," + tag + "\n");
            fout.close();
           
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        final CharSequence[] tagList = {"party","dinner","exercising","studying","others(unrecommend)"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
       
        builder.setTitle("What are you doing now?");

       
        builder.setItems(tagList, new DialogInterface.OnClickListener() {
           
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                String tag = tagList[which].toString();
                String otherTags = tagList[tagList.length -1].toString();
                if(tag.compareTo(otherTags) == 0 )//custom tags
                {                       
                    createNewView();
                }
                else
                {
                    writeTag(tag);
                    Toast.makeText(m_context, "add " + tag + " to log...", Toast.LENGTH_SHORT).show();
                }
                   
            }
        });
       
       
        return builder.create();
    }
   

    private void createNewView()
    {
       
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
       
        builder.setTitle("What are you doing?");
   
        LayoutInflater inflater = LayoutInflater.from(m_context);
        final View otherTagView = inflater.inflate(R.layout.other_tag, null);
       
        final EditText tagEditText = (EditText) otherTagView.findViewById(R.id.tagEditText);

       
       
        builder.setPositiveButton("OK",new DialogInterface.OnClickListener(){

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
       
                        String tag = tagEditText.getText().toString();
                        writeTag(tag);
                        Toast.makeText(m_context, "add " + tag + " to log...", Toast.LENGTH_SHORT).show();

            }
           
        }
        );
       
        builder.setView(otherTagView);
        builder.create();
        builder.show();
       
    }   
   
}

I just put a button in main.xml, and an EditText in other.tag.xml, if you really want them
other.tag.xml
---------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >




    <EditText
        android:id="@+id/tagEditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
---------------


main.xml
-----------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/tagButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Tag" />

</LinearLayout>
---------------------------


I won't talk about the detail for this stage due to my laziness...

[Android] Launch a service daily using AlarmManager

If you have heard crond in Linux kernel, AlarmManager is the counterpart in Android.



hint:  Activity can be regard as a foreground process.
         Service can be regard as a background process.

Task: Check something at everyday midnight automatically (User do not need to operate)

So, we need:
1. A Service that perform the task (in background). - CronService.java
2. An Activity that launch Service periodically. - CronTestActivity.java
3. Register the Service in Manifest.xml

Step 1. Create the Service you want:

public class CronService extends Service{
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
       Toast.makeText(this, "Service start... ", Toast.LENGTH_SHORT).show();
    }
}

Step 2. Create the main activity and set up and schedule

public class CronTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Calendar cal= Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE,30);
        cal.set(Calendar.SECOND, 00);
     
       //Start the Service since today night, 11:30 p.m      

        Intent intent=  new Intent(this, CronService.class);
        PendingIntent pIntent = PendingIntent.getService(this,0, intent, 0);
       
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 24*60*60*1000, pIntent);

      //launch it every 24 hours
    }
}

step 3. Don't forget to register the Service in Manifest

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".CronTestActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <service android:name=".CronService"></service>
    </application>



By doing so, your process will be launched automatically every night since the user launch the app.
reference:
http://stackoverflow.com/questions/9004635/android-how-should-i-run-a-service-daily-and-12pm-using-alarmmanager

Monday, March 26, 2012

[Android] HTC desire S root

Desire 跟 Desire S不一樣,所以去找Desire的root法的下場就是浪費時間
首先要先security off,簡稱S-off

轉貼S-off教學

轉貼root中文教學

remove native apps on AVD
http://changyy.pixnet.net/blog/post/28872517

step 1: Install Superuser.apk.
step 2: Use Terminator to launch CLI on AVD.
step 3: Type su to get privilege.
step 4:  type mount -oremount,rw /dev/block/mtdblock0 /system, then do things you want.

Wednesday, March 21, 2012

[Android] How I launch other probes in Funf tutorial (wifiScanner)

<NOTICE>  I mean ADD, so check the format in your exist codes.

general speaking:
step 1. In MainActivity.java: launch probes in your service pool

 runOnceIntent.putExtra(MainPipeline.RUN_ONCE_PROBE_NAME, <your probe>.class.getName());
 startService(runOnceIntent); 

step 2. In Assets/default.json: set configuration of your probe
            "edu.mit.media.funf.probe.<your probe>": [
                {  }
            ],

step 3. In Manifest : set up your services:

 <service android:name="edu.mit.media.funf.probe.<your probe>"></service>

step 4. In Manifest : add the permission your probes need

    <uses-permission android:name="android.permission.<permission your probe need>" />

-----------------------------
Example:  add  BatteryProbe

1. In MainActivity.java
        Button scanNowButton = (Button)findViewById(R.id.scanNowButton);
        scanNowButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent runOnceIntent = new Intent(context, MainPipeline.class);
                runOnceIntent.setAction(MainPipeline.ACTION_RUN_ONCE);
               
                runOnceIntent.putExtra(MainPipeline.RUN_ONCE_PROBE_NAME, WifiProbe.class.getName());
                startService(runOnceIntent);
                runOnceIntent.putExtra(MainPipeline.RUN_ONCE_PROBE_NAME, LocationProbe.class.getName());
                startService(runOnceIntent);
               
               
                runOnceIntent.putExtra(MainPipeline.RUN_ONCE_PROBE_NAME, BatteryProbe.class.getName());
                startService(runOnceIntent);
            }
        });
    }


step 2. In Assets/default.json
{       "name": "WifiScanner",
        "version":1,
        "dataArchivePeriod":3600,
        "dataRequests":{
            "edu.mit.media.funf.probe.builtin.LocationProbe": [
                { "PERIOD": 900, "DURATION": 30 }
            ],
            "edu.mit.media.funf.probe.builtin.WifiProbe": [
                { "PERIOD": 900 }
            ],
            "edu.mit.media.funf.probe.builtin.BatteryProbe": [
                { }
            ]


        }
}

step3. In Manifest : set up your services

        <service android:name="edu.mit.media.funf.probe.builtin.LocationProbe"></service>
        <service android:name="edu.mit.media.funf.probe.builtin.WifiProbe"></service>
        <service android:name="edu.mit.media.funf.probe.builtin.BatteryProbe"></service>

step4. In Manifest : add the permission your probes need
    <uses-permission android:name="android.permission.BATTERY_STATS" />
    <!-- All probes -->
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
   
    <!-- Location probe -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  
   
    <!-- Wifi probe -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>



----------------

hint: Why I add that permission? check here: Funf wiki

Tuesday, March 20, 2012

[Android] Intent setAction

I am an absolutely newer to Android, and suffered while I developing a project using MIT Funf framework.

these several codes make me scratch my head.
----------------
final Context context = this;
Intent archiveIntent = new Intent(context, MainPipeline.class);
               
 archiveIntent.setAction(MainPipeline.ACTION_ARCHIVE_DATA);
 startService(archiveIntent);
----------------         

The most easy and precise explanation I have saw is:
http://milkmidi.blogspot.com/2012/02/android-intent.html (in Mandarin)

Monday, March 19, 2012

[Android] Resursively compress files in Android

References:
http://stackoverflow.com/questions/5414925/how-to-zip-folder-recursively-in-android
http://ucla.jamesyxu.com/?p=112

and I prefer this:
http://www.mkyong.com/java/how-to-compress-files-in-zip-format/


and I modified it a bit here:
-----------------------------------------------------------------
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class AppZip
{
   List<String> fileList;

   String SOURCE_FOLDER;
   String OUTPUT_ZIP_FILE;

   AppZip(String SOURCE_FOLDER, String OUTPUT_ZIP_FILE){
       this.SOURCE_FOLDER = SOURCE_FOLDER;
       this.OUTPUT_ZIP_FILE = OUTPUT_ZIP_FILE;
       fileList = new ArrayList<String>();
       generateFileList(new File(SOURCE_FOLDER));
   }

 

   /**
    * Zip it
    * @param zipFile output ZIP file location
    */
   public void zipIt(){

    String zipFile = this.OUTPUT_ZIP_FILE;
    byte[] buffer = new byte[1024];

    try{

       FileOutputStream fos = new FileOutputStream(zipFile);
       ZipOutputStream zos = new ZipOutputStream(fos);

       System.out.println("Output to Zip : " + zipFile);

       for(String file : this.fileList){

           System.out.println("File Added : " + file);
           ZipEntry ze= new ZipEntry(file);
           zos.putNextEntry(ze);

           FileInputStream in =
                      new FileInputStream(SOURCE_FOLDER + File.separator + file);

           int len;
           while ((len = in.read(buffer)) > 0) {
               zos.write(buffer, 0, len);
           }

           in.close();
       }

       zos.closeEntry();
       //remember close it
       zos.close();

       System.out.println("Done");
   }catch(IOException ex){
      ex.printStackTrace();  
   }
  }

   /**
    * Traverse a directory and get all files,
    * and add the file into fileList 
    * @param node file or directory
    */
   public void generateFileList(File node){

       //add file only
    if(node.isFile()){
        fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
    }

    if(node.isDirectory()){
        String[] subNote = node.list();
        for(String filename : subNote){
            generateFileList(new File(node, filename));
        }
    }

   }

   /**
    * Format the file path for zip
    * @param file file path
    * @return Formatted file path
    */
   private String generateZipEntry(String file){
       return file.substring(SOURCE_FOLDER.length(), file.length());
   }
}
--------------------------------------
example:
String myFiles = "C:\\myfiles\\"; //do not forgot the backslash in this version
String  outZipName = "compressedFiles"; //compressedFile.zip
AppZip az = new AppZip(myFiles, outZipName);
az.zipIt();




non-recursive version:
http://stackoverflow.com/questions/8409219/zipping-files-and-folders-in-android

Thursday, March 1, 2012

[Java] Recursive listFiles with filter

 /** original: http://snippets.dzone.com/posts/show/1875
*
*    
*    modified by Spencer, Mar. 1, 2012
*    overload member function listfiles: directory name and extension are also acceptable.
*/
import java.io.*;
import java.util.*;
public class FileRecursor
{
public static File[] listFilesAsArray(
        File directory,
        FilenameFilter filter,
        boolean recurse)
{
    Collection<File> files = listFiles(directory,
            filter, recurse);
//Java4: Collection files = listFiles(directory, filter, recurse);
   
    File[] arr = new File[files.size()];
    return files.toArray(arr);
}

public static File[] listFilesAsArray(
        final String sDirectory,
        final String sFilter,
        boolean recurse)
{
    File directory = new File(sDirectory);
    FilenameFilter filter = new FilenameFilter()
    {
        public boolean accept(File dir, String name)
        {
             return name.endsWith(sFilter);
         }
    };
    Collection<File> files = listFiles(directory,
            filter, recurse);
//Java4: Collection files = listFiles(directory, filter, recurse);
   
    File[] arr = new File[files.size()];
    return files.toArray(arr);
}

public static Collection<File> listFiles(
// Java4: public static Collection listFiles(
        File directory,
        FilenameFilter filter,
        boolean recurse)
{
    // List of files / directories
    Vector<File> files = new Vector<File>();
// Java4: Vector files = new Vector();
   
    // Get files / directories in the directory
    File[] entries = directory.listFiles();
   
    // Go over entries
    for (File entry : entries)
    {
// Java4: for (int f = 0; f < files.length; f++) {
// Java4:     File entry = (File) files[f];

        // If there is no filter or the filter accepts the
        // file / directory, add it to the list
        if (filter == null || filter.accept(directory, entry.getName()))
        {
            files.add(entry);
        }
       
        // If the file is a directory and the recurse flag
        // is set, recurse into the directory
        if (recurse && entry.isDirectory())
        {
            files.addAll(listFiles(entry, filter, recurse));
        }
    }
   
    // Return collection of files
    return files;       
}
}

////////////

Example:     
//list the .java files under the current directory
File[] filelist = new FileRecursor().listFilesAsArray("./" ,".java", true);
for(File f:filelist)
   System.out.println(f.getName());

Monday, February 20, 2012

[Android] Android + Eclipse on Mac

1.Download JDK
  
  developer.apple.com

  Click the 'Resource' at the top bar to find the package suit your os

  install it, we assume the path (JDK)is:

  /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Commands



2. Download Android SDK
   
    http://developer.android.com/sdk/

   Choose the suitable version


   Extract it, here, we assume you put the extracted file under : '/Library/android-sdk-macosx'
  $ cd  /Library/android-skd-macosx/tools
  $ ./android

  Choose those version of Android SDK you wish to develop on, then 'Accept all'


3. Download Eclipse and android ADT plug-in
    http://www.eclipse.org/downloads/

    Install and open Eclipse

    Click Help -> Install New Software...

    Click and 'Add...' button on the right side of 'With with'

    Enter you self-description in Name field, say, 'Android Development Kit (ADT)'
    fill the location filed with: 'https://dl-ssl.google.com/android/eclipse/'

    Install 'Android DDMS' and 'Android Development tools' at least
    (If there are error messages under Win7, try running your eclipse as Administrator)

    Click Eclipse -> Preferences -> Android    and set the SDK location as:
    /Library/android-sdk-macosx

Sunday, February 19, 2012

[Git] Git on your MAC

[By macport]
1. Install macport at http://www.macports.org/install.php

sudo port selfupdate 

sudo port install git-core

For default, it will be installed in
/opt/local/bin/git

Note:
Xcode package include git also, its path is:
/usr/bin/git


GUI for git
http://www.sourcetreeapp.com/
or on AppleStore
http://itunes.apple.com/us/app/sourcetree/id411678673


[w/o macport]
 Download the installer for OSX
 http://code.google.com/p/git-osx-installer/


Initialize the current directory:
git init
Add the current directory to tracking repository
git  add .
Commit all the file under the current directory with message 'XXX'
git commit -a -m 'XXX'
Modify the commit message
git commit --amend -m 'new message'
Name the last commit file as 'ver1.0' (branch)
git tag ver1.0
Show all file whose version is 'ver1.0'
git show ver1.0[:[spec file]]
Show the message
git show HEAD
show last message
git show HEAD^
Checkout (restore) all the files to commit 'ver1.0'
git reset ver1.0
Checkout (restore) to last commit
git reset HEAD^

Work with a remote repository
http://spencerimp.blogspot.tw/2013/10/git-how-to-use-git-on-bitbucket.html


You can use option -h to know detail about the command


reference
http://tkg.im.ncue.edu.tw/?p=755

Tuesday, January 10, 2012

[VNC] VNC fullscreen

1. use SSH to login your account

2. edit your ~/.vnc/xstartup
   comment and add
   #twm
  gnome-session &
  #if you use kde
  #startkde

3 start the vncserver by this

   vncserver -geometry 1920x1080


and your session would have a window with 1920x1080 volume