2014年12月29日 星期一

[CCDH] Exercise1 - Using HDFS

Preface 
Files used in this exercise: 
Data files (local)
~/training_materials/developer/data/shakesperare.tar.gz
~/training_materials/developer/data/access_log.gz

In this exercise you will begin to get acquainted with the Hadoop tools. You will manipulate files in HDFS, the Hadoop Distributed File System. 

Exercise 
Before starting the exercises, run the course setup script in a terminal window: 
$ ~/scripts/developer/training_setup_dev.sh

Hadoop 
Hadoop is already installed, configured, and running on your virtual machine. Most of your interaction with the system will be through a command-line wrapper called hadoop. If you run this program with no arguments, it prints a help message. To try this, run the below command in a terminal window: 
$ hadoop
Usage: hadoop [--config confdir] COMMAND
...

The hadoop command is subdivided into several subsystems. For example, there is a subsystem for working with files in HDFS and another for launching and managing MapReduce processing jobs. 

Step1: Exploring HDFS 
The subsystem associated with HDFS in the Hadoop wrapper program is called FsShell. This subsystem can be invoked with command hadoop fs
1. In the terminal window, enter 
$ hadoop fs
Usage: hadoop fs [generic options]
...

You see a help messge describing all the commands associated with the FsShell subsystem. 

2. Enter: 
$ hadoop fs -ls /

This shows you the contents of the root directory in HDFS. There will be multiple entries, one of which is /user. Individual users have a "home" directory under this directory, named after their username. 

Step2: Uploading Files 
Besides browsing the existing filesystem, another important thing you can do with FsShell is to upload new data into HDFS. 
1. Change directories to the local filesystem directory containing the sample data we will be using in the course. 
$ cd ~/training_materials/developer/data

If you perform a regular Linux ls command in this directory, you will see a few files, including two named shakespeare.tar.gz and shakespeare-stream.tar.gz. Both of those contain the complete works of Shakespeare in text format, but with different formats and organizations. For now, we will work with shakespeare.tar.gz

2. Unzip shakespeare.tar.gz by running 
$ tar xvf shakespeare.tar.gz

This creates a directory named shakespeare/ containing several files on your local filesystem. 

3. Insert this directory into HDFS: 
$ hadoop fs -put shakespeare shakespeare

This copies the local shakespeare directory and its contents into a remote HDFS directory named /user/training/shakespeare

4. List the contents of your HDFS home directory now: 
$ hadoop fs -ls

You should see an entry for the shakespeare directory. If you don't pass a directory name to the -ls command, it assumes you mean your home directory, i.e./user/training. Any relative path will based on your home directory too! 

5. We also have Web server log file, which we will put into HDFS for use in the future exercise: 
$ hadoop fs -mkdir weblog

The file is currently compressed using GZip. Rather than extract the file to the local disk and then upload it, we will extract and upload in one step. Now, extrack and upload the file in one step. The -c option to gunzip uncompresses to standard output, and the dash (-) in the below command takes whatever is being sent to its standard input and places that data in HDFS: 
$ gunzip -c access_log.gz | hadoop fs -put - weblog/access_log

6. Run the hadoop fs -ls command to verify that the log file is in your HDFS home directory 

7. The access log file is quite large - around 500 MB. Create a small version of this file, consisting only of its first 5000 lines, and store the smaller version in HDFS. You can use the smaller version for testing in subsequent exercises. 
$ hadoop fs -mkdir testlog
$ gunzip -c access_log.gz | head -n 5000 | hadoop fs -put - testlog/test_access_log

Step3: Viewing and Manipulating Files 
Now let's view some of the data you just copied into HDFS. 

1. Enter 
$ hadoop fs -ls shakespeare

This lists the contents of the /user/training/shakespeare HDFS directory. 

2. The glossary file included in the compressed file you began with is not strictly a work of Shakespere, let's remove it: 
$ hadoop fs -rm shakespeare/glossary

3. Enter: 
$ hadoop fs -cat shakespeare/histories | tail -n 50

