3/07/2014

Python Study, os.path functions

__author__ = 'mare'


from os.path import *


print( abspath('tmp') )
#/Users/mare/PycharmProjects/OS_system/tmp

print( basename('C:/Python32/tmp') )
print( basename('C:/Python32/tmp/test.txt') )
#tmp
#test.txt

print( commonprefix(['c:/python32/lib', 'c:/python32/Tools', 'c:/python32']))
#c:/python32
print( commonprefix(['c:/python26/lib', 'c:/python25/Tools']))
#c:/python2

print( dirname('C:/Python32/tmp'))
print( dirname('C:/Python32/tmp/test.txt'))
#C:/Python32
#C:/Python32/tmp

print( exists('/Users/mare/PycharmProjects/OS_system/'))
print( exists('/Users/mare/'))
print( exists('/Users/mare/AAAA/'))
#True
#True
#False

print( expanduser('~/test'))
#/Users/mare/test
print( expanduser('~someone/test'))
#~someone/test

print( expandvars('$HOME/temp'))
#/Users/mare/temp
print( expandvars('$SYSTEMROOT/var'))
#$SYSTEMROOT/var -> mac is not supported


print(getatime('/Users/mare'))
#1394212008.0 -> latest time to access the path

print(getmtime('/Users/mare'))
#1389968107.0 -> latest time to modify the path

print(getctime('/Users/mare'))
#1389968107.0 -> latest time to create the folder

print( isabs('/Users/mare') ) #absolute path is true another is false
#True
print( isabs('../mare') )
#False

print( isfile('/Users/mare/PycharmProjects/OS_system/main.fy'))
print( isfile('/Users/mare/PycharmProjects/OS_system/main.py'))
#False
#True

print( isdir('/Users/mare/PycharmProjects/OS_system/main.py') )
print( isdir('/Users/mare/PycharmProjects/OS_system/'))
#False
#True


print( join('/python32', 'Script', 'test.py'))
#/python32/Script/test.py

print( split('/python32/Script/test.py'))
#('/python32/Script', 'test.py')

print( splitext('/python32/Script/test.py') )
#('/python32/Script/test', '.py')


import glob

print( glob.glob('*'))
#['main.py']









3/06/2014

(C, C++) int to char *, char * to int, _itoa_s and atoi functions

char *s="100";
int a = atoi(s);
printf("%d\n", a);

char s2[30];
a=211;
_itoa_s(a, s2, 10); //in here, 10 is Decimal, 2 is Binary.
printf("%s\n", s2);

(C, C++) converting char * to float , strtod and atof functions

#include < stdlib.h>
#include < stdio.h>

void main()
{
  char *floatText = "34.12";
  double Afloat = strtod(floatText ,NULL);
  float Bfloat = atof(floatText );
  printf("%f, %f",Afloat ,Bfloat );

}



/* Output */
34.120000, 34.120000

(C, C++) char * compare, strcmp function


#include < stdio.h>
#include < string.h>

int main ()
{
  char szKey[] = "apple";
  if( strcmp (szKey,"apple") == 0)
       printf("same\n");
  else
       printf("different\n");

  
  return 0;
}


(c, c++) 'char * to string' and 'string to char *'

//string to char*

string str = "hello";
char cstr[10];
strcpy(cstr,str.c_str());
 
// char * to string

char cstr[] = "hello";
string str = cstr; //string(cstr)

3/05/2014

(C, C++) TinyXML , xml read & write

Firstly, download TinyXML source code on here -> http://sourceforge.net/projects/tinyxml/

After unzip, you can see many files and folders like that.

But, we only need 6 files.  
Copy these files to appropriate folder.

Make your project and add 6 files in your project.


This is example of xml file. Save file name to "ex4.xml"

---
< ? xml version="1.0" ?>
< LibraryIndex>
    < !-- Settings for MyApp -->
    < Messages>
        < Welcome>Welcome to MyApp< /Welcome>
        < Farewell>Thank you for using MyApp< /Farewell>
    < /Messages>
    < Windows>
        < Window name="MainFrame" x="5" y="15" w="400" h="250" />
    < /Windows>
    < Connection ip="192.168.0.1" timeout="123.456000" />
< /LibraryIndex>

----

Make code like this and run.
In my case, 6 TinyXML files are located "./tinyXML/"

---
#include < stdio.h>
#include "./tinyXML/tinyxml.h"


void main()
{
 TiXmlDocument doc;
 bool loadOkay = doc.LoadFile("ex4.xml");

 if (loadOkay)
 {
  printf("open success\n");
 }
 else
 {
  printf("Failed to load file \n");
 } 
}
---

