Python

Example factorial in Python using coroutine generator

27 Dec , 2012  

I trying to remember what is factorial then I open wikipedia and found that factorial is all the positive integer that less than or equal with n. Here is a quick implementation in Python using generator:

1
2
3
4
5
6
7
8
9
10
11
12
def factorial(n):
    while (n > 0):
        yield n
        n -= 1
    print("Finish ...")

if __name__ == "__main__":
    number = 1
    for x in factorial(10):
        print(x)
        number = number * x
    print("Total: " + str(number))

,

Android

Android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

25 Dec , 2012  

If we got this errors :

1
Android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

What we want?
We want to create a new records and read it.

Problem?
Data is created but we can’t read the new saved records.

Solution? using “moveToFirst()”. Here is the example:

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
33
public Cursor createNewRecord() {
        // Set the new records ID
    long insertId = database.insert(dbHelper.TABLE_TRACKER, null, values);
   
    // Inserting a new records
    mCursor = database.query(dbHelper.TABLE_TRACKER,
            allColumns, dbHelper.COLUMN_ID + " = " + insertId,
            null, null, null, null);
   
    mCursor.moveToFirst();  // This will read the NEW RECORD DATA      

    // Mapping cursor data into newData
    UserDatabase newData = cursorToUser(mCursor);
   
    // Close cursor connection
    mCursor.close();
   
    return newData;
}

/**
 * Mapping cursor into UserDatabase handler
 * @param cursor
 * @return
 */
private UserDatabase cursorToUser(Cursor cursor) {
    UserDatabase userDatabase = new UserDatabase();
    userDatabase.setId(cursor.getLong(0));
    userDatabase.setDay(cursor.getInt(1));
    userDatabase.setIsExercise(cursor.getInt(2));

    return userDatabase;
}

,

Android

Check if Cursor data is exists or not with SQLite database in Android

25 Dec , 2012  

When creating a data, sometimes we need to check whether there is a previous data that can be updated or not. To check if data is exists or not, we can use “cursor.moveToFirst()” instead of “cursor.getCount() > 0”. Simple example :

1
2
3
4
5
6
7
8
9
// Check if days is exists
mCursor = database.query(dbHelper.TABLE_TRACKER,
        allColumns, dbHelper.COLUMN_DAY + "=?",
        new String[] {Integer.toString(day)}, null, null, null, null);
       
// If data exists, then update the records
if(mCursor.moveToFirst()) {
    // Do your update logic here
}

But, then we can do enhancement like if data exists, then update the data. Meanwhile, if there no records, then create a new records. Here is the implementation :

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
Cursor mCursor;

// Check if days is exists
mCursor = database.query(dbHelper.TABLE_TRACKER,
        allColumns, dbHelper.COLUMN_DAY + "=?",
        new String[] {Integer.toString(day)}, null, null, null, null);
       
// If data exists, then update the records
if(mCursor.moveToFirst()) {
    database.update(dbHelper.TABLE_TRACKER, values,
            dbHelper.COLUMN_ID + "=?",
            new String[] {String.valueOf(mCursor.getColumnIndex("id"))}
    );

} else {
    // Set the new records ID
    long insertId = database.insert(dbHelper.TABLE_TRACKER, null, values);
   
    // Inserting a new records
    mCursor = database.query(dbHelper.TABLE_TRACKER,
            allColumns, dbHelper.COLUMN_ID + " = " + insertId,
            null, null, null, null);
   
    mCursor.moveToFirst(); // To get the records
}

...
mCursor.close()

,

Android

BodySlap – Fitness and Workout Tracker Android Application part 3

22 Dec , 2012  

After working with the Dialog and Toast, now in the part 3, BodySlap application (which the previous name is Calendar app) now support for taking photos after workout!

The details update and lesson I’ve learned :

1. Intent is a great way to make UI faster and organize the action between activity.
2. Taking picture from Camera and create a storage album for saving the picture
3. Create a listener and attach them into property like Button, Dialog will make code easy to read

Here is the results:

You can grab this on my github : https://github.com/yodiaditya/android

Previous version :
http://www.yodi.biz/2012/12/16/immediate-update-item-cells-in-gridview-android/
http://www.yodi.biz/2012/12/09/build-calendar-applications-with-todo-list-and-activity-in-android-part-2/
http://www.yodi.biz/2012/12/08/build-calendar-applications-with-todo-list-and-activity-in-android-part-1/

