<file_sep>package com.project.nra;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.project.nra.news_lib.model.News;

import java.io.InputStream;
import java.util.ArrayList;

/**
 * Created by hp.luong on 3/24/2017.
 */

public class NewsAdapter extends ArrayAdapter<News> {
    private ArrayList<News> newsList;

    public NewsAdapter(Context context, ArrayList<News> news) {
        super(context, 0, news);
        this.newsList = news;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        News news = newsList.get(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_listview, parent, false);
        }
        if (news != null) {
            TextView txtNews = (TextView) convertView.findViewById(R.id.txtNews);
            ImageView imageView = (ImageView) convertView.findViewById(R.id.iconImage);
            TextView txtScore = (TextView) convertView.findViewById(R.id.txtScore);
            if (txtNews != null) {
                txtNews.setText(news.getTitle());
//                new DownloadImageTask(imageView).execute(news.getUrlToImage());
                Bitmap bmpImage = BitmapFactory.decodeByteArray(news.getImage(), 0, news.getImage().length);
                imageView.setImageBitmap(bmpImage);
                txtScore.setText("1.0");
            }

        }
        return convertView;
    }
}

class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.d("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}
<file_sep>import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
import matplotlib.axes as ax



data = pd.read_csv("new_data3.csv")
data.shape


print (data.head())

#replace negative values
data['sum'][data['sum']<0] =  data['sum'][data['sum']<0]*(-1)
 
#print (data.head())

#for 2D, needs 2 data columns
X = data.iloc[:,2:4].values

#for 3D, needs 3 data columns
#X = data.iloc[:,1:4].values


print(X.shape)
X_1 = data[data.columns[2]]
X_2 = data[data.columns[3]]

print (X_1.min(), X_1.max())
print (X_2.min(), X_2.max())
k = 3
kmeans = KMeans(n_clusters=k)
kmeans.fit(X)

labels = kmeans.labels_
print("labels:", labels)
centroids = kmeans.cluster_centers_
print("centroids:", centroids)

for i in range(k):
    # select only data observations with cluster label == i
    ds = X[np.where(labels==i)]
	#
    # plot the data observations
    pyplot.plot(ds[:,0],ds[:,1],'o')
    # plot the centroids
    lines = pyplot.plot(centroids[i,0],centroids[i,1],'x')
    # make the centroid x's bigger
    # pyplot.setp(lines,ms=15.0)
    # pyplot.setp(lines,mew=2.0)
pyplot.xlim([X_1.min(),X_1.max()])
pyplot.ylim([X_2.min(),X_2.max()])

# fig = pyplot.figure()
# fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')

# ax = fig.add_subplot(111)
# fig.subplots_adjust(top=0.85)
# ax.set_title('axes title')

# ax.set_xlabel('xlabel')
# ax.set_ylabel('ylabel')
pyplot.xlabel('num_session')
pyplot.ylabel('total_time')

#pyplot.xrange.ticklabel_format(style='plain')
#ax.Axes.get_yaxis().get_major_formatter().set_useOffset(False)

pyplot.show()


# fig = plt.figure(1, figsize=(4, 3))
# ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
# kmeans.fit(X)
# labels = kmeans.labels_

# ax.scatter(X[:, 0], X[:, 1], X[:, 2],
		   # c=labels.astype(np.float), edgecolor='k')

		   		   
# ax.w_xaxis.set_ticklabels([])
# ax.w_yaxis.set_ticklabels([])
# ax.w_zaxis.set_ticklabels([])


# ax.set_xlabel('num_apps')
# ax.set_ylabel('num_session')
# ax.set_zlabel('total_time')
# ax.dist = 12
	
# plt.show()<file_sep>package com.example.testapp;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.enterprise.ApplicationPolicy;
import android.app.enterprise.EnterpriseDeviceManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Base64;
import android.util.Log;

public class EdmPolicyUtils {
    private static final String LOG_TAG = "EdmPolicyUtils";
    
    public static void startApplication(Context ctxt, String packageName) {
        PackageManager pm = ctxt.getPackageManager();
        Intent launch = pm.getLaunchIntentForPackage(packageName);
        if (launch == null) {
            Log.w(LOG_TAG, packageName + " is not installed");
        } else {
            launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ctxt.startActivity(launch);
        }
    }

    public static boolean stopApplication(Context ctxt, String packageName) {
        EnterpriseDeviceManager edm = (EnterpriseDeviceManager) ctxt
                .getSystemService(EnterpriseDeviceManager.ENTERPRISE_POLICY_SERVICE);
        ApplicationPolicy appPolicy = edm.getApplicationPolicy();
        return appPolicy.stopApp(packageName);
    }

    public static String SHA1(String text) 
			throws NoSuchAlgorithmException, UnsupportedEncodingException  { 
		MessageDigest md;
		md = MessageDigest.getInstance("SHA-1");
		byte[] sha1hash = new byte[40];
		md.update(text.getBytes("iso-8859-1"), 0, text.length());
		sha1hash = md.digest();
		String digestStr =Base64.encodeToString(sha1hash,0);
		return digestStr;
	} 

	public static boolean verifyDigest( String userKey, String inDigest ) throws Exception{
		boolean ret = false;
		if (userKey == null || inDigest == null ){
			return ret;
		}

		String outDigest = SHA1 (userKey);
		Log.d(LOG_TAG, "Digest: " + " inDigest: #" + inDigest + "# outDigest: #" + outDigest +"#");
		if (outDigest.equals(inDigest)){
			Log.d(LOG_TAG, " Digests are equal");
			ret = true;
		}else {
			Log.d(LOG_TAG," Digests are not equal");
		}
		return ret;
	}
}
<file_sep>import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA


#N = 500
N = 1000

X = np.loadtxt("data1.txt", dtype = (float, float), delimiter='\t', usecols=(4,5))
print (X.shape)
#print(X[:,0])
plt.hist(X[:,1])
#plt.show()

kmeans_model = KMeans(n_clusters=3, random_state=1)
kmeans_model.fit(X)

labels = kmeans_model.labels_
#print(labels)

pca_2 = PCA(2)
plot_columns = pca_2.fit_transform(X)
plt.scatter(x=plot_columns[:,0], y=plot_columns[:,1], c=labels)
plt.show()
<file_sep>package com.project.nra.news_lib.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by hp.luong on 7/7/2016.
 */
public class JsonUtils {
    public static String getJsonResult(String webURL) throws MalformedURLException {
        StringBuilder result = new StringBuilder();
        HttpURLConnection connection = null;
        URL url = new URL(webURL);

        try {
            connection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result.append(inputLine);
            }
            in.close();
        } catch (IOException e) {
            System.out.println("IOException: " + e.toString());
        } catch (Exception e) {
            System.out.println("Exception: " + e.toString());
        } finally {
            if (connection != null)
                connection.disconnect();
        }
    return result.toString();
    }
}
<file_sep>def twoSum(list_num, target):
    arr = {}
    for idx, item in enumerate(list_num):
        complement = target - item
        if (complement in arr):
            return 

