Posts

Showing posts from June, 2013

Reset Wordpress admin's password through MySQL

This tutorial is from the wordpress documentation http://codex.wordpress.org/Resetting_Your_Password:

Get an MD5 hash of your password.Visit md5 Hash Generator, or...Create a key with Python. or...On Unix/Linux:Create file wp.txt with the new password in it (and *nothing* else)md5sum wp.txtrm wp.txt"mysql -u root -p" (log in to MySQL)

Ubuntu - Auto-mount your partitions

I have some partitions and I want to tell the system to mount those partitions automatically whenever my computer restarts. I heard that Ubuntu 13.04 has some great feature that have GUI to make the job easier, Disks. I tried to use it:

1. Open Disks from the Ubuntu Application Launcher, and choose the partition I want, let call it Partition 6.
2. Click the gear icon (settings), choose Edit Mount Options.
3. Turn off Automatic Mount Options and enter the information for my partition. Then, click OK
I'd thought it gonna work, but it's not. I got an error about some wrong options when I mount the partition.
After awhile googling around, I found a thread from the Linux Mint forum which tells me not to use the Disks utilities of Ubuntu, but modifying the fstab directly instead:

Note: You might want to run the following command to make sure it really has that UUID number and that it is in fact formatted to ext3:
sudo blkid -c /dev/null

Android - Host your Linux images with DriveDroid

Yeah, It's true. You can host your Linux images (Ubuntu, Xubuntu, debian, fedora...) in your Android devices and boot from it. Now with DriveDroid, You don't need any dedicated USB drive or CDs/DVDs which are in a special format (FAT...) to be able to boot from. Everything you need to do are some super simple steps:

1. Install DriveDroid from the Google Play market: https://play.google.com/store/apps/details?id=com.softwarebakery.drivedroid&hl=en

