Code

Code

jQuery Mobile Transitions for Link (A tags)

<a href="{link}" data-transition="flip" class="ui-btn"><p>link</p></a></code></pre><div dir="ltr">

Find multiple element id using jQuery

$('[id="a"]');  $('span[id="a"]');


Get Parameter value from URL with JSP

<% String flag = request.getParameter("flag"); %>


Plus(+) sign in Url Parameter

+ means a space only in application/x-www-form-urlencoded content, such as the query part of a URL:
http://www.example.com/path/foo+bar/path?query+name=query+value
query+name -> query name
query+value -> query value

But,
foo+bar -> foo+bar

Reference: http://stackoverflow.com/questions/2678551/when-to-encode-space-to-plus-or-20

Applying jQuery Flip Transitiosn in Mobile

$.mobile.changePage("#page2", { transition: "flip" });
Demo: http://jsfiddle.net/YjsPD/1204/


Rsync simple example (synchronize specific folders)

#!/bin/sh

rsync -azh ./build -e 'ssh -p 22' user@hostname:~/www

Alert dialog for Android


myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("Title");

        final EditText input = new EditText(getContext());
        input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        builder.setView(input);

        // Set up the buttons
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //m_Text = input.getText().toString();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();
    }
});

// or using layout

myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        View view = View.inflate(mContext, R.layout.page, null);
        builder.setView(view);

        // Set up the buttons
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //m_Text = input.getText().toString();

                childDatabase.insert(new Children());

                setAdapter();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();
    }
});


Soundex Class for Java


// reference: http://en.wikipedia.org/wiki/Soundex
public class SoundexUtil {

	// public static void main(String[] args) {
	// 	System.out.println(soundex("Gauss")); // G200
	// 	System.out.println(soundex("AHN")); // A500
	// }

	public static String soundex(String text) {
		StringBuilder builder = new StringBuilder();
		int numberCounter = 0;

		for (int i = 0; i < text.length(); ++i) {
			char c = text.charAt(i);
			if (i == 0) {
				builder.append(c);

			} else {

				char number = 0;

				switch (Character.toLowerCase(c)) {
				case 'a':
				case 'e':
				case 'h':
				case 'i':
				case 'o':
				case 'u':
				case 'w':
				case 'y':
					continue;

				case 'b':
				case 'f':
				case 'p':
				case 'v':
					number = '1';
					break;

				case 'c':
				case 'g':
				case 'j':
				case 'k':
				case 'q':
				case 's':
				case 'x':
				case 'z':
					number = '2';
					break;

				case 'd':
				case 't':
					number = '3';
					break;

				case 'l':
					number = '4';
					break;

				case 'm':
				case 'n':
					number = '5';
					break;

				case 'r':
					number = '6';
					break;
				}

				if (number > 0
						&& builder.charAt(builder.length() - 1) != number) {
					builder.append(number);
					++numberCounter;
				}
			}
		}

		while (numberCounter < 3) {
			builder.append('0');
			++numberCounter;
		}

		String soundexText = builder.toString();
		return soundexText.substring(0, 4);
	}
}


Palindrome for java


public class Palindrome {

	public static void main(String[] args) {
		System.out.println(isPalindrome("amor roma"));
		System.out.println(isPalindrome("Was it a car or a cat I saw?"));
	}

	public static Boolean isPalindrome(String text) {
		StringBuilder builder = new StringBuilder();
		for (char c : text.toCharArray()) {
			if (Character.isAlphabetic(c)) {
				builder.append(Character.toLowerCase(c));
			}
		}

		text = builder.toString();
		int len = text.length();
		
		for (int i = 0; i < len / 2; ++i) {
			if (text.charAt(i) != text.charAt(len - i - 1)) {
				return false;
			}
		}
		return true;
	}
}


sort check (IsSorted function) for java


public class IsSorted {

	public static void main(String[] args) {
		System.out.println(isSorted(new int[] { 1, 2, 3, 4 })); // true
		System.out.println(isSorted(new int[] { 1, 2, 3, 0 })); // false
	}

	public static boolean isSorted(int[] items) {
		for (int i = 0; i < items.length - 1; ++i) {
			if (items[i] > items[i + 1]) {
				return false;
			}
		}
		return true;
	}
}


Sync system time in Linux using crontab


30 1 * * * root /usr/bin/rdate -s time.bora.net && /sbin/clock -w


post-commit for git


#!/bin/sh