<file_sep>def bubble_sort(array):
    for i in range(len(array) - 1, 0, -1):
        for j in range(0, i):
            if (array[j + 1] < array[j]):
               swap(array, j, j+1)
               print("swapped: i = %s j = %s" %(i,j),array)
    return array

def bubble_sort2(array):
    for i in range(0, len(array) - 1):
        for j in range(0, len(array) -1 - i):
            if (array[j + 1] < array[j]):
               swap(array, j, j+1)
               print("swapped: i = %s j = %s" %(i,j),array)
    return array

def swap(array, i, j):
    tmp = array[i]
    array[i] = array[j]
    array[j] = tmp

unsorted = [2,4,1,5,9,7,3]
print("Before: ", unsorted)
sorted = bubble_sort2(unsorted)
print("After: ", sorted)
<file_sep>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.pyplot as plt
#matplotlib inline

data_train = pd.read_csv('train.csv')
data_test = pd.read_csv('test.csv')

#print (data_train.describe())
#print (data_train[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False).mean())
#print(pd.crosstab(data_train['Pclass'], data_train['Survived']))

#print(data_test.describe())
#sns.barplot(x="Embarked", y="Survived", hue="Sex", data=data_train);
#plt.show();

print(data_train.head(5))
<file_sep>class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def addToFront(self, new_data):
        newNode = Node(new_data)
        newNode.next = self.head
        self.head = newNode

    def addToTail(self, new_data):
        newNode = Node(new_data)
        temp = self.head
        if (temp == None):
            self.head = newNode
        else:
            while (temp.next != None):
                temp = temp.next
            temp.next = newNode

    def deleteNode(self, node_data):
        found = False
        current = self.head
        if (current == None):
            return
        elif (current.data == node_data):
            if (current.next == None):
                self.head = None
            else:
                self.head = current.next
        else:
            while (current.next != None):
                prev = current
                current = current.next
                if (current.data == node_data):
                    prev.next = current.next
                    print ("Node found and deleted")
                    found = True
            if (not found):
                print("Node does not exist")

    def printList(self):
        temp = self.head
        while(temp):
            print (temp.data)
            temp = temp.next