This prints the last 50 lines of Henry IV, Part 1 to your terminal. This command is handy for viewing the output of MapReduce programs. Very often, an individual output file of a MapReduce program is very large, making it inconvenient to view the entire file in the terminal. 

4. To download a file to work with on the local filesystem use the fs -get command. This command takes two arguments: an HDFS path and a local path. It copies the HDFS contents into the local filesystem: 
$ hadoop fs -get shakespeare/poems ~/shakepoems.txt
$ less ~/shakepoems.txt

Other Commands 
Useful arguments for users of a hadoop cluster from hadoop command: 
archive: Creates a hadoop archive. More information can be found at Hadoop Archives.
distcp: Copy file or directories recursively. More information can be found at Hadoop DistCp Guide.
fs: Runs a generic filesystem user client. Deprecated, use hdfs dfs instead.
fsck: Runs a HDFS filesystem checking utility. See here for more info.
fetchdtGets Delegation Token from a NameNode. See here for more info.
jarRuns a jar file. Users can bundle their Map Reduce code in a jar file and execute it using this command.
job: Command to interact with Map Reduce Jobs.
pipes: Runs a pipes job.
queue: command to interact and view Job Queue information
version: Prints the version.
CLASSNAMEhadoop script can be used to invoke any class.
classpath: Prints the class path needed to get the Hadoop jar and the required libraries.

Commands useful for administrators of a hadoop cluster can refer here

Supplement 
Apache Hadoop 2.5.1 - Command Menu

2014年12月28日 星期日

[ RubyAlg ] MIT Linear Algebra, Spring 2005 - Lec10

Source From Here 
4 Fundamental Sub-Space: C(A), N(A), R(A)=C(A^T), N(A^T) 
這邊將介紹 4 個基礎的 Vector Sub-Space. 除了已經過的 Column Space 與 Null Space, 另外兩個如下: 
R(A) = C(A^T): Row sub-space 
N(A^T) = The left nullspace of A 

Let A be an mxn Matrix: 
 

For C(A)
dim(C(A)) = r (Rank)
basis = pivot column


For C(A^T)
dim(C(A^T)) = r (Rank) <-- and="" column="" dimension="" font="" has="" row="" same="" space="" the="">
basis =


For N(A)
basis = Special solution
dim(N(A)) = n - r


For N(A^T)
dim(N(A^T)) = m - r
basis =


 
首先來看 N(A^T), 也就是 Null Space of A^T
 

 
因為 EA=R, 接著來看一些運算: 
>> require "alg/math/LinearAlgebra"
>> LA = LinearAlgebra
>> A = LA.newMtx3(3,4,[1,2,3,1, 1,1,2,1, 1,2,3,1])
>> printf("A:\n%s\n", A) # 建立測試的 Matrix A
A:
1 2 3 1
1 1 2 1
1 2 3 1


>> E = A.E # EA=R
>> printf("E:\n%s\n", E)
E:
-1.0 2.0 0.0
1.0 -1.0 -0.0
-1.0 0.0 1.0


>> R = A.rref # Reduced Row Echelon Form 
>> printf("R:\n%s\n", R)
R:
1 0 1.0 1.0
0 1 1.0 -0.0
0 0 0.0 0.0

而 Matrix E 放在 Matrix A 的左邊說明對 row 進行操作, 舉 EA=R 的 row1 為例: 
 