,

Java

Get the today date in string format in Java

22 Dec , 2012  

Date() in java.utils provide Date instance which contains the date of today. We can showing the day, month, year of today from Date() instance using SimpleDateFormat().format().

Example:

1
String today = new SimpleDateFormat("yyyyMMdd_HH:mm:ss").format(new Date());

Simple!

,

Java

Convert String to Integer and Integer to String in Java vice versa

22 Dec , 2012  

To convert Integer into String in Java, we can use toString() method in Integer class instance :

1
2
Integer hello = 1;
String convert = Integer.toString(hello);

Then, to convert String into Integer, we can use parseInt() method in Integer class instance:

1
2
String hello = "1";
Integer convert = Integer.parseInt(hello);

Easy! 🙂

,

Android

Example Dialog box in Android

18 Dec , 2012  

Dialog is the good way to providing floating menu in Android which users can do several actions on there. It’s different with Toast which is have purpose for showing information only. At this example, we can try which showing selection menu in Dialog box.

For instance, We will make Users can click Button and Dialog will be pop-up. Suppose we have activity like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MainActivity extends Activity {
    private static final int DIALOG_ALERT = 10;
    private static final String ANDROID_TAG = "ANDROID";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Button workout = (Button) findViewById(R.id.top_done_button);
        workout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(DIALOG_ALERT);
            }
        });
    }

showDialog() is built-in method which will showing Dialog based on the unique ID. Later, we can give related Dialog based on ID using switch(). But we should know that showDialog will be expecting for onCreateDialog() method to process all showDialog() request.
More…

,

Android

Immediate update item cells in GridView android

16 Dec , 2012  

We can update immediately background color in items cells (on visibile view) by calling invalidateViews() after do the update. Here is the implementation :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Set image adapter instance from private variable
imageAdapter = new ItemAdapter(this);

// Bind Gridview with calendar XML and set the Adapter
final GridView gridView = (GridView) findViewById(R.id.calendar);
gridView.setAdapter(imageAdapter);

Button workout = (Button) findViewById(R.id.top_done_button);
workout.setOnClickListener(new View.OnClickListener() {        
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Context context = getApplicationContext();
        String text = "Yeah! You're ready workout now!";
        Toast toast = Toast.makeText(context, text,
                Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.show();
       
        // Set date pickers cells
        imageAdapter.setDatePicker(today.getDate());
        gridView.invalidateViews();
    }
});

invalidateViews() called after we doing update on Gridviews items on setDatePicker() method.
Here is the result (without scrolling to update the views) :

And, after I click the workout button:

Next update:
http://www.yodi.biz/2012/12/22/bodyslap-fitness-and-workout-tracker-android-application-part-3/

,

Android

Solve problem wrong update views background color cells in GridView android

16 Dec , 2012  

Usually we need to update item in GridView programmatically without using “ClickListener”. Instead, we can set a “selected position” variable in our Adapter and do position matching in getView(). Usually, our code will end-up like this:

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
public void setChoosenDate(int date) {
    this.selectedDate = date;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    ViewHolder holder; // to reference the child views for later actions
   
    if(convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.item, null);
       
        // cache view fields into the holder
        holder = new ViewHolder();
                ....
       
    } else {
        holder = (ViewHolder) convertView.getTag();
       
        if(this.selectedDate != null && position == this.selectedDate) {
            Log.d(LOG_TAG, "Selected position : " + position);

            // Set text resource on each position      
            convertView.setBackgroundColor(Color.BLACK);
            Log.d(LOG_TAG, "Selected position : " + convertView.getId());
        }
    }

    return convertView;
}

More…

,

Android

How to set FULLSCREEN application window in Android

13 Dec , 2012  

We can set our application into FULL SCREEN mode which will show in entire Android monitor. To do it, we just need to declare FLAG_FULLSCREEN in our Activity. For instance:

1
2
3
4
5
6
7
8
9
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Remove application title
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);
...

Django

Be careful when validate input using length() in Javascript

13 Dec , 2012  

This is trivial things but sometimes just happen. For instance we want to validate the input from users. Fyi, I use JQuery example here.

1
var amount = $(".amount p").text();

When we want to validate amount when we pass this variable into function, usually we use:

