廣告

2015年1月31日 星期六

[python] use python-weather-api sample | 如何使用 python-weather-api

API網址python-weather-api
=========================================


wget https://launchpad.net/python-weather-api/trunk/0.3.8/+download/pywapi-0.3.8.tar.gz
tar -zxvf pywapi-0.3.8.tar.gz
cd pywapi-0.3.8/
python setup.py build
python setup.py install
cd .. 


cdoe
import  pywapi
import string
# coding=UTF-8

locate = 'taiwan taipei'

locatMap = pywapi.get_location_ids(locate)

print locatMap.keys()
keylist = []
for key in locatMap.keys():
 keylist.append(key)

usekey =  keylist[0].decode('utf-8')

print "search result: "+ usekey+"\n"

weather_com_result = pywapi.get_weather_from_weather_com(usekey)

yahoo_result = pywapi.get_weather_from_yahoo(usekey)

print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in "+locate + ".\n"

print "Yahoo says: It is " + string.lower(yahoo_result['condition']['text']) + " and " + yahoo_result['condition']['temp'] + locate+".\n"



[python] BMI sample code

use BMI as sample.
this example will use:
math , class, flow control. def function, import src,




bmi.py
import bmiMethod


#read data from file
file = open('people.txt','r')
print 'the content is ',file.name

people = {}

for line in file.readlines():
   print 'read line:',line
   #rstrip = remove '\n'
   part = line.rstrip().split(' ')
   people[part[1]] = part

for key in people.keys():
        peolist = people.get(key)
        name    = peolist[1]
        height  = int(peolist[2])
        weight  = int(peolist[3])
        bmi = bmiMethod.getBmi(height,weight)
        print name,"'s bmi is ",bmi
        peolist.append(repr(bmi))
        people[key] = peolist
        print 'you are',bmiMethod.getRange(bmi)

f = open('people2.txt','w')
for key in people.keys():
 listp = people.get(key)
 str1 = ' '.join(listp)
 f.write(str1+"\n")

f.close()


bmiMethod.py

from __future__ import division

def getBmi(height , weight):
  print 'height = ',height, " weight = " ,weight
  hei2 = float(height/100)*float(height/100)
  bmi =float (weight/hei2)
  print 'bmi = ',bmi
  return bmi

def getRange(bmi):
  if bmi >= 24:
        return 'fat'
  elif bmi < 24 and bmi >= 19:
        return 'normal'
  else :
        return 'thin'


console
the content is  people.txt
read line: 1 lewis 183 70

read line: 2 leo 175 80

read line: 3 jim 170 60

read line: 4 7 170 80

read line: 5 fai 180 70

height =  183  weight =  70
bmi =  20.902385858
lewis 's bmi is  20.902385858
you are normal
height =  180  weight =  70
bmi =  21.6049382716
fai 's bmi is  21.6049382716
you are normal
height =  170  weight =  60
bmi =  20.7612456747
jim 's bmi is  20.7612456747
you are normal
height =  170  weight =  80
bmi =  27.6816608997
7 's bmi is  27.6816608997
you are fat
height =  175  weight =  80
bmi =  26.1224489796
leo 's bmi is  26.1224489796
you are fat
done


people.txt
1 lewis 183 70
2 leo 175 80
3 jim 170 60
4 7 170 80
5 fai 180 70



people2.txt
1 lewis 183 70 20.902385858042937
5 fai 180 70 21.604938271604937
3 jim 170 60 20.761245674740486
4 7 170 80 27.68166089965398
2 leo 175 80 26.122448979591837

2015年1月29日 星期四

[java] delete non-empty folder / (subfolders). | 刪除整個文件(包含裡面的文件)

以下提供兩種刪整個非空資料夾的方法,
但實際翻了一下
FileUtils.deleteDirectory(File folder);
的source code 後發現兩種是一樣的=.=...

另外:
FileUtils.waitFor(file, 5);
是個好用的東西,他實際上就是在時間內
一直呼叫file.exist(),並且程式會停在這邊,
直到時間到.
這樣就不用自己寫監控檔案下載完了沒XD

package test_fb_api;
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

//http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#deleteDirectory%28java.io.File%29

public class testDeleteNonEmptyFolder {

 public static int tag = 0;