由上面的結果可以知道 C(A^T) 的 rank=2 ( C(A) 的 rank 一樣). 接著考慮 EA=0 可知知道 [-1, 0, 1] 是 N(A^T) 的解 (A 的 -1*row0 加上 A 的 row2 得到 [0,0,0,0]

如果硬解的話, 可以參考下面運算過程: 
>> AT = A.t # 得到 A 的轉置矩陣
>> printf("A^T:\n%s\n", AT)
A^T:
1 1 1
2 1 2
3 2 3
1 1 1


>> RofAT = AT.rref
>> printf("A^T's rref:\n%s\n", RofAT)
A^T's rref:
1 0 1.0
0 1 -0.0
0 0 0.0
0 0 0.0

 

Connection between Row Space and Column Space 
Consider A as a matrix mxn
1. dim(C(A)) = dim(C(A^T)) = r 
2. dim(C(A)) = n - r
3. dim(C(A^T)) = m - r

[CCDH] Exercise15 - Creating an Inverted Index (P54)

Preface
Files and Directories Used in this Exercise
Eclipse project: inverted_index
Java files:
IndexMapper.java (Mapper)
IndexReducer.java (Reducer)
InvertedIndex.java (Driver)

Data files:
~/training_materials/developer/data/invertedIndexInput.tgz

Exercise directory: ~/workspace/inverted_index

In this exercise, you will write a MapReduce job that produces an inverted index.

For this lab you will use an alternative input, provided in the file invertedIndexInput.tgz. When decompressed, this archive contains a directory of files; each is a Shakespeare play formatted as follows:


Each line contains:
Line number
Separator: a tab character
value: The line of text

This format can be read directly using the KeyValueTextInputFormat class provided in the Hadoop API. This input format presents each line as one record to your Mapper, with the part before the tab character as the key, and the part after the tab as the value.

Given a body of text in this form, your indexer should produce an index of all the words in the text. For each word, the index should have a list of all the locations where the words appears. For example, for the word "honeysuckle" your output should look like this:
honeysuckle 2kinghenryiv@1038,midsummernightsdream@2175,...

The index should contain such an entry for every word in the text.

Lab Experiment
Prepare The Input Data
1. Extract the invertedIndexInput directory and upload to HDFS:
$ cd ~/training_materials/developer/data/
$ tar -xvf invertedIndexInput.tgz
$ hadoop fs -put invertedIndexInput invertedIndexInput

Define The MapReduce Solution
Remember that for this program you use a special input format to suit the form of your data, so your driver class will do for it:
2. Implement driver class:
  1. package solution;  
  2.   
  3. import org.apache.hadoop.fs.Path;  
  4. import org.apache.hadoop.io.Text;  
  5. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;  
  6. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;  
  7. import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;  
  8. import org.apache.hadoop.mapreduce.Job;  
  9.   
  10. import org.apache.hadoop.conf.Configured;  
  11. import org.apache.hadoop.conf.Configuration;  
  12. import org.apache.hadoop.util.Tool;  
  13. import org.apache.hadoop.util.ToolRunner;  
  14.   
  15. public class InvertedIndex extends Configured implements Tool {  
  16.   
  17.   public int run(String[] args) throws Exception {  
  18.   
  19.     if (args.length != 2) {  
  20.       System.out.printf("Usage: InvertedIndex \n");  
  21.       return -1;  
  22.     }  
  23.   
  24.     Job job = new Job(getConf());  
  25.     job.setJarByClass(InvertedIndex.class);  
  26.     job.setJobName("Inverted Index");  
  27.   
  28.     /* 
  29.      * We are using a KeyValueText file as the input file. 
  30.      * Therefore, we must call setInputFormatClass. 
  31.      * There is no need to call setOutputFormatClass, because the 
  32.      * application uses a text file for output. 
  33.      */  
  34.     job.setInputFormatClass(KeyValueTextInputFormat.class);  // Here setup our customized input format  
  35.   
  36.     FileInputFormat.setInputPaths(job, new Path(args[0]));  
  37.     FileOutputFormat.setOutputPath(job, new Path(args[1]));  
  38.   
  39.     job.setMapperClass(IndexMapper.class);  
  40.     job.setReducerClass(IndexReducer.class);  
  41.   
  42.     job.setOutputKeyClass(Text.class);  
  43.     job.setOutputValueClass(Text.class);  
  44.   
  45.     boolean success = job.waitForCompletion(true);  
  46.     return success ? 0 : 1;  
  47.   }  
  48.   
  49.   public static void main(String[] args) throws Exception {  
  50.     int exitCode = ToolRunner.run(new Configuration(), new InvertedIndex(), args);  
  51.     System.exit(exitCode);  
  52.   }  
  53. }  
Note that the exercise requires you to retrieve the file name - since that is the name of the play. The Context object can be used to retrieve the name of the file.
2. Implement the Mapper class
  1. package solution;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.apache.hadoop.fs.Path;  
  6. import org.apache.hadoop.io.Text;  
  7. import org.apache.hadoop.mapreduce.lib.input.FileSplit;  
  8. import org.apache.hadoop.mapreduce.Mapper;  
  9.   
  10. public class IndexMapper extends Mapper {  
  11.   
  12.   @Override  
  13.   public void map(Text key, Text value, Context context) throws IOException,  
  14.       InterruptedException {  
  15.   
  16.     /* 
  17.      * Get the FileSplit for the input file, which provides access 
  18.      * to the file's path. You need the file's path because it 
  19.      * contains the name of the play. 
  20.      */  
  21.     FileSplit fileSplit = (FileSplit) context.getInputSplit();  
  22.     Path path = fileSplit.getPath();  
  23.       
  24.     /* 
  25.      * Call the getName method on the Path object to retrieve the 
  26.       * file's name, which is the name of the play. Then append 
  27.      * "@" and the line number to the play's name. The resulting 
  28.      * string is the location of the words on that line. 
  29.      */  
  30.     String wordPlace = path.getName() + "@" + key.toString();  
  31.     Text location = new Text(wordPlace);  
  32.       
  33.     /* 
  34.      * Convert the line to lower case. 
  35.      */  
  36.     String lc_line = value.toString().toLowerCase();  
  37.       
  38.     /*  
  39.      * Split the line into words. For each word on the line, 
  40.      * emit an output record that has the word as the key and 
  41.      * the location of the word as the value.  
  42.      */  
  43.     for (String word : lc_line.split("\\W+")) {  
  44.       if (word.length() > 0) {  
  45.         context.write(new Text(word), location);  
  46.       }  
  47.     }  
  48.   }  
  49. }  
The Reducer will output inverted index information for key as word and value as exist location list:
3. Implement the Reducer class
  1. package solution;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.apache.hadoop.io.Text;  
  6.   
  7. import org.apache.hadoop.mapreduce.Reducer;  
  8.   
  9. /** 
  10. * On input, the reducer receives a word as the key and a set 
  11. * of locations in the form "play name@line number" for the values.  
  12. * The reducer builds a readable string in the valueList variable that 
  13. * contains an index of all the locations of the word.  
  14. */  
  15. public class IndexReducer extends Reducer {  
  16.   
  17.   private static final String SEP = ",";  
  18.   
  19.   @Override  
  20.   public void reduce(Text key, Iterable values, Context context)  
  21.       throws IOException, InterruptedException {  
  22.   
  23.     StringBuilder valueList = new StringBuilder();  
  24.     boolean firstValue = true;  
  25.   
  26.     /* 
  27.      * For each "play name@line number" in the input value set: 
  28.      */  
  29.     for (Text value : values) {  
  30.   
  31.       /* 
  32.        * If this is not the word's first location, add a comma to the 
  33.        * end of valueList. 
  34.        */  
  35.       if (!firstValue) {  
  36.         valueList.append(SEP);  
  37.       } else {  
  38.         firstValue = false;  
  39.       }  
  40.         
  41.       /* 
  42.        * Convert the location to a String and append it to valueList. 
  43.        */  
  44.       valueList.append(value.toString());   
  45.     }  
  46.   
  47.     /* 
  48.      * Emit the index entry.  
  49.      */  
  50.     context.write(key, new Text(valueList.toString()));  
  51.   }  
  52. }  
4. Build project and run MapReduce job
$ ant -f build.xml # Build project and output inverted_index.jar
$ hadoop fs -rm -r inverted_index # Clean previous result
$ hadoop jar inverted_index.jar solution.InvertedIndex invertedIndexInput inverted_index # Run MapReduce job
$ hadoop fs -ls inverted_index # Check result
...
... -rw-r--r-- 1 training supergroup 18446906 2014-12-28 21:24 inverted_index/part-r-00000

5. Check result
$ hadoop fs -cat inverted_index/part-r-00000 | less


[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...