If you see the "open success" massage, xml file is opened nomally.


-----------------------------
XML read & parsing example source code.
---
#include < stdio.h>
#include "./tinyXML/tinyxml.h"


void main()
{
 TiXmlDocument doc;
 bool loadOkay = doc.LoadFile("ex4.xml");

 if (loadOkay)
 {
  printf("open success\n");
 }
 else
 {
  printf("Failed to load file \n");
 } 


 //root node access
 TiXmlElement* pRoot = doc.FirstChildElement("LibraryIndex"); 
 if (!pRoot) return;

 //access "welcom" element to get value
 TiXmlElement* pElem = pRoot->FirstChildElement("Messages")->FirstChildElement("Welcome");
 if (!pElem) return;

 //get element value (Welcome).
 char* pszNode = (char*)pElem->Value();
 if (pszNode)
  printf("Node: %s\n", pszNode);

 //get element text(Welcome to MyApp)
 char* pszText = (char*)pElem->GetText();
 if (pszText)
  printf("Text: %s\n", pszText);


}

---
The result is like that.

--------------------------
modify example.
***
#include < stdio.h>
#include "./tinyXML/tinyxml.h"


void main()
{
 TiXmlDocument doc;
 bool loadOkay = doc.LoadFile("ex4.xml");

 if (loadOkay)
 {
  printf("open success\n");
 }
 else
 {
  printf("Failed to load file \n");
 } 

 // access root node
 TiXmlElement* pRoot = doc.FirstChildElement("LibraryIndex");   
 if (!pRoot) return;  

 // access welcome element to modify value  
 TiXmlElement* pElem = pRoot->FirstChildElement("Messages")->FirstChildElement("Welcome");  
 if (!pElem) return;

 // element clear and new value adding 
 pElem->Clear();
 pElem->LinkEndChild( new TiXmlText("Edit My App"));

 doc.SaveFile("m_ex4.xml");
}
***
The result is like the figure.


-------------
Example source code to make New xml file.
In the source code, new and delete pair is do not need because created variable by new keyword will be delete automatically after block.
***
#include < stdio.h>
#include "./tinyXML/tinyxml.h"


void main()
{
 
 // Declaration XML format
 TiXmlDocument doc;
 TiXmlDeclaration* pDecl = new TiXmlDeclaration("1.0", "euc-kr", "");  
 doc.LinkEndChild(pDecl);

 //Add Root node
 TiXmlElement* pRoot = new TiXmlElement("LibraryIndex2");
 doc.LinkEndChild(pRoot);

 // Add Comment sentence
 TiXmlComment * pComment = new TiXmlComment();
 pComment->SetValue("Settings for MyApp");
 pRoot->LinkEndChild(pComment);

 // Add child node and data
 TiXmlElement* pElem = new TiXmlElement("Messages");
 pRoot->LinkEndChild(pElem);

 TiXmlElement* pSubElem = new TiXmlElement("Welcome");
 pSubElem->LinkEndChild( new TiXmlText("Welcome to MyApp"));
 pElem->LinkEndChild(pSubElem);

 pSubElem = new TiXmlElement("Farewell");
 pSubElem->LinkEndChild( new TiXmlText("Thank you for using MyApp"));
 pElem->LinkEndChild(pSubElem);

 // Add child node and set attribute 
 pElem = new TiXmlElement("Windows");
 pRoot->LinkEndChild(pElem);

 pSubElem = new TiXmlElement("Window");
 pElem->LinkEndChild(pSubElem);
 pSubElem->SetAttribute("name", "MainFrame");
 pSubElem->SetAttribute("x", 5);
 pSubElem->SetAttribute("y", 15);
 pSubElem->SetAttribute("w", 400);
 pSubElem->SetAttribute("h", 250);

 pElem = new TiXmlElement("Connection");
 pRoot->LinkEndChild(pElem);
 pElem->SetAttribute("ip", "192.168.0.1");
 pElem->SetDoubleAttribute("timeout", 123.456);

 //Save xml file format
 doc.SaveFile("new_ex4.xml");

}
***
The result is like the figure.

-------
Finally, This source code is searching all node and text by using recursive routine.

#include < stdio.h>
#include "./tinyXML/tinyxml.h"

void searchXMLData(TiXmlElement* pElem)
{
 TiXmlHandle hRoot(0);
 TiXmlElement* pSubElem = pElem;
 TiXmlAttribute* pAttrib = NULL;

 
 //Set current node to root node and determine childe node is exist or not
 hRoot = TiXmlHandle(pSubElem);
 pSubElem = hRoot.FirstChildElement().Element();
 if (!pSubElem) return;

 char* pszNode = NULL;
 char* pszAttrib = NULL;
 char* pszText = NULL;

 while (pSubElem)
 {
  //node
  pszNode = (char*)pSubElem->Value();
  if (pszNode)
   printf("Node: %s\n", pszNode);

  //Attribute
  pAttrib = pSubElem->FirstAttribute();
  while (pAttrib)
  {
   char* pszAttrib = (char*)pAttrib->Name();
   char* pszText = (char*)pAttrib->Value();

   printf("------------Attribute: %s, Data: %s\n", pszAttrib, pszText);

   pAttrib = pAttrib->Next();
  }
  
  //Data
  pszText = (char*)pSubElem->GetText();
  if (pszText)
   printf("Text: %s\n", pszText);

  // Recursive call for searching child node based current node
  searchXMLData(pSubElem);
  pSubElem = pSubElem->NextSiblingElement();
 }
}

int main()
{
 TiXmlDocument doc;
 doc.LoadFile("ex4.xml");
 TiXmlHandle hDoc(&doc);

 //access root node
 TiXmlElement* pRoot = hDoc.FirstChildElement().Element();
 if (!pRoot) return 0;

 
 //search childe node step by step from starting root node
 searchXMLData(pRoot);
 
 return 0;
}

The result is like the figure.


Thank you.
Good luck!.

3/04/2014

(OpenCV Study) xml write & read, example source code.

This is very simple example source code for write and read xml file.
OpenCV version will be no matter.
I hope helpful to you.
Thank you.



//Write example
FileStorage xmlW("A.xml", FileStorage::WRITE);
Mat A(3,3, CV_32F);
setIdentity(A);
xmlW << "A" << A;
xmlW.release();

//read example
FileStorage xmlR;
xmlR.open("A.xml", FileStorage::READ);
Mat B;
xmlR["A"] >> B;
cout << B << endl;
xmlR.release();

3/03/2014

python study, math modules, example source code

__author__ = 'mare'


l = list( range(0, 10) )
print( sum(l) )
print( sum(l, 100) )
print( max(l) )
print( min(l) )
print( abs(-11) )
#45
#145
#9
#0
#11

print( "-----" )
print( pow(2, 10) ) #2^10
print( pow(2, 10, 100) )  #(2^10)%10
print( divmod(10, 7) )
print( divmod(5.3, 2.1) )
#1024
#24
#(1, 3)
#(2.0, 1.0999999999999996)

print( round(152.394) )
print( round(152.394, 1) )
print( round(152.394, -1) )
#152
#152.4
#150.0

import math
print( math.ceil(3.14 ) )
print( math.floor(3.14) )
print( math.trunc(3.14) )
#4
#3
#3

print("---")
print( math.copysign(6.5, -0.0) )
print( math.fabs(-6.5) )
print( math.factorial(3.0) )
print( math.modf(-6.5) )
l = [3.14, 1.24, 5.23]
print( math.fsum(l) )
#-6.5
#6.5
#6
#(-0.5, -6.0)
#9.610000000000001


print("---")
print( math.fmod(5.5, 3) )
print( 5.5%3 )
print( math.fmod(-5.5, 3) )
print( -5.5 % 3 )
#2.5
#2.5
#-2.5
#0.5

print( math.pow(2, 10) )
print( math.pow(1.5, 3) )
print( math.sqrt(2) ) #sqrt(2)
print( math.exp(2) ) #e^2
print( math.log(math.e) ) #ln(e)
#1024.0
#3.375
#1.4142135623730951
#7.38905609893065
#1.0

print("---")
r = math.radians(30)
print(math.sin(r))
r = math.radians(180)
v = math.cos(r)
print( v )
print( r == math.acos(v) )
print( math.degrees(r) )
#0.49999999999999994
#-1.0
#True
#180.0


print("---")
#fractions
import fractions
print( fractions.Fraction(4,16) )
print( fractions.Fraction(-6, 21) )
print( fractions.Fraction(3) )
#1/4
#-2/7
#3

f = fractions.Fraction(4,3)
print(f)
#4/3
f2 = fractions.Fraction(f)
print(f2)
#4/3

print("---")
#special functions
print( fractions.Fraction('6/21') )
print( fractions.Fraction('3.14') )
print( fractions.Fraction('     -0.34     '))
s = """
-0.34
"""
print( fractions.Fraction(s) )
#2/7
#157/50
#-17/50
#-17/50

print("---")
from fractions import Fraction
print( Fraction.from_float(0.5) )
print( Fraction.from_decimal(4) )
#1/2
#4

print("---")
from math import pi, cos
from fractions import Fraction
print( Fraction.from_float(pi) )
#884279719003555/281474976710656
print( Fraction.from_float( pi ).limit_denominator(100) )
#311/99

f = Fraction.from_float(3.14)
print( f.__floor__() )
#3

import math
print( math.floor(f) )
print( math.ceil(f) )
print( round(f) )
#3
#3
#4
#3


import fractions
fractions.gcd(120, 180)
fractions.gcd(0.5, 6)
#60, 0.5

print("---")

#decimal
import decimal
print( decimal.Decimal(3) )
print( decimal.Decimal('1.1') )
print( decimal.Decimal(str(1/7)) )
#decimal.Deciaml( (0,(3,1,4),-2) )
print( decimal.Decimal("-Infinity") )
print( decimal.Decimal('-0') )
print( decimal.Decimal('NaN') )
#3
#1.1
#0.14285714285714285
#-Infinity
#-0
#NaN


a, b = decimal.Decimal('3.14'), decimal.Decimal('0.4')
print( a+b )
print( a-b )
print( a*b )
print( a/b )
print( a**b )
#3.54
#2.74
#1.256
#7.85
#1.580417606406722895935118558

a = decimal.Decimal('3.14')
print( a*3 )
print( divmod(a, 2) )
print( round(a, 1) )
print( int(a) )
#9.42
#(Decimal('1'), Decimal('1.14'))
#3.1
#3

print("---")
rawData = '3.14|5.3|1.65|9|-1.28'
l = [decimal.Decimal(x) for x in rawData.split('|') ]
print(l)
#[Decimal('3.14'), Decimal('5.3'), Decimal('1.65'), Decimal('9'), Decimal('-1.28')]
print( max(l) )
print( min(l) )
print( sum(l) )
print( sorted(l) )
#9
#-1.28
#17.81
#[Decimal('-1.28'), Decimal('1.65'), Decimal('3.14'), Decimal('5.3'), Decimal('9')]



from decimal import Decimal
d = Decimal("3.14")
print( d.sqrt() )
#1.772004514666935040199112510
print( d.exp() )
print( d.ln() )
#23.10386685872218278457908458
#1.144222799920161998805694448

d2 = Decimal("-1.414")
print( d.compare(d2) )
print( d.copy_abs() )
print( d.copy_negate() )
print( d.copy_sign(d2) )
#1
#3.14
#-3.14
#-3.14

print( d2.is_signed() )
print( d.is_finite() )
print( d.is_infinite() )
print( d.is_zero() )
#True
#True
#False
#False


#random
import random
print( random.random() )
print( random.random() )
#0.7774163660360384
#0.7987333021579469

print( random.uniform(3, 4) )
#3.013465537004017

for i in range(3):
 print( random.gauss(1, 1.0) )
#0.07892791910471075
#0.49322741367164435
#0.6201914100688197


print( [random.randrange(20) for i in range(10) ])
#[0, 15, 11, 5, 17, 15, 0, 0, 11, 4]

print( random.sample( range(20), 10 ))
#[16, 4, 8, 0, 15, 10, 2, 19, 7, 13]

print( [random.randrange(0,20,3) for i in range(5) ] )
#[18, 18, 18, 12, 12]


print("---")
l = list(range(10))
print(l)
print( [random.choice(l) for i in range(3) ])
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#[1, 0, 6]

print( random.sample(l,3))
#[5, 4, 8]


l = list( range(10) )
print( l )
random.shuffle(l)
print( l )
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#[2, 4, 1, 7, 3, 0, 8, 9, 5, 6]


l = list( range(10) )
s = random.sample(l, 10)
print( l, s)
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [9, 5, 6, 8, 7, 1, 3, 4, 0, 2]


Python study, time module, example source code

import time

print( time.time() ) #the timestamp after 1970.1.1
#1393854889.330645
print( time.gmtime() ) #UTC
#time.struct_time(tm_year=2014, tm_mon=3, tm_mday=3, tm_hour=13, tm_min=54, tm_sec=49, tm_wday=0, tm_yday=62, tm_isdst=0)
print( time.localtime() ) #current time based on system
#time.struct_time(tm_year=2014, tm_mon=3, tm_mday=3, tm_hour=22, tm_min=54, tm_sec=49, tm_wday=0, tm_yday=62, tm_isdst=0)
t = time.gmtime(1234567890)
print( t )
#time.struct_time(tm_year=2009, tm_mon=2, tm_mday=13, tm_hour=23, tm_min=31, tm_sec=30, tm_wday=4, tm_yday=44, tm_isdst=0)

print( t.tm_mon )
print( t.tm_hour )
#2
#23

print( time.asctime(t) )
print( time.mktime(t) )
#Fri Feb 13 23:31:30 2009
#1234535490.0


#sleep
t = time.time()
time.sleep(1) #10 second sleep
t2 = time.time()

spendtime = t2 - t
print( "before timestamp: ", t)
print( "after timestamp: ", t2)
print( "wait {0} second".format(spendtime))
#before timestamp:  1393855412.738972
#after timestamp:  1393855413.740086
#wait 1.0011141300201416 second

from time import localtime, strftime
print( strftime( "%B %dth %A %I:%M", localtime() ) )
print( strftime( "%Y-%m-%d %I:%M", localtime() ) )
print( strftime( "%y/%m/%d %H:%M:%S", localtime() ) )
print( strftime("%y/%m/%d %H:%M:%S", localtime() ) )
print( strftime("%x %X", localtime()) )

#March 03th Monday 11:03
#2014-03-03 11:03
#14/03/03 23:03:33
#14/03/03 23:03:33
#03/03/14 23:03:33

import datetime
print( datetime.date(2009, 5, 5) )
#2009-05-05
print( datetime.date.fromtimestamp( time.time() ) )
#2014-03-03
print( datetime.date.today() )
#2014-03-03


d = datetime.date.today()
print( d.year )
print( d.month )
print( d.day )
print( d.max )
print( d.min )
#2014
#3
#3
#9999-12-31
#0001-01-01

d = datetime.date.today()
d2 = d.replace(day=25)
print(d, d2)
#2014-03-03 2014-03-25

d.timetuple()
print( d.toordinal() )
print( d.weekday() )
#735295
#0 -> It means monday.

d = datetime.date.today()
print( d.isoformat() )
print( d.ctime() )
#2014-03-03
#Mon Mar  3 00:00:00 2014

from datetime import time
print( time(7) )
#07:00:00
print( time(8, 14, 20, 3000 ) )
#08:14:20.003000

print( time(hour=3, second=3) )
#03:00:03

print("-----")

from datetime import datetime, date, time
print( datetime.now() )
print( datetime.today() )
print( datetime.utcnow() )
print( datetime.fromtimestamp(1234567890))
print( datetime.utcfromtimestamp(1234567890))
print( datetime.fromordinal(732421))
d = date(2009, 3, 10)
t = time(12, 23, 53)
print( datetime.combine(d, t) )
#014-03-03 23:22:08.580259
#2014-03-03 23:22:08.580277
#2014-03-03 14:22:08.580292
#2009-02-14 08:31:30
#2009-02-13 23:31:30
#2006-04-20 00:00:00
#2009-03-10 12:23:53

print("----")

from datetime import datetime
dt = datetime.now()
print( dt.date() )
print( dt.time() )
print( dt.replace(hour=20, second=30 ) )
print( dt.timetuple() )
#2014-03-03
#23:25:15.304432
#2014-03-03 20:25:30.304432
#time.struct_time(tm_year=2014, tm_mon=3, tm_mday=3, tm_hour=23, tm_min=25, tm_sec=15, tm_wday=0, tm_yday=62, tm_isdst=-1)


print("----")
dt = datetime.now()
print( dt.weekday() )
print( dt.isoweekday() )
#0
#1

print(dt.isoweekday())
print(dt.ctime())
print( str(dt) )
#1
#Mon Mar  3 23:27:26 2014
#2014-03-03 23:27:26.117400

print(" timedelta class ");
from datetime import timedelta
print( timedelta(days=-3 ) )
print( timedelta( hours=7) )
#-3 days, 0:00:00
#7:00:00

print( timedelta(weeks=2, days=3, hours=-3, minutes=30) )
print( timedelta(minutes=3, milliseconds=-20, microseconds=400))
#16 days, 21:30:00
#0:02:59.980400

print("---")

from datetime import timedelta

td_1 = timedelta(hours = 7 )
td_2 = timedelta(days=-3)
print( td_1 + td_2 )
#-3 days, 7:00:00

print( td_1-td_2, td_1+td_2, td_1*4, td_1//3, abs(td_2))
#3 days, 7:00:00 -3 days, 7:00:00 1 day, 4:00:00 2:20:00 3 days, 0:00:00

td_1 = timedelta(hours = 7 )
td_2 = timedelta(days=-3)
print( td_1 > td_2 )
print( td_1 < td_2 )
#True
#False

td_1 = timedelta(hours=24)
td_2 = timedelta(seconds=86400)
print( td_1 == td_2 )
#True