 public static void main(String[] args) {

  String path = "F:/opt_test/";
  String path2 = "F:/opt_test2/";

  File file = new File(path);

  System.out.println(FileUtils.waitFor(file, 5));

  System.out.println("deleteMethodB:");
  System.out.println("exists before delete : " + file.exists());
  deleteMethodB(file);
  System.out.println("exists after  delete : " + file.exists());

  System.out.println("===========================");
  System.out.println("deleteMethodA:");
  File file2 = new File(path2);
  // set tag = 0 , because "deleteMethodA" is recursive.
  // so you don't know where go false, or is still folder
  tag = 0;
  System.out.println("exists before delete : " + file2.exists());
  deleteMethodA(file2);
  if (tag == 0) {
   System.out.println("deleteMethodA: delete success");
  } else {
   System.out.println("deleteMethodA: have subFolder: " + tag);
  }
  System.out.println("exists after  delete : " + file2.exists());
 }

 public static void deleteMethodB(File folder) {
  try {
   FileUtils.deleteDirectory(folder);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   System.out.println(e.getMessage());
  }
 }

 public static void deleteMethodA(File folder) {
  // check if folder file is a real folder
  if (folder.isDirectory()) {
   File[] list = folder.listFiles();
   if (list != null) {
    for (int i = 0; i < list.length; i++) {
     File tmpF = list[i];
     if (tmpF.isDirectory()) {
      deleteMethodA(tmpF);
     }
     if (!tmpF.delete()) {
      tag++;
     }
    }
   }
   if (!folder.delete()) {
    System.out.println("can't delete folder : " + folder);
   }
  }
 }

}



2015年1月27日 星期二

[java] better way to remove object in arraylist, 從arraylist 拿掉不需要的

如果想在一個迴圈裡面拿掉不須要的item,有兩個可以呼叫,
1.remove(int index)
2.remove(object o)


package test_fb_api;

import java.util.ArrayList;
import java.util.HashMap;



public class testArrayListRemove {

	public static void main(String[] args) {
		
		ArrayList bookShelfData_ReName = new ArrayList();
		bookShelfData_ReName.add("1");
		bookShelfData_ReName.add("2");
		bookShelfData_ReName.add("3");
		bookShelfData_ReName.add("5");
		bookShelfData_ReName.add("2");
		
		System.out.println("remove(int index)");
		for(int i = 0 ; i< bookShelfData_ReName.size() ; i++)
		{	
			System.out.println("===============");
			System.out.println("before:"+bookShelfData_ReName);
			if(bookShelfData_ReName.get(i).equals("2"))
			{
				bookShelfData_ReName.remove(i);
			}
			System.out.println("after:"+bookShelfData_ReName);
			
		}
		System.out.println("****************************");
		
		ArrayList bookShelfData_ReName2 = new ArrayList();
		bookShelfData_ReName2.add("1");
		bookShelfData_ReName2.add("2");
		bookShelfData_ReName2.add("3");
		bookShelfData_ReName2.add("5");
		bookShelfData_ReName2.add("2");
		
		System.out.println("remove(object)");
		System.out.println("===============");
		ArrayList forRemove = new ArrayList();
		for(int i = 0 ; i< bookShelfData_ReName.size() ; i++)
		{	
			if(bookShelfData_ReName.get(i).equals("2"))
			{
				forRemove.add(bookShelfData_ReName.get(i));
			}
			
		}
		for(int i = 0 ; i< forRemove.size() ; i++)
		{
			bookShelfData_ReName.remove(forRemove.get(i));
		}
		System.out.println("after:"+bookShelfData_ReName);
		
		//still O(n)
	}

}



結果:


[java] save || download file , then delete file , cannot be deleted sometimes

http://stackoverflow.com/questions/991489/i-cant-delete-a-file-in-java

2015年1月19日 星期一

[python] 基本語法&用法


variable assign

#one lin comment

"""
multi line comment

"""

#variable assign
x = 1
print x

x += 1

print x

x,y = 1,2
print x,y

x = 1.999
print x

string = "this is stirng"
print string







list:


mlist = [12,45,1]

mlist.append(3)

print mlist

mlist.append(1)

print mlist

print mlist.count(1),mlist.index(1)
print mlist

print mlist.reverse()
mlist.remove(1)

print mlist
print mlist.pop(2)

mlist.append(11);












dictionary
#dictionary

info = {'name': 'lewis'}

print info

info['title']= 'member'
info['age']= '23'
info['locate']= 'taipei'

print info

print info.keys()

print info.get('name')

del info['locate']
print info


#set

channel = set()
channel.add('ylib')
channel.add('zinio')
channel.add('ibobar')

tChannel = {'ibobar','ylib'}

print channel & tChannel
print channel | tChannel
print channel ^ tChannel
print channel - tChannel
print channel - tChannel
print channel | tChannel














String
#String

x = 'i\'m lewis'
print x
y = ',hi1234'
z=x+y
print z

print z[-3]
print z[3:-2]
print z[3:1]

print len(z)

ss='123'

for s in ss:
 print (s , ':')

print z*2

print y in z

#type convertion


i = 10
d = 1.5
f = 3.5
s = "string"
c = 'c'

print int(i+d)
print float(10/2.6)
print i%d
print ord(c)+10
print chr(ord(c)+i)

2015年1月17日 星期六

[python] 快速入門

直接放這張強大的說明圖:




coffeeghost-q-in-py.png


120417-coffeeghost-q-in-py.png




ref: http://tech.marsw.tw/blog/2014/09/03/getting-started-with-python-in-ten-minute

[python]ubuntu下的python相關配置& hellow world

環境:ubuntu14.04.1

此版本已經內建pyhon 2.7.6.
所以本篇大概相關環境設定.

由於android 與java 算是寫了一段時間,所以沒有很仔細地從頭
介紹,所以想說python就記錄的仔細一點好了XD.

1.安裝git (因為方便同步code )

$ sudo apt-get install git
   
2.直接看code最快  (網路上的範例 )

$ git clone https://github.com/cihm/PyConTW2013Tutorial.git

3.安裝編輯器(看個人喜好 )
$ wget http://c758482.r82.cf2.rackcdn.com/Sublime%20Text%202.0.2.tar.bz2
//下載
$ tar -xf "Sublime Text 2.0.2.tar.bz2"
//解壓縮
$ sudo mv "Sublime Text 2" /usr/lib
//移到目錄
$ sudo ln -s "/usr/lib/Sublime Text 2/sublime_text" /usr/bin/st2
//連結到目錄

4.在 Python 標準程式庫中有個 distutils,是用來建立與安裝額外模組,適用於簡易的安裝場合,有些程式庫擴充了 distutils,像是 Setuptools,可以使用以下的指令建立、進入 scripts 資料夾,然後下載、安裝 Setuptools:
$ mkdir scripts
$ cd scripts
$ wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python
$ sudo easy_install pip
$ sudo pip install virtualenv

ps:安裝套件時,建議可以使用 pip,如果發現有 pip 無法安裝的套件,可以嘗試使用 easy_install,如果這兩個選項都無法安裝,則可以嘗試尋找是否有 setup.py 進行安裝

5.使用 Virtualenv
Python 的套件不少都會直接安裝到 Python 預設的一些系統路徑中,Pip 的 pip-1.4.1-py2.7.egg 就安裝到 /usr/local/lib/python2.7/dist-packages 之中,如果不想都安裝到系統路徑中,或者不具備系統管理者權限而無法安裝到系統路徑,會希望有個虛擬環境可以使用,安裝 Pip 之後,通常會建議安裝 Virtualenv 做為搭配
$ virtualenv --distribute venv
$ cd venv
$ source bin/activate
$ vim hello.py
    hello.py內容為:
    print 'hellow world'


離開 虛擬環境為
deactivate


6.安裝Virtualenvwrapper
是一個 Virtualenv 的 extension,可使虛擬環境的管理變得更容易。
詳細來說,Virtualenvwrapper 提供下述功能:
1.將所有的虛擬環境整合在一個目錄下。
2.管理(新增、移除、複製)所有的虛擬環境。
3.可以使用一個命令切換虛擬環境。
4.Tab 補全虛擬環境的名字。
5.每個操作都提供允許使用者自訂的 hooks。
6.可撰寫容易分享的 extension plugin 系統。

$ easy_install virtualenvwrapper
$ mkdir $HOME/.virtualenvs (之後的虛擬機目錄會放到這)
$ export WORKON_HOME=$HOME/.virtualenvs
$ source /usr/local/bin/virtualenvwrapper.sh (每次用之 前要先執行這行)
$ source ~/.bashrc                    (每次用之 前要先執行這行)

用法:
創建虛擬環境:mkvirtualenv [ENVNAME]
列出所有的虛擬環境:lsvirtualenv
移除虛擬環境:rmvirtualenv ENVNAME
複製虛擬環境:cpvirtualenv ENVNAME TARGETENVNAME
啟動虛擬環境:workon [environment_name]
離開虛擬環境:deactivate
官方文件




ref:http://www.codedata.com.tw/python/python-tutorial-the-1st-class-4-unicode-support-basic-input-output/

ref:http://www.openfoundry.org/tw/tech-column/8516-pythons-virtual-environment-and-multi-version-programming-tools-virtualenv-and-pythonbrew