1
2
3
if(amount.length > 0) {
     // logic here
}

But, when we have amount in Integer or Float, then it will be problem, eg:

1
2
var amount = $(".amount p").text();
var amount = parseFloat(amount);

Using validation based on length will be failed. Instead of counting on string element length, we can use this validation:

1
2
3
if(amount) {
     // logic here
}

So, this the tricky part is how we validation javascript variable data type.

,

Django

Unit Test in Django doesn’t running the test method inside the TestCase

12 Dec , 2012  

If you got the problem like what I mention on the title, that’s mean you need to take a rest. Why? The big possibilty is sometimes we forgot to add “test” as prefix on our testCase method. For instance:

1
2
3
4
5
6
7
8
class InsuranceTestCase(TestCase):
    """Insurance unit-testing"""

    def setUp(self):
        pass

    def check_whether_user_valid(self):
        pass

When you running this unit-test, Django will give result 0 test has been executed. So, the correct way is :

1
2
3
4
5
6
7
8
class InsuranceTestCase(TestCase):
    """Insurance unit-testing"""

    def setUp(self):
        pass

    def test_check_whether_user_valid(self):
        pass

Simple! 🙂

,

Django

Solve django admin search error related fields has invalid lookup: icontains

11 Dec , 2012  

When we trying to do search in Django admin, suddenly we caught by this error:

1
2
TypeError at /admin/myapp/myappfolder/
Related Field has invalid lookup: icontains

Then we should check that search_fields in DjangoAdmin should be on field rather on ForeignKey objects.
Eg :

1
2
3
4
5
class InsuranceAdmin(admin.ModelAdmin):
    """Set Insurance Configuration in Admin page"""
    list_display = ["country", "subscription", "created", "modified"]
    list_filter = ("country", "subscription")
    search_fields = ('country', )

At this example, country is ForeignKey to Country models. When it comes to search_fields, it’s should be fields, so the correct version is :

1
2
3
4
5
class InsuranceAdmin(admin.ModelAdmin):
    """Set Insurance Configuration in Admin page"""
    list_display = ["country", "subscription", "created", "modified"]
    list_filter = ("country", "subscription")
    search_fields = ('country__name', )

,

Django

Django suddenly get very heavy and slow

11 Dec , 2012  

Today i found something weird with my django applications. Suddenly, it became heavy and slow. It took 100 to 150 % of Python process. Sometimes I saw this error :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Traceback (most recent call last):
  File "/home/tripvillas/.virtualenvs/trip/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 284, in run
    self.finish_response()
  File "/home/tripvillas/.virtualenvs/trip/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 324, in finish_response
    self.write(data)
  File "/home/tripvillas/.virtualenvs/trip/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 403, in write
    self.send_headers()
  File "/home/tripvillas/.virtualenvs/trip/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 467, in send_headers
    self.send_preamble()
  File "/home/tripvillas/.virtualenvs/trip/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 385, in send_preamble
    'Date: %srn' % http_date()
  File "/usr/lib64/python2.7/socket.py", line 324, in write
    self.flush()
  File "/usr/lib64/python2.7/socket.py", line 303, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe

After looking at different part, then I found the culprit was Django Debug Toolbar. Indeed, after i disabled django-debug-toolbar, suddenly it became fast again! Weird!

,

Android

Build Calendar Applications with TODO List and Activity in Android Part 2

9 Dec , 2012  

Yes, i’ve made progress in building my Android applications. There is a new things I’ve learned today, especially on design. I found out that RelativeLayout is powerfull and flexible to build blocks.

Here is the Part 2 results :

You can grab this on my github : https://github.com/yodiaditya/android

Previous:
http://www.yodi.biz/2012/12/08/build-calendar-applications-with-todo-list-and-activity-in-android-part-1/

Next update:
http://www.yodi.biz/2012/12/16/immediate-update-item-cells-in-gridview-android/

Server

Solve [error] 28901#0: *401 upstream sent too big header while reading response header from upstream

9 Dec , 2012  

Today I got this 502 error on my websites :

1
Solve [error] 28901#0: *401 upstream sent too big header while reading response header from upstream, client: 116.86.214.27, server: yodi.biz, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "yodi.biz"

After looking at NGINX documentation, i found the problem in my fastcgi buffers. So, the solution is just open /etc/nginx/nginx.conf and on “http” part, put this :