#MAIN RUN
if __name__=='__main__':
    lst = LinkedList()
    lst.head = Node(1)
    second = Node(2)
    third = Node(3)
    lst.head.next = second
    second.next = third

    lst.printList()
    print("Add node 5 to the head of the list")
    lst.addToFront(5)
    lst.printList()

    print("Add node  to the end of the list")
    lst.addToTail(8)
    lst.printList()

    print("Delete node")
    lst.deleteNode(5)
    lst.deleteNode(8)
    lst.deleteNode(8)
    lst.printList()

<file_sep>def fibonacci(n):
    if n == 0: return 0
    if n == 1: return 1
    return fibonacci(n-1) + fibonacci(n-2)

ret = []
def fibonacci2(n):
	if n == 0: 
		ret.append(0)
		return ret
	if n == 1: 
		ret.append(1)
		return ret
	tmp = fibonacci2(n-1) + fibonacci2(n-2)
	ret.append(tmp)
	return ret
	
cache = []
def fibonacci_ds(n):
	if n == 0:	cache.insert(0,0)
	if n == 1:	cache.insert(1,1)
	if n > 1:	cache.insert(n,fibonacci_ds(n-1) + fibonacci_ds(n-2))
	return cache[n]
	
print (fibonacci(9))
#print (fibonacci_ds(9))
print(fibonacci2(3))<file_sep>include ':MainApp'
include ':LIBRARY:mylibrary1'
include ':LIBRARY:mylibrary2'<file_sep>package com.project.nra.news_lib.model;

import android.graphics.Bitmap;

import java.util.ArrayList;

public class News {
    private int id;
    private String source;
    private String author;
    private String title;
    private String description;
    private String url;
    private String urlToImage;
    private String publishedAt;
    private byte[] image;

    public News(int id, String source, String author, String title, String description, String url, String urlToImage, String publishedAt, byte[] image) {
        this.id = id;
        this.source = source;
        this.author = author;
        this.title = title;
        this.description = description;
        this.url = url;
        this.urlToImage = urlToImage;
        this.publishedAt = publishedAt;
        this.image = image;
    }

    public News() {
        this.id = 0;
        this.source = null;
        this.author = null;
        this.description = null;
        this.title = null;
        this.url = null;
        this.urlToImage = null;
        this.publishedAt = null;
    }
    @Override
    public String toString() {
        return getTitle();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }


    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrlToImage() {
        return urlToImage;
    }

    public void setUrlToImage(String urlToImage) {
        this.urlToImage = urlToImage;
    }

    public String getPublishedAt() {
        return publishedAt;
    }

    public void setPublishedAt(String publishedAt) {
        this.publishedAt = publishedAt;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }
}
<file_sep>package com.project.nra.news_lib.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.project.nra.news_lib.model.News;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hp.luong on 3/8/2017.
 */

public class DBHelper extends SQLiteOpenHelper {
    private static final String TAG = DBHelper.class.getSimpleName();

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "news.db";
    private static final String TABLE_NEWS = "news";

    private static final String COLUMN_NEWS_ID = "id";
    private static final String COLUMN_NEWS_SOURCE = "source";
    private static final String COLUMN_NEWS_AUTHOR = "author";
    private static final String COLUMN_NEWS_TITLE = "title";
    private static final String COLUMN_NEWS_DESC = "description";
    private static final String COLUMN_NEWS_URL = "url";
    private static final String COLUMN_NEWS_URLTOIMAGE = "url_to_image";
    private static final String COLUMN_NEWS_PUBLISHEDAT = "published_at";
    private static final String COLUMN_NEWS_IMAGE = "news_image";