Virtualenvwrapperref:http://blog.csdn.net/jazywoo123/article/details/37564957


2015年1月16日 星期五

[ubuntu ] putty(on window) connect to VM(ubuntu )

[ubuntu]

 1. 先在ubuntu上安裝 openssh,
     指令:apt-get install ssh openssh-server 

 2. 查IP (vm網路要設為NAT,Bridged我沒設過XD)
     指令:ifcongig

















[window] putty設定如下:



2015年1月13日 星期二

[Java]convert data type X into type Y in Java

package test;

public class testDataConversion {

 public static void main(String[] args) {

  //integer to String
  int i = 11; 
  String stri = Integer.toString(i);
  
  //String to integer 
  stri = "25";
  i = Integer.parseInt(stri);
  i = Integer.parseInt(stri);
  
  
  //double to String 
  double d = 1.0;
  String strd = Double.toString(d);
  
  //String to double
  d = Double.valueOf(strd).doubleValue();
  d = Double.parseDouble(strd);
  
  
  //float to String
  float f = 111;
  String strf = Float.toString(f);
  
  //String to float
  f = Float.valueOf(strf).floatValue();
  f = Float.parseFloat(strf);
  
  
  //long to String
  long l =111111;
  String strl = Long.toString(l);
  //String to long
  l = Long.valueOf(strl).longValue();
  l = Long.parseLong(strl);
  
  
  //decimal to binary
  int decimal = 11;
  String binstr = Integer.toBinaryString(decimal);
  
  //decimal to hexadecimal
  decimal = 1111;
  String hexstr = Integer.toString(decimal, 16);
  String hexstr2 = Integer.toHexString(decimal);
  
  //hexadecimal (String) to integer
  decimal  = Integer.valueOf("B8DA34", 16).intValue();
  decimal  = Integer.parseInt("B8DA34", 16);
  
  
  //ASCII code to String
  int ASCII = 64;  
  String aChar = new Character((char)ASCII).toString();
  
  //integer to ASCII code (byte):
  char c = 'A';  
  ASCII = (int) c; 
  
 }

}


2015年1月5日 星期一

[Java] 相對路徑,絕對路徑

public class testPath {

 public static void main(String[] args) {

  System.out.println(System.getProperty("java.class.path"));//Java 類別路徑
  
  
  System.out.println(System.getProperty("user.dir"));//用戶的當前工作目錄
  //System.getProperty("user.dir") + "/filename" ,較安全的相對路徑
  
  String basePathR = new File("").getPath();
  System.out.println("getPath:"+basePathR);
  
  String basePathA = new File("").getAbsolutePath();
  System.out.println("getAbsolutePath:"+basePathA);

  try {
   String basePathC = new File("").getCanonicalPath();
   System.out.println("getCanonicalPath:"+basePathC);
   
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  System.out.println("=releative path=============");
  
  FileWriter writer = null;
  try {
   File file = new File("releative.txt");
   writer = new FileWriter(file);
   writer.write("test re");
   displayPath(file);
  } catch (IOException e) {
   System.out.println("releative:" + e.getMessage());
  } finally {
   try {
    if (writer != null)
     writer.close();
   } catch (IOException e) {
   }
  }

  System.out.println("=absolute path=============");
  
  try {
   File file = new File("/candelete/absolute.txt");
   
   writer = new FileWriter(file);
   writer.write("test ab");
   displayPath(file);
  } catch (IOException e) {
   System.out.println("absolute:" + e.getMessage());
  } finally {
   try {
    if (writer != null)
     writer.close();
   } catch (IOException e) {
   }
  }

 }

 public static void displayPath(File testFile) {

  System.out.println("path : " + testFile.getPath());

  System.out.println("absolute path : " + testFile.getAbsolutePath());

  try {

   System.out.println("canonical path : "
     + testFile.getCanonicalPath());

  } catch (Exception e) {

   e.printStackTrace();

  }

 }

}


輸出結果:
C:\Users\Melody\workspace_web\testJava\bin
C:\Users\Melody\workspace_web\testJava
getPath:
getAbsolutePath:C:\Users\Melody\workspace_web\testJava
getCanonicalPath:C:\Users\Melody\workspace_web\testJava
=releative path=============
path : releative.txt
absolute path : C:\Users\Melody\workspace_web\testJava\releative.txt
canonical path : C:\Users\Melody\workspace_web\testJava\releative.txt
=absolute path=============
path : \candelete\absolute.txt
absolute path : C:\candelete\absolute.txt
canonical path : C:\candelete\absolute.txt