1
2
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;

If you still get 502 upstream sent too big header, then try to increase the fastcgi buffers 🙂

,

Android

Android : How to disable or remove application name title bar

8 Dec , 2012  

When building Android application, it will have Application Title on top bar as default. We can remove this app title bar with 2 ways. Here is how to remove title bar:

1. Using AndroidManifest.XML
In the Activity, we can set the Theme using NoTitleBar, like this:

1
2
3
4
5
<activity
     android:name="com.yodi.calendar.MainActivity"
     android:theme="@android:style/Theme.Black.NoTitleBar"
     android:label="@string/app_name" >
</activity>

2. Define in Activity
Which on the files that contain Activity, we can set the RequestWindowFeature with Window.FEATURE.NO_TITLE and set flags before we set the ContentView.

1
2
3
4
5
6
7
8
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Remove application title
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
...

Now when we running the application, the title application will be dissapear 🙂

,

Android

Build Calendar Applications with TODO List and Activity in Android Part 1

8 Dec , 2012  

I’ve plan to build Calendar apps which make people can make note about their Activity and Achievement every-day. For the first step, here is the plan of the things I want to build:

1. Build calendar list of today
2. Each day have detail page

Based on that requirement, I found what I should’ve to learn:

1. Build Calendar in Java
2. Intent and Activity
3. Layout and XML
4. Adapter for the View

So, I start learning how to build calendar in Java, set XML layout for displaying calendar and create action handler for GridView ItemOnClick to execute another activity.

Then here is the results for today:

Main page

You can grab this on my github : https://github.com/yodiaditya/android

Next Update:
http://www.yodi.biz/2012/12/09/build-calendar-applications-with-todo-list-and-activity-in-android-part-2/

Android

Example click on detail item using intent and use another Activity in Android

7 Dec , 2012  

The usual things when we deploy application in Android is providing detail information after user click on some parts of our application. Given example is calendar, which have MainActivity like this:

MainActivity.java

1
<br /> package com.yodi.calendar;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

GridView gridView = (GridView) findViewById(R.id.calendar);
gridView.setAdapter(new ImageAdapter(this));

gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView< ?> parent, View v,
int position, long id) {
// Create Intent to passing id position to CalendarDetail
Intent i = new Intent(getApplicationContext(),
CalendarDetail.class);
i.putExtra(“id”, position);
startActivity(i);
}
});
}

}

More…

,

Python

Convert date into datetime and reverse datetime into date objects in Python

6 Dec , 2012  

This is a quick tips to convert “datetime” into “date” objects in Python:

1
2
3
4
5
from datetime import datetime
today = datetime.now()
print today
today_date = today.date()
print today_date

The result will be :

1
2
datetime.datetime(2012, 12, 6, 14, 48, 5, 133765)
datetime.date(2012, 12, 6)

Then, how about convert date into datetime objects? We need time() function:

1
2
3
4
5
6
from datetime import date, datetime, time

today = date.today()
print today
today_datetime = datetime.combine(today, time())
print today_datetime

And the result will be :

1
2
datetime.date(2012, 12, 6)
datetime.datetime(2012, 12, 6, 0, 0)

It easy! 😀

,

Django

How to set Django admin models into Read Only mode

3 Dec , 2012  

This is common question we need to showing models of app inside django admin but in read-only mode. That’s meaning admin only can see but can’t modify. For instance, I have models called Insurance :

1
2
3
4
class InsuranceBranch(models.ModelAdmin):
    country = models.ForeignKey(Country)
    created = models.DateTimeField(auto_now_add=True, default=datetime.now())
    modified = models.DateTimeField(auto_now=True, default=datetime.now())

Then, I want to show it into Django admin, so inside admins.py :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class InsuranceBranchAdmin(admin.ModelAdmin):
    list_display = ["country"]
    readonly_fieds = ("country",)
   
    def get_readonly_fields(self, request, obj=None):
        return self.readonly_fieds

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

admin.site.register(InsuranceBranch, InsuranceBranchAdmin)

What this code mean? basically, you need to set readonly_fields to tell Django admin to set this fields into read-only mode.
For has_add_permission and has_delete_permission, we make it to False to keep no data created / deleted.

And the last thing is, set get_readonly_fields() to return readonly_fields to make on Change Page, all become read-only. Simple 🙂