    private static final int INDEX_COLUMN_NEWS_ID = 0;
    private static final int INDEX_COLUMN_NEWS_SOURCE = 1;
    private static final int INDEX_COLUMN_NEWS_AUTHOR = 2;
    private static final int INDEX_COLUMN_NEWS_TITLE = 3;
    private static final int INDEX_COLUMN_NEWS_DESC = 4;
    private static final int INDEX_COLUMN_NEWS_URL = 5;
    private static final int INDEX_COLUMN_NEWS_URLTOIMAGE = 6;
    private static final int INDEX_COLUMN_NEWS_PUBLISHEDAT = 7;
    private static final int INDEX_COLUMN_NEWS_IMAGE = 8;

    public static DBHelper dbHelper;
    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static synchronized DBHelper getInstance(Context context) {
        if (dbHelper == null) {
            dbHelper = new DBHelper(context);
        }
        return dbHelper;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG, "onCreate");
        String CREATE_NEWS_TABLE = "CREATE TABLE " + TABLE_NEWS + "("
                + COLUMN_NEWS_ID + " INTEGER PRIMARY KEY,"
                + COLUMN_NEWS_SOURCE + " TEXT,"
                + COLUMN_NEWS_AUTHOR + " TEXT,"
                + COLUMN_NEWS_TITLE + " TEXT,"
                + COLUMN_NEWS_DESC + " TEXT,"
                + COLUMN_NEWS_URL + " TEXT,"
                + COLUMN_NEWS_URLTOIMAGE + " TEXT,"
                + COLUMN_NEWS_PUBLISHEDAT + " TEXT,"
                + COLUMN_NEWS_IMAGE + " BLOB" + ");";
        db.execSQL(CREATE_NEWS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWS);

        // Create tables again
        onCreate(db);
    }

    public void addNews(News news) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_NEWS_ID, news.getId());
        values.put(COLUMN_NEWS_SOURCE, news.getSource());
        values.put(COLUMN_NEWS_AUTHOR, news.getAuthor());
        values.put(COLUMN_NEWS_TITLE, news.getTitle());
        values.put(COLUMN_NEWS_DESC, news.getDescription());
        values.put(COLUMN_NEWS_URL, news.getUrl());
        values.put(COLUMN_NEWS_URLTOIMAGE, news.getUrlToImage());
        values.put(COLUMN_NEWS_PUBLISHEDAT, news.getPublishedAt());
        values.put(COLUMN_NEWS_IMAGE, news.getImage());

        db.insert(TABLE_NEWS, null, values);
        db.close();
    }

    public boolean isNewsExisted(String url) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_NEWS, new String[] { COLUMN_NEWS_ID,
                        COLUMN_NEWS_SOURCE, COLUMN_NEWS_AUTHOR, COLUMN_NEWS_TITLE, COLUMN_NEWS_DESC, COLUMN_NEWS_URL,
                        COLUMN_NEWS_URLTOIMAGE, COLUMN_NEWS_PUBLISHEDAT, COLUMN_NEWS_IMAGE}, COLUMN_NEWS_URL + "=?",
                new String[] {url}, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            return true;
        }
        return false;
    }

    public News getNews(int newsId) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_NEWS, new String[] { COLUMN_NEWS_ID,
                        COLUMN_NEWS_SOURCE, COLUMN_NEWS_AUTHOR, COLUMN_NEWS_TITLE, COLUMN_NEWS_DESC, COLUMN_NEWS_URL,
                        COLUMN_NEWS_URLTOIMAGE, COLUMN_NEWS_PUBLISHEDAT, COLUMN_NEWS_IMAGE}, COLUMN_NEWS_ID + "=?",
                new String[] { String.valueOf(newsId) }, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            News news = new News(Integer.parseInt(cursor.getString(INDEX_COLUMN_NEWS_ID)),
                    cursor.getString(INDEX_COLUMN_NEWS_SOURCE), cursor.getString(INDEX_COLUMN_NEWS_AUTHOR), cursor.getString(INDEX_COLUMN_NEWS_TITLE), cursor.getString(INDEX_COLUMN_NEWS_DESC),
                    cursor.getString(INDEX_COLUMN_NEWS_URL), cursor.getString(INDEX_COLUMN_NEWS_URLTOIMAGE), cursor.getString(INDEX_COLUMN_NEWS_PUBLISHEDAT), cursor.getBlob(INDEX_COLUMN_NEWS_IMAGE));
            return news;
        }
        return null;
    }

    public List<News> getAllNews() {
        List<News> newsList = new ArrayList<News>();
        String selectQuery = "SELECT  * FROM " + TABLE_NEWS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                News news = new News();
                news.setId(Integer.parseInt(cursor.getString(INDEX_COLUMN_NEWS_ID)));
                news.setSource(cursor.getString(INDEX_COLUMN_NEWS_SOURCE));
                news.setAuthor(cursor.getString(INDEX_COLUMN_NEWS_AUTHOR));
                news.setTitle(cursor.getString(INDEX_COLUMN_NEWS_TITLE));
                news.setDescription(cursor.getString(INDEX_COLUMN_NEWS_DESC));
                news.setUrl(cursor.getString(INDEX_COLUMN_NEWS_URL));
                news.setUrlToImage(cursor.getString(INDEX_COLUMN_NEWS_URLTOIMAGE));
                news.setPublishedAt(cursor.getString(INDEX_COLUMN_NEWS_PUBLISHEDAT));
                news.setImage(cursor.getBlob(INDEX_COLUMN_NEWS_IMAGE));

                newsList.add(news);
            } while (cursor.moveToNext());
        }

        return newsList;
    }

    public ArrayList<String> getNewsTitleBySource(String source) {
        ArrayList<String> newsTitleList = new ArrayList<String>();
        List<News> newsList = getNewsBySource(source);
        if (newsList.size() > 0) {
            for (News news: newsList) {
                newsTitleList.add(news.getTitle());
            }
        }
        return newsTitleList;
    }

    public ArrayList<String> getNewsSources() {
        Log.d(TAG, "getNewsSources... news count = " + getNewsCount());
        ArrayList<String> newsSourceList = new ArrayList<String>();
        SQLiteDatabase db = this.getReadableDatabase();

        String countQuery = "SELECT DISTINCT source FROM " + TABLE_NEWS + ";";
        Cursor cursor = db.rawQuery(countQuery, null);

        if (cursor.moveToFirst()) {
            do {
                newsSourceList.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }
        Log.d(TAG, "newsSourceList = " + newsSourceList.size());
        return newsSourceList;
    }

    public List<News> getNewsBySource(String source) {
        List<News> newsList = new ArrayList<News>();
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.query(TABLE_NEWS, new String[] { COLUMN_NEWS_ID,
                        COLUMN_NEWS_SOURCE, COLUMN_NEWS_AUTHOR, COLUMN_NEWS_TITLE, COLUMN_NEWS_DESC, COLUMN_NEWS_URL,
                        COLUMN_NEWS_URLTOIMAGE, COLUMN_NEWS_PUBLISHEDAT, COLUMN_NEWS_IMAGE}, COLUMN_NEWS_SOURCE + "=?",
                new String[] {source}, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                News news = new News();
                news.setId(Integer.parseInt(cursor.getString(INDEX_COLUMN_NEWS_ID)));
                news.setSource(cursor.getString(INDEX_COLUMN_NEWS_SOURCE));
                news.setAuthor(cursor.getString(INDEX_COLUMN_NEWS_AUTHOR));
                news.setTitle(cursor.getString(INDEX_COLUMN_NEWS_TITLE));
                news.setDescription(cursor.getString(INDEX_COLUMN_NEWS_DESC));
                news.setUrl(cursor.getString(INDEX_COLUMN_NEWS_URL));
                news.setUrlToImage(cursor.getString(INDEX_COLUMN_NEWS_URLTOIMAGE));
                news.setPublishedAt(cursor.getString(INDEX_COLUMN_NEWS_PUBLISHEDAT));
                news.setImage(cursor.getBlob(INDEX_COLUMN_NEWS_IMAGE));
                newsList.add(news);
            } while (cursor.moveToNext());
        }

        return newsList;
    }

    public void removeNews(News news) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NEWS, COLUMN_NEWS_ID + " = ?",
                new String[] { String.valueOf(news.getId()) });
        db.close();
    }

    public int updateNews (News news) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_NEWS_ID, news.getId());
        values.put(COLUMN_NEWS_SOURCE, news.getSource());
        values.put(COLUMN_NEWS_AUTHOR, news.getAuthor());
        values.put(COLUMN_NEWS_TITLE, news.getTitle());
        values.put(COLUMN_NEWS_DESC, news.getDescription());
        values.put(COLUMN_NEWS_URL, news.getUrl());
        values.put(COLUMN_NEWS_URLTOIMAGE, news.getUrlToImage());
        values.put(COLUMN_NEWS_PUBLISHEDAT, news.getPublishedAt());
        values.put(COLUMN_NEWS_IMAGE, news.getImage());

        return db.update(TABLE_NEWS, values, COLUMN_NEWS_ID + " = ?",
                new String[] { String.valueOf(news.getId()) });
    }

    public int getNewsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_NEWS + ";";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int count = cursor.getCount();
        cursor.close();

        return count;
    }

    public long getDBSize() {
        SQLiteDatabase db = this.getReadableDatabase();
        return new File(db.getPath()).length();
    }
}
<file_sep>package com.project.nra.news_lib.model;

/**
 * Created by hp.luong on 7/7/2016.
 */
public class Constants {
    public static final String STATUS = "status";
    public static final String STATUS_OK = "ok";
    public static final String STATUS_ERROR = "error";
    public static final String SOURCES = "sources";
    public static final String SOURCE_ID = "id";
    public static final String ARTICLES = "articles";
    public static final String AUTHOR = "author";
    public static final String DESCRIPTION = "description";
    public static final String TITLE = "title";
    public static final String URL = "url";
    public static final String URL_IMAGE = "urlToImage";
    public static final String PUBLISHED_AT = "publishedAt";

    public static final String API_KEY = "de2f02ca31e54052bf41b1ae7daceafa";
    public static final String SOURCE_QUERY = "https://newsapi.org/v1/sources";
    public static final String PREFIX_SOURCE_QUERY ="https://newsapi.org/v1/articles?source=";

}
<file_sep>import numpy as np

data = np.loadtxt("data.txt", dtype = (int, int), delimiter='\t', usecols=(4,5))

print ("data = ", data)
<file_sep>from sys import argv
import numpy as np


def loadData(filename):
    #script, filename = argv 
    with open(filename) as f:
        lines = f.readlines()

    print lines

def loadDataset(training_data, test_data):
    training = np.loadtxt(training_data, dtype = 'str', delimiter = ', ', skiprows = 0)
    print training.shape
    print training.item((0, 1))
    print training.item((2, 14))
    for (row in training)
        print row[0]

def main():
    print "Hello"
    loadDataset('adult.data', 'adult.test')
    
main()

<file_sep>def quicksort(array):
    less = []
    equal = []
    greater = []
    if (len(array) > 1):
        pivot = array[0]
        for x in array:
            if (x < pivot):
                less.append(x)
            elif (x == pivot):
                equal.append(x)
            else:
                greater.append(x)
        return quicksort(less) + equal + quicksort(greater)
    else:
        return array

def main():
    input = [12,5,3,3,6,7,2,45,2]
    output = quicksort(input)
    print("Result: ", output)

if __name__ == "__main__":main()    
<file_sep>import numpy as np
import pandas as pd

data = pd.read_csv("train.csv")
#print(data.head())

test = pd.read_csv("test.csv")
#print(test.head().T)
null_columns=data.columns[data.isnull().any()]

import matplotlib.pyplot as plt
import seaborn as sns
sns.set(font_scale=1)

pd.options.display.mpl_style = 'default'
labels = []
values = []
for col in null_columns:
    labels.append(col)
    values.append(data[col].isnull().sum())
    ind = np.arange(len(labels))
    width=0.6
    fig, ax = plt.subplots(figsize=(6,5))
    rects = ax.barh(ind, np.array(values), color='purple')
    ax.set_yticks(ind+((width)/2.))
    ax.set_yticklabels(labels, rotation='horizontal')
    ax.set_xlabel("Count of missing values")
    ax.set_ylabel("Column Names")
    ax.set_title("Variables with missing values");
data.hist(bins=10,figsize=(9,7),grid=False);            
<file_sep>include ':NRA_APP'
include ':LIBRARY:NEWS_LIB'
<file_sep>import csv
with open('iris.data', 'rt') as csvfile:
	lines = csv.reader(csvfile)
	print (lines)
	for row in lines:
		print (row)