2. Download any Linux Image you want. I recently host the Xubuntu in my Android phone with DriveDroid (http://xubuntu.org/). And then copy the image to /storage/sdcard0/Download/images .

3. On your Android phone, turn on DriveDroid, select the image to let your phone host the file over USB.

4. Restart your computer (make sure that you've set up to boot from USB as the first priority)

5. Enjoy


Note: You can host many Linux images on your phone with DriveDroid.


Reset my password in Ubuntu

I want to write down the "how-to" of resetting password in Ubuntu (in my case It's is Ubuntu v12.10) which is not something new, but helpful:

1. Reset the computer and press or hold down the Shift key the see the Grub menu, and choose Advanced options for Ubuntu

2. Select the first recovery mode item on the list

3. Choose root - Drop to root shell prompt

4. Remount the root directory by entering the following command:

mount -rw -o remount /

5. Reset my password:

passwd trinh

Note: "trinh" here is my username

I've rooted my Android phone

Today, after a while, I decided to root my Lenovo p770 which is running Android v4.1.1.

I followed the guide from the xda forum: http://forum.xda-developers.com/showthread.php?t=2220275

Here are some issues I faced along the way:

1. At step 4a (Guide for rooting your phone (using CWM) and Google Apps (optionally), install theRoot_by_javum.zip file:

When booting to CWM, I saw the menu "apply zip from sdcard" instead of "“install zip from sdcard", and the menus are in yellow or brown color. After awhile re-tried the 3rd step of the guide (3) Guide for Winflash recovery flashing, including CWM (Clockwork Mod Recovery) ), I finally saw the corrected menu ("install zip from sdcard", and the menus are in blue color)

2. Step 4b, install Google play:

Have to start the 3rd step again.

3. After my phone had been rooted, all of apps stopped working:

- I forgot to adjust the correct date/time settings. After set the right date and time, everything was OK.


Now I have …

Moodle - Using external database for courses enrolment

Image
The Moodle v2.5 gives us a very cool plugin for enrolment with pre-defined courses, teachers, and students data which are stored in an external database. You can enable that plugin following these steps:

- Log-in to your moodle using the site administrator account, in the Plugins sections of Site administration menu, select Enrolments, then select Manage enrol plugins:

Python - Convert a list of string into a list of integer

Assuming I have a list of strings like the following:

my_list = ['1', '2', '3']

and then I want to make it a list of integer:

my_list = map(int, my_list)

That's it!

My ebooks collection

Image
I stored my ebooks collection in my Copy Cloud Storage:

[Cannot share links because of the copyright :D]

(email me to request for download link)


(source: http://3.bp.blogspot.com/-fjoJGAXtKqk/TzlvExT3o8I/AAAAAAAADeo/vCEdwJuhqHM/s1600/IMG_3259.JPG)

Have a nice weekend!

Copy Cloud Storage - Fix "Out Of Disk Space" error of Copy Agent

One day, my Copy Agent notified me that I'm out of disk space. My machine's hard drive still has 107GB of free space instead. So, what's going on here?

After Googling around, I saw this method, it maybe helpful:

Open up Terminal and run these commands, as root:# echo 16384 > /proc/sys/fs/inotify/max_user_watches To make the change permanent, edit the file /etc/sysctl.conf and add this line to the end of the file:fs.inotify.max_user_watches=16384

If the above method doesn't help, try this:

- Remove the Copy's config folder, in my case:

sudo rm -r /home/trinh/.copy

- Download and install the new Copy Agent at https://www.copy.com/install/

- Re-setup your account and enjoy!



Python - Remove duplicate dictionaries in a list

Assuming I have a list of dictionaries, and I want to remove all of duplicate item from that list. The set built-in type of Python is what we need:


def remove_duplicate_items(my_list):
return_list = []
myset = set()
for i in my_list:
t = tuple(i.items())
if t not in myset:
myset.add(t)
return_list.append(i)

return return_list

my_list = [{'a': 1, 'b': 2}, {'a': 4, 'b': 7}, {'a': 1, 'b': 2}]

my_final_list = remove_duplicate_items(my_list)

>>> [{'a': 1, 'b': 2}, {'a': 4, 'b': 7}]

Remember: a set only accepts tuples as its items.

SQLAlchemy Python module with MySQL

Image
SQLAlchemy is such a great Python module to work with DBMs. This blog is about how to manipulate MySQL database with SQLAlchemy.

1. Install MySQL driver for Python:

$ sudo apt-get build-dep python-mysqldb

$ sudo pip install MySQL-python

2. Install SQLAlchemy:

$ sudo pip install SQLAlchemy

3. Example:

- We have a database name mydb which contains 1 table, name mytable:

Python - Send email with attachments

This is the code snippet to send an email with attachments using python smtp module:

Useful Python string methods

The Python built-in string type has many useful methods that can make your life easier. You can navigate all of them, the methods in the Python documentation: http://docs.python.org/2/library/stdtypes.html#string-methods

One of those is the method that check if a string is a number. For example, you have a string, let's call it:

my_str = "Linux101"

 The first 5 characters stands for the subject, and the last 3 characters stands for the session of the class. We have a dictionary of teachers:

edX-platform - Source code exploration

Image
I'm pretty sure that we all know the famous online learning websites, Coursera, edX, Udacity... They have changed the education system of the world and created a new revolution about how people access the knowledge. Those MOOC (Massive Open Online Courses) platform provide us the tools to study whatever subjects we like in a professional way just like we did it in college through the Internet. And there are more and more advantages of using those tools to achieving our studying targets, you name it.

Today, I found that the edX team has opened their source code to the public and make clear about the edX project's vision: open platform for open-minded learner. They stated:

How to fix "E: Could not get lock /var/cache/apt/archives/lock - open (11: Resource temporarily unavailable)"

Just got the error when upgrading my system (Ubuntu 12.04):

---
E: Could not get lock /var/cache/apt/archives/lock - open (11: Resource temporarily unavailable)
E: Unable to lock directory /var/cache/apt/archives/
---

And here're things I need to do to get rid of that annoying error:

$ sudo rm /var/lib/apt/lists/lock

$ sudo rm /var/cache/apt/archives/lock

Check if a DN on a M$ Active Directory existed

I will use the ssh_client module I wrote (http://iambusychangingtheworld.blogspot.com/2013/05/manipulate-windows-machines-from-linux.html) to execute M$ Windows Active Directory command line remotely from my Ubuntu.

#! /usr/bin/python
import ssh_client

def dn_existed(dn, type_of_dn, ssh_client):

# type_of_dn is group, ou or user
command = 'dsget ' + type_of_dn + ' "' + dn + '"'
ssh_client.execute_command(command)

if 'succeeded' in ssh_client.return_str:
return True

return False

if __name__ == "__main__":
       client = ssh_client.MySSHClient()
       client.do_connect()

       dn = 'OU=MYOU,DC=MYGENIUS,DC=COM'
       if dn_existed(dn, 'ou', client):
              print "Existed"
       else:
              print "Not existed"


Some errors when executing M$ Active Directory commands

I list here some of the error occur when I use commands tool to manipulate the M$ Active Directory instead of using GUI.

#1:  Directory object not found.:The object was created successfully but there was an error during post create operations.:

- Solution: check the command which will be executed (e.g.: output using python print built-in function...). It mostly caused by the DN parameter of your command has not been configured or created.

Example: dsadd user "CN=Super\, Genius99,OU=2099 Class Users,OU=Students,DC=MYSCHOOL,DC=ORG" -samid supergenius99 -upn supergenius99@myschool.org -pwd 126428 -fn Super -ln Genius -display "Super, Genius" -desc "Student 2099" -office 700004 -emailsuper99@myschool.org -memberof "CN=2099 Class,OU=Student Groups,OU=Students,DC=MYSCHOOL,DC=ORG" "CN=Students,OU=Student Groups,OU=Students,DC=MYSCHOOL,DC=ORG" -mustchpwd no -disabled no

All the DNs:
+  "OU=2099 Class Users,OU=Students,DC=MYSCHOOL,DC=ORG&qu…

Python + Oracle + SQLAlchemy on Ubuntu 13.04

Image
This is quite a beautiful night, so I want to post a blog about using python along with Oracle database and SQLAlchemy module.

My computer is running Ubuntu 13.04 x86-64bit, python 2.7.4. So, I will show you how to make python work with Oracle database in that enviroment, but, you can find the relevant packages for your own machine by looking arround the provided urls.

Let's start it!

1. Installing the Oracle driver for python: I use cx_Oracle here:

a. Install alien to convert rpm packages to deb packages (because we the Oracle instant client and cx_Oracle are rpm packages, and Ubuntu use .deb instead):

Shell - Copying file from remote server to local machine

Sometime you want to copy something (files) from your remote server to your local machine. The thing is, the remote server is the only one that has ssh, so you can only push file to it (remote one) through scp command.

I found the rsync command that solves the problem: (type this in your local machine's terminal)

rsync -chavzP --stats user@remote.host:/path/to/copy /path/to/local/storage

Free Javascript, Python,... ebooks

Just found some great free sources:

Javascript books: http://jsbooks.revolunet.com/

Python books: http://pythonbooks.revolunet.com/

Many things: http://it-ebooks.info/

Shell - Remove grep itself from grep's output

Image
When grepping something you usually see the grep itselft:



 to remove grep from the grep's output:

$ sudo ps aux | grep mysql | grep -v grep


Python - print the absolute path of the current file

This is just a small note when I tried to get the path of the current (python) file:

#! /usr/bin python
import os

print os.path.dirname(os.path.abspath(__file__))


Note: The above script wont work in the Python REPL shell.



"Don't let life randomly kick you into an adult you don't want to become" ~Chris Hadfield

Image
This series of photos illustrates the story of Chris Hadfield (Commander, expedition 35, International Space Station).

Source: http://www.linkedin.com/today/post/article/20130604171414-2967511-why-it-s-still-important-to-follow-your-heart?trk=tod-home-art-medium_0

See and get inspired:

A story of the Googler #13

Image
Today, I read a story about a man who did whatever he can to get a job. He's is Steve Schimmel, the Google's employee number 13.

The article appeared on Hacker Monthly Issue #12, Published May 2011 (http://hackermonthly.com/issue-12.html)

Here is the story:


Bulk model objects creation in Django

Have you ever thought about creating a list of model objects in one query (through Django ORM of-course)? It's really fast! Bumb, and everything are in the db.

Usually, we create and save objects in the db by calling:

from my_project.my_app import models

my_first_obj = models.MyModel(my_attr='genius')
my_first_obj.save()

my_second_obj = models.MyModel(my_attr='super')
my_second_obj.save()

Remember the objects are still not save in the database if we do not call 'save()'. The 'save()' is actually the method that communicate (query) with the underlying DBMS. And it takes time to insert object to the db. If the number of objects you have to create is hundreds or thousands, It'll be a really problem. With Django ORM API, we can create all the objects in a single action:

my_first_obj = models.MyModel(my_attr='genius')
my_second_obj = models.MyModel(my_attr='super')
obj_list = [my_first_obj, my_second_obj]
created_objs = models.MyModel.objects.…

Bash - Check if an user existed in Django db

When deploying my Django app  to a server, I want to create a script to create Django superuser. The script will check if the inputed user_name existed, if YES, It will prompt me to change password, if NO, it will create the user for me.

I use the mysql command to query the user (auth_user table) from the shell just like the way I did in the previous blog spot (http://iambusychangingtheworld.blogspot.com/2013/06/bash-check-if-mysql-database-is-existed.html).

create_superuser.sh:

#! /bin/bash
# $1: db username
# $2: db password
# $3: db name
# $4: admin username
cd /home/projects/myproject/
. /home/.venv/myvenv/bin/activate
RESULT=`mysql -u $1 -p"$2" --skip-column-names -e "USE '$3';SELECT username FROM auth_user WHERE username='$4'"`
if echo "$RESULT" | egrep -q "$4" ; then
echo "$4 existed"
exec python manage.py changepassword $4
else
echo "$4 not existed" 
exec python manage.py createsuperuser --username $4
fi


Then, run the…

Bash - Check if a mysql database existed

I use mysqlshow command to check if a mysql database existed, check_db_existed.sh:

#! /bin/bash
# $1: db username
# $2: db password
# $3: db name

#RESULT=`mysqlshow -u $1 -p"$2" $3 | grep -v Wildcard | grep -o $3`
RESULT=`mysql -u $1 -p"$2" --skip-column-names -e "SHOW DATABASES LIKE '$3'"`
if echo "$RESULT" | egrep -q "$3" ; then
echo "$3 existed"
else
echo "$3 not existed"
fi

And call the script to check if 'mydb' existed, (root is db username and password) :

# sh check_db_existed.sh root root mydb



2013 Enterprise End User Report by Linux Foundation

Image
According to the Enterprise End User Report Linux Adoption made by the Linux Foundation, March 2013:

"Linux is the dominant platform for cloud computing"
The report points out some critical statistics and data, such as:

- The openness of Linux environment helps enterprise users foster their cloud system.
- The increasing use of Linux is way more than Windows
- More and more organizations said that they want to migrate their system from Windows to Linux
- More needs on Linux talents with pros and cons.

For more detail and further information, please read the report at (download needed): http://www.linuxfoundation.org/publications/linux-foundation/linux-adoption-trends-end-user-report-2013

Infographic:

Getting started with static files in Django

For the first time I worked with Django (v1.1), I had to do something like: adding the url pattern point to static directory of my project in the main urls.py file:

...
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': False}),
...


In the newest version of Django (1.5.1) which I'm using right now, all I have to do is:

1. Put  the static files in a static subdirectory of my apps (myapp/static/) or list absolute path to static directories in

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    #~ '/home/projects/mystatics/',
)

Django will serves your app static files by looking for them in those above directories. 

2. Leave the main static directory (the STATIC_ROOT) bl…

Bash shell to check if a string is existed in another string

The example script to check if 'new_user' of rabbitmq has been created:



Note: the double-quote used in USERS_LIST=`rabbitmqctl list_users`  is "`" , not "'"

Restore missing conf files of a package in /etc

Here is my case:

- Remove nginx by using the command: sudo apt-get remove nginx
- Delete /etc/nginx config folder: sudo rm -r /etc/nginx
- Re-install nginx: sudo apt-get install nginx
- Cannot start nginx because of missing conf file! Oops!

After awhile searching on the Internet, I found a solution:
All you need to do: Find the list of conffiles provided by the package:dpkg --status <package> (look under the Conffiles: section). Remove those conffiles yourself. Reinstall the package. If you've found the .deb file,dpkg -i --force-confmiss <package_deb>.deb Alternatively, passing the dpkg option via apt should work:apt-get install --reinstall -o Dpkg::Options::="--force-confmiss" <package>
Especially in Ubuntu, I have to look for the packages in the cache folder, and It works:
sudo dpkg -i --force-confmiss /var/cache/apt/archives/nginx*.deb
Awesome!

Vine for Android

Yeahooo,

A couple days ago, Twitter announced and released the Android version of Vine, a 6-seconds blog app. I'm trying it now!!! It's so funny!!!! \m/\m/\m/

Here are some of my short-clips:

How to forcefully kill mysqld process

Sometimes, I just cannot kill the mysqld process. The mysqld process will automatically start a new one with a different id or port after I kill its process with the command line:

$ sudo kill -9 <mysqld_id>

Then I found this cool solution:

$ sudo mysqladmin -u root -p shutdown

Deploy Django app with Fabric made easy

Here we go,

The last time I deployed my Django app to a production server, I felt pain in the ass. I had to do all the same things repeatedly: copy the source code, create a virtualenv for my app, config nginx, supervisor... And then I found Fabric. Fabric help me do the pre-defined actions in a script file name fabfile.py.

Follow the instructions of a tutorial (http://www.abidibo.net/blog/2012/06/29/deploy-django-applications-nginx-uwsgi-virtualenv-south-git-and-fabric-part-5/), I modified the fabfile to fit my needs. And here are the steps: