Saturday, October 7, 2017

Run mnist example on Caffe


  1. Go to Caffe folder. 
  2. sudo sh data/mnist/get_mnist.sh
  3. sudo sh examples/mnist/create_mnist.sh
  4. sudo vi examples/mnist/lenet_solver.prototxt
  5. sudo time sh examples/mnist/train_lenet.sh
Done
http://blog.csdn.net/xzy_thu/article/details/70842934

Install Caffe on Ubuntu 16.04 (CPU only)


  1. Install a clean Ubuntu 16.04 and mkdir workspace
  2. sudo apt install git and git clone https://github.com/BVLC/caffe
  3. sudo apt-get install libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-dev libhdf5-serial-dev protobuf-compiler
  4. sudo apt-get install libatlas-base-dev
  5. sudo apt-get install libgflags-dev libgoogle-glog-dev liblmdb-dev
  6. Go to python folder inside the caffe directory: cd python/
  7. Install pip: sudo apt install python-pip
  8. Upgrade pip: sudo -H pip install --upgrade pip
  9. Install all the dependency in requirements.txt via: 
    1. for req in 'cat requirements.txt'; do pip install $req; done
    2. sudo pip install -r requirements.txt
  10. sudo apt-get install python-dev
  11. sudo apt-get install -y python-numpy python-scipy
  12. sudo apt-get install --no-install-recommends libboost-all-dev
  13. Go to caffe folder and cp Makefile.config.example Makefile.config. 
  14. Edit Makefile.config: 
    1. INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include /usr/include/hdf5/serial
    2. LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib /usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/hdf5/serial
    3. Uncomment: CPU_ONLY := 1 if this is CPU only mode
  15. Now make!
    1. make pycaffe
    2. make all
    3. make test
    4. make runtest
    5. make distribute
  16. export PYTHONPATH=/path/to/caffe/python:$PYTHONPATH
  17. Verify by running python2.7:
    1. >>> import caffe
    2. >>> caffe._version__
  18. Install opencv: 
    1. sudo apt-get install python-opencv
    2. sudo pip install opencv-python
  19. Install lmdb: sudo pip install lmdb
You should be able to see All Pass. Happy Ending. 
http://blog.csdn.net/qq_25737169/article/details/77773884

Thursday, August 27, 2015

How to achieve splitting equally to N number of people using a coin

What do I mean to split equally to N number of people using a coin? For example, we have a group of six people. Suppose we need a coin to decide who's going to buy the group a round of drink and we have to make this decision unbiased. All we have is a quarter. What can we do about this coin? We can't make this coin into a dice.. :(

Analysis:
We start to notice that flip a coin once makes each 1/2 equally.
If we define flip twice and define both head, head first and then tail, tail first and then head, and both tails as four different outcomes then we have 1/4 (1/2 * 1/2).
Same applies when we flip three times, which give 1/8 (1/2 * 1/2 * 1/2).

Here's the solution:
Suppose head represents 0 and tail is 1 when we flip the coin.
Flip 3 times of coin
Denote each time's result as 0 or 1.
000 – 3 heads
001 – head, head, tail
010 – head, tail, head
011 – head, tail, tail
100 – tail, head, head
101 – tail, head, tail
110 – tail, tail, head
111 – 3 tails

There are eight of them all with 1/8 possibility. We can simply use 6 of them and discard the rest. If the group of people is beyond 8 people then we can simply add one more flip to increase the range up to 16 (1/2 * 1/2 * 1/2 * 1/2).

Thursday, September 18, 2014

Java - Hash Tables

A simple hash function:
h(k)=k mod N.
If a hash function is chosen well, it should guarantee that the probability that two different keys get hashed to the same bucket is at most 1/N. Therefore, instead, the below hash function is more appropriate:
h(k)= (ak+b) mod N.

Android Development using Python in Linux (Ubuntu)

There are a few steps:
Prerequisite:
$ sudo apt-get install python-setuptools python-pygame python-opengl python-gst0.10 python-enchant gstreamer0.10-plugins-good cython python-dev build-essential libgl1-mesa-dev libgles2-mesa-dev

$ python
>>> import pkg_resources
>>> print pkg_resources.resource_filename('kivy', '../share/kivy-examples')
# Copy the address
>>> exit()

$ ln -s address

# Check the kivy examples
$ cd kivy-examples
$ cd demo/touchtracer
$ python main.py

Build the distribution
./distribute.sh -m "kivy"
The file "distribute.sh" can be found at /home/bz/python-for-android


Linux for dummies like myself


You will be amazed about how incredible the materials out there from which we can learn. Below is some:

Ryan's Tutorial has this amazing Linux basic tutorial:
http://ryanstutorials.net/linuxtutorial/

I have learned a lot about bash command in Linux system from Ryan's Tutorial.

I found the book "Linux All-in-One For Dummies" very informative about Linux system you may need. More importantly, you can get it free from IT ebooks for free.


It's quite different to issue all kinds of commands in the shell in Linux system. Although it seems hard to get on your hand at the first sight, you may be quite familiar with how things work after you get to know some basic commands and get your hand wet in this.

grep can be used to search this keyword in a file/log in Linux. It's very handy feature to search. The system will provide the search result in no time. It's suitable to extract the specific thing you can looking for in some large files. e.g. grep "keyword" /destination/location. Another example: scan_r |grep delay; the command is also known as a combined command.

cat displays the content of a file on the command screen. e.g. cat /home/file

at any stage, if you feel like to issue the command in more than one line, and would like to break a line into a new line, you can use backslash \.
e.g. ls /etc; cat \
file |grep name

Asterisk (*): Matches zero or more characters in a filename. That means* denotes all files in a directory.

Question mark (?): Matches any single character. If you type test?, thatmatches any five-character text that begins with test.

Set of characters in brackets: Matches any single character from that set. The string [aB], for example, matches only files named a or B, The string [aB]*, though, matches any filename that starts with a or B.

cp can copy a file/directory from one location to another. e.g. cp -avr /source/location /dest/location

Two takeout note for new learner like me:
1. up-arrow is your best companion... it can bring up all history command that's ever issued in that command window. It will become handy when you ask somebody to perform some tasks and you can review and learn the command afterwards. Also, Tab button saves a lot of time to type something in full... double press Tab can bring up any files that match your current partial input if there's any.
2. avoid using space in file name. If you do use a space in a filename, you have to use backslash \ before each space. If you want to copy the file it would also cause problem... If you have to deal with tons of files, say PNG screenshots, that contains space in it, just tar (compress approach) everything would do the trick.


Sunday, July 21, 2013

Install Spotify in Ubuntu 13.04

How to Install Spotify in Ubuntu 13.04

1. Open a terminal window.
2. Execute each bullet in the terminal.
  • sudo add-apt-repository “deb http://repository.spotify.com stable non-free”
  • sudo apt-get update
  • sudo apt-get install spotify-client-qt
Done!

Saturday, June 8, 2013

Java - Thread

Java offers thread manipulation that allows even single core computer do multitasking, which is also known as Multiprogramming, a way of parallelism.

A Java thread will always be in one of four different states:

  • New
  • Runnable
  • Blocked
  • Dead
"When designing a program that uses multiple threads, we must be careful not to allow an individual thread to monopolize the CPU."  (Textbook)
The above mentioned could potentially lead to hanging of an application, which appears to be running but in fact, doing no computation at all. However, some OS can solve this problem by bring Round Robin as the mechanism to avoid such monopolization. 

A linked list is a collection of nodes that form a linear ordering together. 
A singly linked list:
The next reference inside a node can be viewed as a link/pointer to another node.
Moving from one node to another by following a next reference is known as link hopping/pointer hopping.
The first and last node of a linked list are called the head and tail of the list.
The tail contains a null reference, that indicates the ends of the list.

A singly linked list does not have a predetermined fixed size, and uses space proportional to the number of its elements.

Tuesday, May 21, 2013

R - Part 1

A start with R (to be cont'd)

  • Get the RStudio at here
  • install.packages("devtools")
  • library(devtools)
  • install_github("slidify","ramnathv")
  • install_github("slidifyLibraries","ramnathv")



Approaches of Efficient Academic Reading

Sometimes it is easier to say than done. Follow by the following points which I got inspired from Michael Hanson and Dylan McNamee version of "Efficient Reading of Papers in Science and Technology". Stick to these principles for a while, progress will be accumulated and ideas will be inspired.

Skim Reading

  • Abstract is a good way to get the general idea of what the paper is about.
  • Introduction is a good way to know the background of the proposed solution to a current problem.
  • Algorithm gives the analysis of the justification of the proposed theoretical idea and implementation shows the validation of the proposed idea.
  • Conclusion shows the merits and some drawbacks maybe for further research. 

Thorough Reading

  • Pay attention to the proposed approach.
  • Be aware of the limitation and challenges.
  • Examine the assumption, methods, statistics, reasoning and conclusion.
  • Take notes while reading and Highlight major points.
  • Think through the conclusion by yourself.

Another thing to bare in mind is that always examine the credibility of the paper before the thorough reading. Typical approach can be a look on the abstract, the conference and the bibliography.

I DO believe there is no shortcut when it comes to critical study. Absorb other's fruit before make a further step upon other's contribution.

Friday, May 17, 2013

Python - Part 2 Playing with Twitter API


Install Python if never installed before:
bowen@bowen:~$ sudo apt-get install python-pip python-dev build-essential

bowen@bowen:~$ sudo pip install python-twitter

Run Python
bowen@bowen:~$ python
>>> import twitter
>>> api = twitter.Api()
>>> api = twitter.Api(consumer_key='consumer_key',consumer_secret='consumer_secret', access_token_key='access_token', access_token_secret='access_token_secret')

#Replace all ' ' into your own key.

Some functionality that we can play with:
>>> users=api.GetFriends()
>>> print [u.name for u in users]

>>> statuses = api.GetUserTimeline()
>>> print [s.user.name for s in statuses]

>>> status = api.PostUpdate('Test Twitter message via Python')


And acquiring more information even without third party package:

import urllib
import simplejson

def searchTweets(query):
 search = urllib.urlopen("http://search.twitter.com/search.json?q="+query)
 dict = simplejson.loads(search.read())
 for result in dict["results"]: # result is a list of dictionaries
  print "*",result["text"],"\n"

# we will search tweets about "gator game" 
searchTweets("gator+game&rpp=50") # &rpp here is to offer arbitrary results that is more than 15.

Just list a few results here:
* RT @colebutler787: Great game tonight guys! @eLEMONator17 @BrandonMoz89 @JonathanW37 @JustenKinder @sirtwinksalots @khumphries734 @gator_dav15 @TheDaveMaster0

* RT @colebutler787: Great game tonight guys! @eLEMONator17 @BrandonMoz89 @JonathanW37 @JustenKinder @sirtwinksalots @khumphries734 @gator_dav15 @TheDaveMaster0

* @BrandtSnedeker at a Florida Gator football game, duh

* RT @colebutler787: Great game tonight guys! @eLEMONator17 @BrandonMoz89 @JonathanW37 @JustenKinder @sirtwinksalots @khumphries734 @gator_dav15 @TheDaveMaster0

* RT @colebutler787: Great game tonight guys! @eLEMONator17 @BrandonMoz89 @JonathanW37 @JustenKinder @sirtwinksalots @khumphries734 @gator_dav15 @TheDaveMaster0

* RT @colebutler787: Great game tonight guys! @eLEMONator17 @BrandonMoz89 @JonathanW37 @JustenKinder @sirtwinksalots @khumphries734 @gator_dav15 @TheDaveMaster0

* RT @CHCAWarriors: Awesome crowd at tonight's game.
 Final CHCA 6 St. Luke's 6
Good jobs guys, time to hit the weight room and get ready for the fall.

* Great game tonight guys! @eLEMONator17 @BrandonMoz89 @JonathanW37 @JustenKinder @sirtwinksalots @khumphries734 @gator_dav15 @TheDaveMaster0

* I liked a @YouTube video from @iheartmakeup92 http://t.co/Tflm5sFnt4 Get Ready With Me│GATOR GAME STYLE

* You can't have a conscience in the pimp game. #gator

* RT @Jhalapio33: Had a lot of tackles today with two assist tackles and 2 sacks ! Blessed with a good game !

* @0hMelissaRegan yay Zoey!!!!! Man I might have to go to a Gator game to see her cheer... Eeeeee.... We will have to make it the FSU/UF game

* If Gametracker is tracking the UGA-UF game in real time, then it took Gator reliever Parker Danciu 12 minutes to throw to one batter.

* I can't belive that was my last game as a gator, I'm going to miss it so much 😭

* RT @DoubleO_55: Pumped for the the blue and gold game.🏈 #blueteamswag @AlRoberts16 @J_Flinno @gator_68 @T_sully42 @JaredEidson6 @CadenRicketts


Thursday, May 16, 2013

Data Structure and Algorithm Study Notes 1

For object-oriented design approach, the three FUNDAMENTAL TO OO-DESIGN list below is important:
  • Abstraction
  • Encapsulation
  • Modularity
The main idea of abstraction is to distill a complicated system down to its most fundamental parts and describe these parts in a simple, precise language. (Example: "edit" menu in a text-editor GUI, copy or paste will not appear unless click the menu)
Encapsulation, or information hiding, states that different components of a software system should implement an abstraction, without revealing the internal details of that implementation. (Example: "edit" menu itself tells the functionality very well)
Modularity refers to an organizing structure, in which the different components of a software system are divided into separate functional units. (Example: organized architect designed house - electrical, heating and cooling, plumbing and structural [interact in well-defined ways: In doing so, he or she is using modularity to bring a clarity of thought that provides a natural way of organizing functions in to distinct manageable units]) 

Notation:
The "Big-Oh" Notation
f(n) is O(g(n)) if there is a real constant c>0 and an integer constant m>=1 such that f(n)<=cg(n) for every integer n>=m.
//NOTE: Usually, g(n) is the highest order of f(n).

The "Big-Omega" Notation
f(n) is Ω(g(n)) if there is a real constant c>0 and an integer constant m>=1 such that f(n)>=cg(n) for every integer n>=m.

The "Big-Theta" Notation
f(n) is Θ(g(n)) if f(n) is O(g(n)) and Ω(g(n)) at the same time.

Monday, May 13, 2013

Python - Part 1

Install Python and run the Python Shell.

The command line offers the functionality that you can directly input the arithmetic calculations and string inputs. For example, type "3<4" and get the "True" results.
Another example, type
>>> three = str('3')
The results will be '3' if you type three

There are also other special arithmetic calculations apart from normal add, subtract, multiplication, and division such as // (integer division), not (as opposed to), and (both statement has to be in order to get "True"), or (either one of the statement is true to make the result "True"), etc.

Now consider
>>> num = int(input('give me a number'))
if you input number like 500, the num can be compared as a number.
>>> num2 = 400
>>> num > num2
True


Friday, April 19, 2013

Give location information in Android Emulator

When we dealing with simulating the GPS or location-based service on emulator of Eclispes ADT bundle, the results are null generally, namely, we don't have the access of the longitude and latitude of the coordination. However, in this kind of scenarios, there are two commons ways to address this problem.


  1. open the command in Windows and make sure that you open the telnet services. For Windows 7 the telnet service is automatically closed unless we manually start it. (Please Google how to start telnet service if you have doubts) In the command line, type telnet localhost 5554. If your emulator is port 5556 or something else, type it accordingly. The port number will be shown in the title when you start the emulator. Then type geo fix 0 0. The two numbers here are the coordination (longitude and latitude respectively) of the location you desired.
  2. OR you can use the DDMS on the upper right corner of the Eclipse ADT. Then choose the device and type the coordinates and press send.
press the above icon on the top right of the Eclipse window and choose DDMS


Either way will do the trick.

p.s.
One more solution is to use this brilliant guy dpdearing's solution. An Android GPS Location Emulator

Sunday, April 14, 2013

How to get your own SHA1 fingerprint

When you first starts the Android development, you will need the SHA1 fingerprint. If this is your time you may find this a little bit hard to find out.

In the command terminal, first step is to locate the keytool.exe, which is the tool to obtain the SHA1.
Usually, the location of the file is located under JDK directory. In my case it locates at
C:\Program Files\Java\jdk1.7.0_11\jre\bin

After locating the directory, next step is to find the .android directory location which typically locates at the user directory under your name, for example, C:\Users\Bowen in my case.

Finally, type the following command to get the fingerprint:
keytool.exe -list -alias androiddebugkey -keystore "...\.android\debug.keystore" -storepass android -keypass android

The ... in the parentheses represents the directory location I mentioned above.
If you follow the above steps correctly, the system will display the Certificate fingerprint (SHA1).

Please leave a comment if you have any questions. Thx

Saturday, April 13, 2013

Java - Iteration and Arrays


"while" loops to check a number is prime or not.

public static boolean isPrime (int n) {
  int divisor =2;
  while (divisor < n) {
    if (n%divisor == 0) {
      return false;
    }
  return true;
}

"for" loops

for (initialize; test; next) {
  statement;
}
  Equivalent to: 
initialize;
while (test) {
  statement;
}
next;

ARRAYS
initialize a list of charactors:
char[] c = new char[4]; // reference to array of charactors of any length

For strings c.length() is a method
For characters c.length is a field.

Print the primes from 1 to n using Sieve of Eratosthenes:
public static void printPrimes(int n) {
boolean[] prime = new boolean[n+1];
        int i;

for (i=2; i<=n; i++){
prime[i]=true;
}
for(int divisor=2; divisor*divisor<=n; divisor++){
if(prime[divisor]){
for(i=2*divisor; i<=n; i=i+divisor){
prime[i]=false;
}
}
}
for(i=2; i<=n; i++){
if(prime[i]){
System.out.print(" "+i);
}
}
}
}

Friday, April 12, 2013

Java - Object & Methods

Object & Methods

String s1; //Step 1: declare a String variable.
s1 = new String(); //Step 2: assign it a value: a new empty string.

first line create a box, store references in strings.
second line construct a brand new string object.
= create a reference

A syntax sugar in Java:
String s2 = new String();

s1 = "Yow!"; also creates a constructor with Yow in the box.

now s1 forget the last one and remembers yow instead of the empty one.

s2 = s1; // reference to the same object;
s2 = new String (s1); //now 2 different, identical objects.

3 String constructors:

  1. new String() constructs empty string - contains no character. 
  2. "whatever"
  3. new String(s1) takes a parameter s1. Makes copy of object that s1 references.
Constructors always have the same name as their class, except "stuff in quotes".

s2 = s1.toUppercase();
String s3= s2.concat("!!"); // or just s2+"!!";
String s4 = "*".concat(s2).concat("*");//"*".concat(s2) compute first

In Java, String object are immutable unlike in C: their contents never change.


Java I/O Classes

Objects in System class for interacting with a user:
System.out is a PrintStream object that outputs to the screen.
System.in is an InputStream " " reads from the keyboard.
Actually, the two mentioned above should be variables that references to the object.

readLine method is defined on BufferedReader objects.

How do we construct a BufferedReader(compose into entire lines of text)? With an InputStream.Reader.
How .. an InputStreamReader(compose into characters typically 2 bytes)? We need an InputStream 
How .. an InputStream(read raw data)? System.in is one.
Figure this out from online Java libraries API. Specifically, java.io library here.

import java.io.*;//to use the java library, other than java.lang

class SimpleIO{
  public static void main(String[] arg) throws Exception{
    BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in));
    System.out.println(keybd.readLine());
  }

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

import java.net.*;
import java.io.*;

public class readURL {
public static void main(String[] arg) throws Exception{
URL u = new URL("http://www.bbc.co.uk");
InputStream s = u.openStream();
InputStreamReader inputrd = new InputStreamReader(s);
BufferedReader bbc = new BufferedReader(inputrd);
System.out.println(bbc.readLine());
}

}

Java – OOP intro


Some concepts in Object-Oriented Programming.
Object: Repository of data, such as milk or jam. 
Class: Type of object. 
Method: Procedure or Function that operates on an object (or class).
Inheritance: A class can inherit properties from a more general class. For instance, Shopping List inherits from List class the property of storing a sequence of items.
Polymorphism: One method call works on several classes, even if the classes need different implementation. e.g. “addItem” method on every kind of List, even though adding item to ShoppingList is different from ShoppingCart.
Polymorphism is the thing that distincts from other languages.
Object-oriented: Each object knows its own class&method. Each ShoppingList & ShoppingCart knows which addItem method it uses.


Code example:

String myString;
// mystring is a variable
myString = new String();
// new String() is called a constructor. It creates a string object,
// "=" causes myString to a reference the object

Differences between Java & Scheme:

  1. Everything in Java has a type; you must declare it.
  2. Scheme program (.sch) --> (eval) Answer. Java program (.java) --> (javac) .class Files --> (java) Answer