REPOS="$1"
REV="$2"

#mailer.py commit "$REPOS" "$REV" /path/to/mailer.conf
MESSAGE=$(svnlook propget --revprop -r $REV $REPOS svn:log)

cat <<EOF | /root/monitor/sendmail.py -s "[COMMIT] $REPOS:$REV" -r user@domain
REPOS: $REPOS
REV: $REV
MESSAGE:
$MESSAGE
EOF

sendmail using python


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import smtplib
import datetime

from optparse import OptionParser

from smtplib import SMTP as SMTP
from email.MIMEText import MIMEText

DEFAULT_FROM = 'no-reply@domain.com'
DEFAULT_DOMAIN = 'smtp.domain.com'

class SendMail(object):
  username = None
  password = None
  host = None
  port = None

  def __init__(self, username, password, host, port=25):
    self.username = username
    self.password = password
    self.host = host
    self.port = port

  def send(self, subject='', content='', recipient=None):
    conn = SMTP(host=self.host, port=self.port)
    conn.set_debuglevel(False)

    if self.username and self.password:
      conn.login(self.username, self.password)

    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = DEFAULT_FROM
    msg['To'] = recipient

    try:
      conn.sendmail(self.username, recipient.split(','), msg.as_string())

    finally:
      conn.close()

    print 'Sending...'

if __name__ == '__main__':
  parser = OptionParser()
  parser.add_option('-s', '--subject', dest='subject', default='no subject', help='Subject of mail', metavar='SUBJECT')
  parser.add_option('-r', '--recipients', dest='recipients', help='Recipients of mail')
  parser.add_option('--host', dest='host', default=DEFAULT_DOMAIN, help='SMTP server host')
  parser.add_option('--port', dest='port', default='25', help='SMTP server port')
  parser.add_option('--username', dest='username', default=None, help='SMTP username')
  parser.add_option('--password', dest='password', default=None, help='SMTP password')
  
  (options, args) = parser.parse_args()

  lines = []
  for line in sys.stdin:
    stripped = line.strip()
    #if not stripped: break
    lines.append(stripped)
  
  options.content = '\r\n'.join(lines)
  
  sendmail = SendMail(
    username=options.username, 
    password=options.password, 
    host=options.host, 
    port=options.port
    )
    
  sendmail.send(subject=options.subject, content=options.content, recipient=options.recipients)


Swap using XOR algorithm in C# Raw


// http://en.wikipedia.org/wiki/XOR_swap_algorithm
private void Swap(ref int x, ref int y)
{
    x ^= y;
    y ^= x;
    x ^= y;
}


라벨:

GetListItems using Func Generic in C#


Func, ListItem[]> GetListItems = (items) =>
{
    List list = new List();
    foreach(int i in items)
    {
        string item = i.ToString("D2");
        list.Add(new ListItem()
        {
            Text = item,
            Value = item
        });
    }

    return list.ToArray();
};

dropListYear.Items.AddRange(GetListItems(Enumerable.Range(DateTime.Now.Year - 99, 100).Reverse().ToList()));
dropListMonth.Items.AddRange(GetListItems(Enumerable.Range(1, 12).ToList()));
dropListDay.Items.AddRange(GetListItems(Enumerable.Range(1, 31).ToList()));


URL query string parameter to mongoose parameters Raw


exports.query = function(query) {
  var operator = {};
  if (query) {

    var tokenize = function(operator, str) {
      var data = str.split(operator);
      if (data.length > 1) {
        return data;
      }
      return null;
    };

    var tokens = query.split(',');

    for (var i = 0; i < tokens.length; ++i) {
      var selector = tokenize('<=', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]]['$lte'] = selector[1];
        continue;
      }

      selector = tokenize('>=', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]]['$gte'] = selector[1];
        continue;
      }

      selector = tokenize('<', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]]['$lt'] = selector[1];
        continue;
      }

      selector = tokenize('>', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]]['$gt'] = selector[1];
        continue;
      }

      selector = tokenize('!=', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]]['$net'] = selector[1];
        continue;
      }

      selector = tokenize('=', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]] = selector[1];
        continue;
      }

      selector = tokenize('$regex', tokens[i]);
      if (selector) {
        operator[selector[0]] = operator[selector[0]] || {};
        operator[selector[0]] =  new RegExp(selector[1], 'i');
        continue;
      }
    }
  }

  return operator;
};



Subscribe to: Posts (Atom)