'Programming'에 해당되는 글 76건

  1. 2015.09.30 Python - String, File, Regular Expression
  2. 2015.09.30 Python - Stock Price Quote
  3. 2015.09.30 VIM resource file
  4. 2015.09.29 Python - Date, Time
  5. 2015.09.26 Python with Django
  6. 2015.09.25 Regular Expression
  7. 2015.09.24 Book - EXCEL Hacks
  8. 2015.09.24 file/directory 비교 tool - Meld
  9. 2015.09.19 git 과 repo
  10. 2015.09.19 bash alias
Programming2015. 9. 30. 14:37


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

>>> ord(b'A')

65

>>> ord(b'!')

33

>>> list(b'Example')

[69, 120, 97, 109, 112, 108, 101]


>>> chr(65)

'A'

>>> chr(33)

'!'


>>>'This is an example, with punctuation and UPPERCASE.'.encode('ascii')

b'This is an example, with punctuation and UPPERCASE.'

>>> ascii = 'This is a test'.encode('ascii')

>>> ascii

b'This is a test'

>>> ascii.decode('utf-8')


{0}, {1}


>>> import os.path

>>> '{0:>20}{1}'.format(*os.path.splitext('contents.txt'))

'            contents.txt'

>>> for filename in ['contents.txt', 'chapter.txt', 'index.txt']:

... print('{0:<10}{1}'.format(*os.path.splitext(filename)))

contents .txt

chapter  .txt

index     .txt


>>> heading('Standard Format Specification')

'=====Standard Format Specification======'

>>> heading('This is a longer heading, beyond 40 characters')

'=This is a longer heading, beyond 40 characters='

>>> heading('Standard Format Specification', padding='-', width

'---------------Standard Format Specification----------------'



print string + str(123)


days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]

for i, d in enumerate(days):

    print i, d


0 Mon

1 Tue

2 Wed

3 Thu

4 Fri

5 Sat

6 Sun


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

String and Parsing

http://www.tutorialspoint.com/python/string_find.htm


str1 = "this is string example....wow!!!";
str2 = "exam";

print str(len(str1))+ " " +str(len(str2))
print str1.find(str2)
print str1.find(str2, 10)
print str1.find(str2, 40)
print str1.find("this", 0, len(str1))

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( )
print str.split(' ', 1 )

str1.capitalize()
str1.lower()
str1.upper()

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

File

f = open("textfile.txt") # by default, read only
f = open("textfile.txt","r")
f = open("textfile.txt","w+")
f = open("textfile.txt","a+")

if f.mode == 'r': # check to make sure that the file was opened

txt = f.read() # read entire content

fl = f.readlines() # readlines reads the individual lines into a list
for x in fl:
  print x

# write some lines of data to the file
for i in range(10):
  f.write("This is line %d\r\n" % (i+1))

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

File Path

import os
from os import path
import datetime
from datetime import date, time, timedelta
import time

def main():
  # Print the name of the OS
  print os.name
  
  # Check for item existence and type
  print "Item exists: " + str(path.exists("textfile.txt"))
  print "Item is a file: " + str(path.isfile("textfile.txt"))
  print "Item is a directory: " + str(path.isdir("textfile.txt"))
  
  # Work with file paths
  print "Item's path: " + str(path.realpath("textfile.txt"))
  print "Item's path and name: " + str(path.split(path.realpath("textfile.txt")))
  
  # Get the modification time
  t = time.ctime(path.getmtime("textfile.txt"))
  print t
  print datetime.datetime.fromtimestamp(path.getmtime("textfile.txt"))
  
  # Calculate how long ago the item was modified
  td= datetime.datetime.now() - datetime.datetime.fromtimestamp(path.getmtime("textfile.txt"))
  print "It has been " + str(td) + "The file was modified"
  print "Or, " + str(td.total_seconds()) + " seconds"
  
if __name__ == "__main__":
  main()

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

Regular Expression

import time, os, re
# display time corresponding to your location
print(time.ctime())
f=open("sink_info.txt")
txt = f.read()
#AU_LINUX_ANDROID_LA.BF64.1.2.2.05.01.01.110.103
result = re.search("AU_LINUX_ANDROID_LA.\w+.\d.\d.\d.\d{2}.\d{2}.\d{2}.\d{3}.\d{3}", txt)
#result = re.search("AU_LINUX_ANDROID_LA.(HB|BF64).[0-9].[0-9].[0-9].[0-9]{2}.[0-9]{2}.[0-9]{2}.[0-9]{3}.[0-9]{3}", txt)
print result
if result:
	tmp1=result.group(0)
	#tmp2=result.group(1)
	print tmp1
	#print tmp2

#RUN SINK command with this AU


'Programming' 카테고리의 다른 글

Python - JSON을 이용한 지진검색  (0) 2015.10.01
VM Virtualbox에 Ubuntu설치후  (0) 2015.10.01
Python - Stock Price Quote  (0) 2015.09.30
VIM resource file  (0) 2015.09.30
Python - Date, Time  (0) 2015.09.29
Posted by 쁘레드
Programming2015. 9. 30. 10:28

주식시세 query

webservicex는 response가 간단해서 빠른편인데, data 자체는 realtime도 아니고 15-20분에 한번씩 update는것 같음.

Google finance는 response자체가 너무 복잡함. 시간이 좀 걸림. 개인적인 용도로는 상관없지만.

간단하게 빠르게 update되는 서버는 무료는 없을듯. Nasdaq에서 한달에 얼마씩 내면 준다고 함.

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

http://www.webservicex.net/stockquote.asmx/GetQuote?symbol=aapl


XML response example)

<string xmlns="http://www.webserviceX.NET/">

<StockQuotes>

<Stock>

<Symbol>aapl</Symbol>

<Last>109.06</Last>

<Date>9/29/2015</Date>

<Time>4:00pm</Time>

<Change>-3.38</Change>

<Open>112.79</Open>

<High>113.51</High>

<Low>107.86</Low>

<Volume>73365384</Volume>

<MktCap>621.94B</MktCap>

<PreviousClose>112.44</PreviousClose>

<PercentageChange>-3.01%</PercentageChange>

<AnnRange>92.00 - 134.54</AnnRange>

<Earns>8.65</Earns>

<P-E>12.62</P-E>

<Name>Apple Inc.</Name>

</Stock>

</StockQuotes>


*but from urllib2 read, all tags are UTF-9 encoded(llike corrupted) like below ==> HTML parser로 escape문자를 바꿔줘야함

<?xml version="1.0" encoding="utf-8"?>

<string xmlns="http://www.webserviceX.NET/">&lt;StockQuotes&gt;&lt;Stock&gt;&lt;Symbol&gt;AAPL&lt;/Symbol&gt;&lt;Last&gt

;109.06&lt;/Last&gt;&lt;Date&gt;9/29/2015&lt;/Date&gt;&lt;Time&gt;4:00pm&lt;/Time&gt;&lt;Change&gt;-3.38&lt;/Change&gt;&

lt;Open&gt;112.79&lt;/Open&gt;&lt;High&gt;113.51&lt;/High&gt;&lt;Low&gt;107.86&lt;/Low&gt;&lt;Volume&gt;73365384&lt;/Vol

ume&gt;&lt;MktCap&gt;621.94B&lt;/MktCap&gt;&lt;PreviousClose&gt;112.44&lt;/PreviousClose&gt;&lt;PercentageChange&gt;-3.0

1%&lt;/PercentageChange&gt;&lt;AnnRange&gt;92.00 - 134.54&lt;/AnnRange&gt;&lt;Earns&gt;8.65&lt;/Earns&gt;&lt;P-E&gt;12.6

2&lt;/P-E&gt;&lt;Name&gt;Apple Inc.&lt;/Name&gt;&lt;/Stock&gt;&lt;/StockQuotes&gt;</string>

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

Pattern matching in XML

import urllib2, time, os, re
import HTMLParser
def fetchStockPrice(ticker):
	url="http://www.webservicex.net/stockquote.asmx/GetQuote?symbol="
	txt=urllib2.urlopen(url+ticker).read()
	html_parser = HTMLParser.HTMLParser()
	parsed = html_parser.unescape(txt)
	#print parsed
	#unicode =  txt.encode('utf-8')
	#print unicode

	#result=re.search('(.*?)',parsed)
	result=re.search('([0-9]+\.[0-9]+)', parsed)
	if result:
		stockprice = result.group(1)
		cur_date = re.search('(.*?)',parsed)
		cur_time = re.search('',parsed)
		ret = stockprice + " " + cur_date.group(1) + " " + cur_time.group(1)
	else:
		stockprice = "Nothing found for: " + ticker
		ret = "Nothing found for: " + ticker
	return ret

print ("NOW = " + time.ctime())
print "Stock Price is " + fetchStockPrice("AAPL") 

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

Just Pattern Matching Python code
import  urllib2, time, os, re
def fetchStockPrice(ticker):
	url="http://www.webservicex.net/stockquote.asmx/GetQuote?symbol="
	txt=urllib2.urlopen(url+ticker).read()
	#f=open("sample.xml")
	#txt = f.read()
	#print txt
	#result=re.search('(.*?)',txt)
	result=re.search('([0-9]+\.[0-9]+)',txt)
	#result=re.search("Last\>(\d+\.\d+)\</Last", txt)
	if result:
		stockprice = result.group(1)
	else:
		stockprice = "Nothing found for: " + ticker
	return stockprice

print(time.ctime())
print fetchStockPrice("AAPL") 


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

XML parsing example

https://docs.python.org/2/library/xml.dom.minidom.html?highlight=xml.dom.minidom#module-xml.dom.minidom

import xml.dom.minidom

document = """\

	
		aapl
		109.06
		9/29/2015
		
		-3.38
		112.79
		113.51
		107.86
		73365384
		621.94B
		112.44
		-3.01%
		92.00 - 134.54
		8.65
		12.62
		Apple Inc.
	

"""

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

def getStockPrice(quote):
	 print "Last Stock Price is :" % getText(quote.childNodes)

def handleToc(stocks):
    for stock in stocks:
		symbol = stock.getElementsByTagName("Symbol")[0]
		print "

%s

" % getText(symbol.childNodes) last = stock.getElementsByTagName("Last")[0] print "

%s

" % getText(last.childNodes) date = stock.getElementsByTagName("Date")[0] print "

%s

" % getText(date.childNodes) time = stock.getElementsByTagName("Time")[0] print "

%s

" % getText(time.childNodes) dom = xml.dom.minidom.parseString(document) stocks = dom.getElementsByTagName("Stock") handleToc(stocks)

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

Stock Quote from Google finance

import urllib2, time, os, re, csv
 
def fetchGF(googleticker):
	url="http://www.google.com/finance?&q="
	txt=urllib2.urlopen(url+googleticker).read()
	#print txt
	#search phase 112.44
	k=re.search('id="ref_(.*?)">(.*?)<',txt)
	#print k
	if k:
		tmp1=k.group(0)
		tmp2=k.group(1)
		#print tmp1
		#print tmp2
		tmp=k.group(2)
		#print tmp
		q=tmp.replace(',','')
		#print q
	else:
		q="Nothing found for: "+googleticker
	return q
	
print(time.ctime())
print fetchGF("AAPL")
#print fetchGF("NASDAQ:AAPL")

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

Stock Portfolio를 query하려면

#file에서 읽어도 좋겠다.
tickers=["NASDAQ:AAPL","NASDAQ:GOOG","NASDAQ:BIDU","NYSE:IBM", \
         "NASDAQ:INTC","NASDAQ:MSFT","NYSEARCA:SPY"]

for ticker in tickers:
	data=combine(ticker)
	print(data)

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

 xmlparsing_finished.py


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

import urllib2, time, os, re
import HTMLParser
def fetchStockPrice(ticker):
    url="http://www.webservicex.net/stockquote.asmx/GetQuote?symbol="
    txt=urllib2.urlopen(url+ticker).read()
    html_parser = HTMLParser.HTMLParser()
    parsed = html_parser.unescape(txt)
    #print parsed
    #unicode =  txt.encode('utf-8')
    #print unicode
 
    #result=re.search('(.*?)',parsed)
    result=re.search('([0-9]+\.[0-9]+)', parsed)
    if result:
        stockprice = result.group(1)
        cur_date = re.search('(.*?)',parsed)
        cur_time = re.search('',parsed)
        cur_percent = re.search('(.*?)',parsed)
        #Text formatting
        ret = '{:4s}: {:7s} {:7s} - {:10s} {:7s}'.format(ticker, stockprice, cur_percent.group(1), cur_date.group(1), cur_time.group(1))
        #ret =  '{:4s}'.format(ticker) + ": " +stockprice + " " + cur_percent.group(1) + " " + cur_date.group(1) + " " + cur_time.group(1)
    else:
        stockprice = "Nothing found for: " + ticker
        ret = "Nothing found for: " + ticker
    return ret
 
print(time.ctime())

#tickers=["NASDAQ:AAPL","NASDAQ:GOOG","NASDAQ:QCOM","NYSE:NUAN", \
#         "NASDAQ:INTC","NYSE:DAL","NYSE:F", "NYSE:SMI", "NASDAQ:HQCL", "NYSEARCA:UCO"]
tickers=["AAPL","GOOG","QCOM","NUAN", \
         "INTC","DAL","F", "SMI", "HQCL", "UCO"]
print ("--------------------------")
#print fetchStockPrice("AAPL")
for ticker in tickers:
    data=fetchStockPrice(ticker)
    print(data)
print ("--------------------------") 

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


stockprices.py


'Programming' 카테고리의 다른 글

VM Virtualbox에 Ubuntu설치후  (0) 2015.10.01
Python - String, File, Regular Expression  (0) 2015.09.30
VIM resource file  (0) 2015.09.30
Python - Date, Time  (0) 2015.09.29
Python with Django  (0) 2015.09.26
Posted by 쁘레드
Programming2015. 9. 30. 09:46

vim with ctags, cscope

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

Download VIM plug-ins from vim.org

Source Explorer

Nerd Tree

Tag list


unzip copy to vim plugins folder

~/.vim/plugins

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


"VI env"
set nu
set ai
set ts=4
set bg=dark

ctag db"
set tags=/home/fred/host/kernel-3.10/linux-3.10.89/tags

"cscope db"
set csprg=/usr/bin/cscope
set csto=0
set cst
set nocsverb
cs add /home/fred/host/kernel-3.10/linux-3.10.89/cscope.out /home/fred/host/kernel-3.10/linux-3.10.89
set csverb

"tag list"
filetype on
nmap  :TlistToggle
let Tlist_Ctags_Cmd = "/usr/bin/ctags"
let Tlist_Inc_Winwidth = 0
let Tlist_Exit_OnlyWindow = 0
let Tlist_Auto_Open = 0
let Tlist_Use_Right_Window = 1

"Source Explorer"
nmap  :SrcExplToggle
nmap  h
nmap  j
nmap  k
nmap  l

let g:SrcExpl_winHeight = 8
let g:SrcExpl_refreshTime = 100
let g:SrcExpl_jumpKey = ""
let g:SrcExpl_gobackKey = ""
let g:SrcExpl_isUpdateTags = 0

"Nerd Tree"
let NERDTreeWinPos = "left"
nmap  :NERDTreeToggle"

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

make ARCH=x86 COMPILED_SOURCE=1 cscope tags

cscope -d  ; do not update cross reference

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

F7, F8, F9 ;open plugins


CRTL + H J K L ; windows switching

SPACEBAR ; previous window

CTRL + ] ; jump to definition

CTRL + t ; back to previous code


cscope command

:CS find s <SYMBOL_NAME>



'Programming' 카테고리의 다른 글

Python - String, File, Regular Expression  (0) 2015.09.30
Python - Stock Price Quote  (0) 2015.09.30
Python - Date, Time  (0) 2015.09.29
Python with Django  (0) 2015.09.26
Regular Expression  (0) 2015.09.25
Posted by 쁘레드
Programming2015. 9. 29. 21:59


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

http://www.tutorialspoint.com/python/python_date_time.htm

https://docs.python.org/2/library/datetime.html


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

TimeZone and Local time

import os, time

print(time.ctime())

#FRED : doesn't work in Windows, only UNIX/Linux
# Set local time zone to NYC
os.environ['TZ']='America/New_York'
time.tzset()
print time.strftime('%X %x %Z')

os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
time.tzset()
print time.strftime('%X %x %Z')

t=time.localtime() # string
print(time.ctime())

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

from datetime import date
from datetime import time
from datetime import datetime

def main():
  ## DATE OBJECTS
  # Get today's date from the simple today() method from the date class
  today = date.today()
  print "Today's date is ", today
  
  # print out the date's individual components
  print "Date Components: ", today.day, today.month, today.year
  
  # retrieve today's weekday (0=Monday, 6=Sunday)
  print "Today's Weekday #: ", today.weekday()
  
  ## DATETIME OBJECTS
  # Get today's date from the datetime class
  today = datetime.now()
  print  "The current date and time is ", today
  
  # Get the current time
  t = datetime.time(datetime.now())
  print "The current time is ", t
  
  # weekday returns 0 (monday) through 6 (sunday)
  wd = date.weekday(today)  
  # Days start at 0 for Monday 
  days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
  print "Today is day number %d" % wd
  print "Which is a " + days[wd]
  
  
if __name__ == "__main__":
  main();
 

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

Formatting

http://www.tutorialspoint.com/python/time_strftime.htm

from datetime import datetime

def main():
  # Times and dates can be formatted using a set of predefined string
  # control codes 
  now = datetime.now() # get the current date and time
  
  #### Date Formatting ####
  
  # %y/%Y - Year, %a/%A - weekday, %b/%B - month, %d - day of month
  print now.strftime("%Y") # full year with century
  print now.strftime("%a, %d %B, %y") # abbreviated day, num, full month, abbreviated year
  
  # %c - locale's date and time, %x - locale's date, %X - locale's time
  print now.strftime("%c")
  print now.strftime("%x")
  print now.strftime("%X")
  
  #### Time Formatting ####
  
  # %I/%H - 12/24 Hour, %M - minute, %S - second, %p - locale's AM/PM
  print now.strftime("%I:%M:%S %p") # 12-Hour:Minute:Second:AM
  print now.strftime("%H:%M") # 24-Hour:Minute

  ## Fred's preference
  print now.strftime("FRED date_time format: %Y%m%d_%H%M%S")

if __name__ == "__main__":
  main();

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

Diff, counting date, time

from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

# construct a basic timedelta and print it
print timedelta(days=365, hours=5, minutes=1)

# print today's date
print "today is: " + str(datetime.now())

# print today's date one year from now
print "one year from now it will be: " + str(datetime.now() + timedelta(days=365))

# create a timedelta that uses more than one argument
print "in two weeks and 3 days it will be: " + str(datetime.now() + timedelta(weeks=2, days=3))

# calculate the date 1 week ago, formatted as a string
t = datetime.now() - timedelta(weeks=1)
s = t.strftime("%A %B %d, %Y")
print "one week ago it was " + s

### How many days until April Fools' Day?

today = date.today()  # get today's date
afd = date(today.year, 4, 1)  # get April Fool's for the same year
# use date comparison to see if April Fool's has already gone for this year
# if it has, use the replace() function to get the date for next year
if afd < today:
  print "April Fool's day already went by %d days ago" % ((today-afd).days)
  afd = afd.replace(year=today.year + 1)  # if so, get the date for next year

# Now calculate the amount of time until April Fool's Day  
time_to_afd = abs(afd - today)
print time_to_afd.days, "days until next April Fools' Day!"


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

import calendar

# create a plain text calendar
c = calendar.TextCalendar(calendar.SUNDAY)
str = c.formatmonth(2015, 1, 0, 0)
print str

# create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.SUNDAY)
str = hc.formatmonth(2015, 1)
print str

# loop over the days of a month
# zeroes mean that the day of the week is in an overlapping month
for i in c.itermonthdays(2015, 8):
  print i

# The Calendar module provides useful utilities for the given locale,
# such as the names of days and months in both full and abbreviated forms
for name in calendar.month_name:
  print name

for day in calendar.day_name:
  print day

# Calculate days based on a rule: For example, consider
# a team meeting on the first Friday of every month.
# To figure out what days that would be for each month,
# we can use this script:
for m in range(1,13):
  # returns an array of weeks that represent the month
  cal = calendar.monthcalendar(2015, m)
  # The first Friday has to be within the first two weeks
  weekone = cal[0]
  weektwo = cal[1]
   
  if weekone[calendar.FRIDAY] != 0:
    meetday = weekone[calendar.FRIDAY]
  else:
    # if the first friday isn't in the first week, it must be in the second
    meetday = weektwo[calendar.FRIDAY]
      
  print "%10s %2d" % (calendar.month_name[m], meetday)


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


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


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

'Programming' 카테고리의 다른 글

Python - Stock Price Quote  (0) 2015.09.30
VIM resource file  (0) 2015.09.30
Python with Django  (0) 2015.09.26
Regular Expression  (0) 2015.09.25
Book - EXCEL Hacks  (0) 2015.09.24
Posted by 쁘레드
Programming2015. 9. 26. 07:38

Python으로 website를 돌리는것을 배우려고 강좌를 하나 봤는데 꽤 재밌고 빠르고 짧다.

문제는 python language가 그렇듯 high level abstraction이 쉬운것처럼 보이지만 반대로 상당히 이해하기 어렵다. 말은 쉬운데 진짜로 만들기 어려운것 처럼. 하여간 output을 만들면 짧고 간견하세 maintenance는 쉬울듯.

이번에 Python으로 inventory check하는 프로그램을 만들려고 하는데 이것으로 하면 재밌겠다.



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

Up and Running with Python and Django

http://www.lynda.com/Developer-Web-Development-tutorials/Up-Running-Python-Django/386287-2.html


https://www.djangoproject.com/

http://djangogirls.com


*Need pip

sudo apt-get install python-pip


django-admin startproject <project_name>

manage.py runserver


*FIles

__init__.py

wggi.py : hook for web

urls.py

settings.py : DEBUG, Database

- Models - data layer

model.py


-Migration

manage.py

manage.py migrate --list

manage.py makemigration

manage.py migrate



*SQL browser

http://sqlitebrowser.org/ 

 

 URL Patterns  -> Views -> Templates

                                  |

                                  |

                                  |

                              Models


*New text editor

http://www.sublimetext.com/2


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

Barcode scanner

https://play.google.com/store/apps/details?id=com.google.zxing.client.android&hl=en

https://github.com/zxing/zxing


ZXing-based third-party open source projects

ModuleDescription
QZXingport to Qt framework
zxing-cppport to C++ (forked from the deprecated official C++ port)
zxing_cpp.rbbindings for Ruby (not just JRuby), powered by zxing-cpp
python-zxingbindings for Python
ZXing .NETport to .NET and C#, and related Windows platform

Other related third-party open source projects


ModuleDescription
Barcode4JGenerator library in Java
ZBarReader library in C99
OkapiBarcode


'Programming' 카테고리의 다른 글

VIM resource file  (0) 2015.09.30
Python - Date, Time  (0) 2015.09.29
Regular Expression  (0) 2015.09.25
Book - EXCEL Hacks  (0) 2015.09.24
file/directory 비교 tool - Meld  (0) 2015.09.24
Posted by 쁘레드
Programming2015. 9. 25. 03:23

Javascript based regular expression engine.

http://regexpal.com/ - save it to file and enable global checkmark which is enabled by default.


Python reqular expression test

http://pythex.org/

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

grep

egrep = grep -e

awk, vi, emacs

POSIX

BRE - Basic R.E.

ERE - Extended R.E.

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


\ : excape character

\t : tab

\r, \n, \r\n : new lines


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

[aeiou] : any of vowel

[0-9] : - is range character

[A-Za-z] : all alphabet

[^aeiou] : non vowel

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

[\d\s] : digit and space

[^\d\s] : non digit and non space

[\D\S] : all ==> don't use multiple capital characters


*POSIX expressions are not popular



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

#Year

(19|20)\d\d

/(19[5-9]\d|20[0-4]\d)/

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

# Does first letter have to be capitalized?

Regex:  /^[A-Z][A-Za-z]+$/m


# Capture first, middle, and last name

Regex:  /^([A-Z][A-Za-z.'\-]+) (?:([A-Z][A-Za-z.'\-]+) )?([A-Z][A-Za-z.'\-]+)$/m

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

# U.S. postal codes

Regex:  /^\d{5}(-\d{4})?$/m


# Canada postal codes

Regex:  /^[A-Z]\d[A-Z] \d[A-Z]\d$/m

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

# Email and domain specifications allow other characters

Regex:  /^[\w.%+\-]+@[\w.\-]+\.[A-Za-z]{2,3}$/


Regex:  /^[\w.%+\-]+@[\w.\-]+\.[A-Za-z]{2,6}$/

String: "someone@somewhere.museum"

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

# Query string portion

Regex:  /^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+.*$/

Regex:  /^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+[/?#]?.*$/

Regex:  /^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+[\w\-.,@?^=%&:/~\\+#]*$/


# Make groups non-capturing

Regex:  /^(?:http|https):\/\/[\w\-_]+(?:\.[\w\-_]+)+[\w\-.,@?^=%&:/~\\+#]*$/

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

# Decimal numbers

Regex:  /^\d+\.\d+$/m

Regex:  /^\d?\.\d+$/m

Regex:  /^\d*\.?\d*$/m


# U.S. Dollar

Regex:  /^\$(\d*\.\d{2}|\d+)$/m

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

# 12 hour time

Regex:  /^(0?[1-9]|1[0-2]):[0-5][0-9]$/m


# Optional am/pm


Regex:  /^(0?[1-9]|1[0-2]):[0-5][0-9](am|pm|AM|PM)?$/m

Regex:  /^(0?[1-9]|1[0-2]):[0-5][0-9]([aApP][mM])?$/m


Timezone


Regex:  /^([0-1]?[0-9]|[2][0-3]):[0-5][0-9](:[0-5][0-9])?( [A-Z]{3})?$/m

Regex:  /^([0-1]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?( ([A-Z]{3}|GMT [-+]([0-9]|1[0-2])))?$/m

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

.Any character except newline.
\.A period (and so on for \*, \(, \\, etc.)
^The start of the string.
$The end of the string.
\d,\w,\sA digit, word character [A-Za-z0-9_], or whitespace.
\D,\W,\SAnything except a digit, word character, or whitespace.
[abc]Character a, b, or c.
[a-z]a through z.
[^abc]Any character except a, b, or c.
aa|bbEither aa or bb.
?Zero or one of the preceding element.
*Zero or more of the preceding element.
+One or more of the preceding element.
{n}Exactly n of the preceding element.
{n,}n or more of the preceding element.
{m,n}Between m and n of the preceding element.
??,*?,+?,
{n}?, etc.
Same as above, but as few as possible.
(expr)Capture expr for use with \1, etc.
(?:expr)Non-capturing group.
(?=expr)Followed by expr.
(?!expr)Not followed by expr.

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

Regular expression cheat sheet

Special characters

\escape special characters
.matches any character
^matches beginning of string
$matches end of string
[5b-d]matches any chars '5', 'b', 'c' or 'd'
[^a-c6]matches any char except 'a', 'b', 'c' or '6'
R|Smatches either regex R or regex S
()creates a capture group and indicates precedence

Quantifiers

*0 or more (append ? for non-greedy)
+1 or more (append ? for non-greedy)
?0 or 1 (append ? for non-greedy)
{m}exactly mm occurrences
{m, n}from m to nm defaults to 0, n to infinity
{m, n}?from m to n, as few as possible

Special sequences

\Astart of string
\bmatches empty string at word boundary (between \wand \W)
\Bmatches empty string not at word boundary
\ddigit
\Dnon-digit
\swhitespace: [ \t\n\r\f\v]
\Snon-whitespace
\walphanumeric: [0-9a-zA-Z_]
\Wnon-alphanumeric
\Zend of string
\g<id>matches a previously defined group

Special sequences

(?iLmsux)matches empty string, sets re.X flags
(?:...)non-capturing version of regular parentheses
(?P...)matches whatever matched previously named group
(?P=)digit
(?#...)a comment; ignored
(?=...)lookahead assertion: matches without consuming
(?!...)negative lookahead assertion
(?<=...)lookbehind assertion: matches if preceded
(?<!...)negative lookbehind assertion
(?(id)yes|no)match 'yes' if group 'id' matched, else 'no'


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

Unicode

Unicode indicator: \u

caf\u00E9 = cafe (e is unicode)


Unicode wildcard : \X (only for Perl and PHP)


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


-----------


-----------

'Programming' 카테고리의 다른 글

Python - Date, Time  (0) 2015.09.29
Python with Django  (0) 2015.09.26
Book - EXCEL Hacks  (0) 2015.09.24
file/directory 비교 tool - Meld  (0) 2015.09.24
git 과 repo  (0) 2015.09.19
Posted by 쁘레드
Programming2015. 9. 24. 10:49

EXCEL하면

  • Finding/removing duplicates
  • Sorting
  • Filtering
  • Conditional formatting
  • Pivot table
  • vlookup() 응용


오늘은 EXCEL Hacks 라는 책을 봤습니다. 오래 볼것은 아니고 스스로 필요한 부분만 빨리 습득하면 될만한 책인데, 상당히 유용한 tip들을 많이가지고 있습니다.


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

EXCEL conditional formatting이라는 메뉴가 있습니다. 이미 free define되어 있는 기능도 있는데 duplicate를 highlight해주는게 있습니다

Data에서 remove duplicates과는 다르게 유용합니다.


conditional formatting으로 every row마다 다른 background도 표시할수 있고

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

두 table차이 비교하기

1. =A1=A19 처럼TRUE or FALSE로 찾기

2. Conditional formatting으로 =NOT(A1=A9) 때 color표시하기

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

VLOOKUP 으로 이전 리스트와 비교하기

=VLOOKUP(VALUE, TABLE_RANGE, COLUME_from_the_table, 0)

=VLOOKUP(C1,F1:H13,1,0)


TIP: drag해도 range를 변하지 않게 하려면 절대 range를 넣어준다.

L1:L5 vs $L$1:$L$5

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

이미 순서 정해진 array에서 그 subset이 주어지면 그 mother array의 순서에 맞게 sub-array를 sorting

==>이것도 VLOOKUP을 이용해서

=VLOOKUP(K2, $L$2:$L$6,1,0)


기준 subset 결과 모범답
Fred Joe Fred Fred
Joe Fred Joe Dave
Dave Dave Dave Joe
James Tania #N/A Mett
Joe Mett Joe Tania
Minsu #N/A
Mett Mett
Robyn #N/A
Marlene #N/A
Tania Tania
Jill #N/A
Jill #N/A

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


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

'Programming' 카테고리의 다른 글

Python with Django  (0) 2015.09.26
Regular Expression  (0) 2015.09.25
file/directory 비교 tool - Meld  (0) 2015.09.24
git 과 repo  (0) 2015.09.19
bash alias  (0) 2015.09.19
Posted by 쁘레드
Programming2015. 9. 24. 02:24

Windows에서는 Beyond Compare를 오래동안 썼는데,

Meld는 open source로 된 tool인데 상당히 좋네요. Linux, WIndows지원

윈도우즈는 설치파일로 잘 될것 같은데, 리눅스는 이놈의 GTK+ 버전때문에 오래된 리눅스는 안되고 아주 복잡하네요. Open Source/Linux가 더 크게 성장못하는 좋은 예이기도 한네요. 엄청좋은데 사용자를 계속 짜증나게 하는것이죠.

http://meldmerge.org/


Requirements

  • Python 2.7 (Python 3 not yet supported)
  • GTK+ 3.12
  • GLib 2.36
  • PyGObject 3.8
  • GtkSourceView 3.10

-----------


'Programming' 카테고리의 다른 글

Regular Expression  (0) 2015.09.25
Book - EXCEL Hacks  (0) 2015.09.24
git 과 repo  (0) 2015.09.19
bash alias  (0) 2015.09.19
codeaurora.org and linaro.org  (0) 2015.09.13
Posted by 쁘레드
Programming2015. 9. 19. 17:22

git과 repo 이야기

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


Using repo and git

git config sample, alias in git config?

sudo apt-get install g++-multilib bison g++-multilib git gperf libxml2-utils make python-networkx zlib1g-dev:i386 zip

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

git diff

git diff --cached


git rm <file>

git rm --cached <file> ; unstaging

git reset HEAD <file> ; unstaging

git checkout -- <file>; unmodify


git log
--oneline
--decorate
--remote
--no-merges = --max-parents=1

--stat : show modified files

--graph : ascii graph

--pretty : show commit in alternate format


--since, --after

--until,--before

--author

--committer

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

git gui = gitk

install xming and set putty X11 forwarding

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

git branching is killer feature
incredibly lightweight
git branch <branch>
git checkout -b <branch>
git merge <branch_src> ; merge branch_src to current branch
will create 'merge commit'

git fetch orgin

merge or rebase

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

git clone [git url]

git clone [git url] [dir name]

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

git pull = fetch + merge

or

git pull = fetch + rebase

or

git pull = fetch

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

git push orgin HEAD:remote

git push orgin HEAD:refs/for/BRANCH

refs/for = gerrit server.

Change-ID is for gerrit server.

$ git push ssh://review-android.quicinc.com:29418/PROJECT HEAD:refs/for/BRANCH
$ git push ssh://review-android.quicinc.com:29418/PROJECT COMMIT_ID:refs/changes/CHANGE_NUM

git clone git://PATH/PROJECT.git

cd PROJECT

$ git remote

quic

$ git remote -v

quic    ssh://git.quicinc.com:29418/platform/vendor/qcom/msm8992 (fetch)

quic    ssh://git.quicinc.com:29418/platform/vendor/qcom/msm8992 (push)


Adding remote repositories
git remote add [shortname] [url]
git remote add pb git://github.com/paulboone/ticgit.git

git fetch [remote-name]
git fetch pb

$revp
path=device/qcom/msm8992; project=platform/vendor/qcom/msm8992; refs=LA.BF64.1.2.1
git push [remote] HEAD:refs/for/BRANCH
git push quic HEAD:refs/for/LA.BF64.1.2.1 ; 이 command가 먹힐지 궁금

git remote rename pb paul
$ git remote
orgin
paul

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

git format-patch HEAD^
scripts/checkpatch.pl 0001-xxxx.patch
or
git show HEAD | scripts/checkpatch.pl -

git format-patch FROM...TO
  • How to apply patch
git apply --stat PATCH.patch ; just to check
git apply PATCH.patch
patch -p1 <PATCH.patch
git am < 000*
git am -3 < 

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

repo init

-u url
-m manifest, otherwise default.xml
-b specify revision branch

repo sync
[project list]
at first = git clone
already done = git remote update; git rebase orgin/<branch>

repo start <branch> -all
starting from the revision specified in the manifest.
git checkout (starting from the revision)
        + git branch <branch>

repo upload
[project list]
git push

repo forall -c [git commands]

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

git command alias for bash

### Git command

alias gbr='git branch'

alias gcm='git commit'

alias gco='git checkout'

alias gst='git status'

alias gd='git diff'

alias gdf='git diff'

alias gad='git add'

alias gch='git cherry-pick'

alias gcl='git clean -x -f -d'

alias gf='git format-patch'

alias ghe='git help'

alias gres='git reset --hard HEAD'

alias gr='git rebase'

alias gre='git rebase'

alias gl='git log --oneline --decorate'

alias gll='git log --stat --decorate'

alias gs='git show'

alias gbl='git blame'

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

'Programming' 카테고리의 다른 글

Book - EXCEL Hacks  (0) 2015.09.24
file/directory 비교 tool - Meld  (0) 2015.09.24
bash alias  (0) 2015.09.19
codeaurora.org and linaro.org  (0) 2015.09.13
Natural Language Processing with Python  (0) 2015.08.24
Posted by 쁘레드
Programming2015. 9. 19. 16:33

Linux BASH에서 유용한 alias들


----------

## get rid of command not found ##

alias cd..='cd ..'


## a quick way to get out of current directory ##

alias ..='cd ..'

alias ...='cd ../../../'

alias ....='cd ../../../../'

alias .....='cd ../../../../'

alias .4='cd ../../../../'

alias .5='cd ../../../../..'


alias grep='grep --color=auto'

alias egrep='egrep --color=auto'

alias fgrep='fgrep --color=auto'


#Start calculator with math support

alias bc='bc -l'

# install  colordiff package :)

alias diff='colordiff'

#Make mount command output pretty and human readable format

alias mount='mount |column -t'


alias redo='source ~/.bash_profile'

alias root='cd ~<ID>'

alias cls='clear'

alias vi='vim'

alias emacs="emacs -nw"

#eval `dircolors -b ~/.dir_colors`

alias ls="ls --color=auto"

alias ll="ls -al --color=auto"

alias rd='rdesktop -g 1152x900 -k en-us -a 24 -s sound:local DESKTOP_NAME:3389 -u <ID>-d ap &'

alias do_synergy='synergyc <IP_ADDRESS>'

alias build_kernel='m -j8 ONE_SHOT_MAKEFILE=build/target/board/Android.mk bootimage'

alias build_all='make -j12 > buildlog.txt 2>&1'

alias git_config_quic='git config user.email <QUIC_EMAIL>'


#######################

### Stuff for Linux ###

#######################

#if [ `uname` = "Linux" ] ; then

#  source /usr/local/projects/l4linux/.bash_l4linux

#  source /prj/l4linux/.bash_nativelinux -a 2.1 -g 3.4.4 # for 7200 Native Linux

#  source /prj/l4linux/.bash_l4.gcc344                  # for 6800 Linux on L4

  alias work='cd /local/mnt/workspace/<ID>'

  alias work2='cd /local/mnt2/workspace2/<ID>'

  alias work3='cd /local/mnt/workspace3/<ID>'

  alias setenv='source build/envsetup.sh'

  alias l8974='lunch msm8974-userdebug'

  alias l8226='lunch msm8226-userdebug'

  alias l8x26='lunch msm8226-userdebug'

  alias l8084='lunch apq8084-userdebug'

  alias l8994='lunch msm8994-userdebug'

  alias l8916='lunch msm8916_64-userdebug'

  alias l8992='lunch msm8992-userdebug'

  alias l8996='lunch msm8996-userdebug'

  alias msm=msm8992

#fi


### Git command

alias gbr='git branch'

alias gcm='git commit'

alias gco='git checkout'

alias gst='git status'

alias gd='git diff'

alias gdf='git diff'

alias gad='git add'

alias gch='git cherry-pick'

alias gcl='git clean -x -f -d'

alias gf='git format-patch'

alias ghe='git help'

alias gres='git reset --hard HEAD'

alias gr='git rebase'

alias gre='git rebase'

alias gl='git log --oneline --decorate'

alias gll='git log --stat --decorate'

alias gs='git show'

alias gbl='git blame'


### Project path

alias av="cd frameworks/av"

alias af="cd frameworks/av/services/audioflinger"

alias hal="cd hardware/qcom/audio/hal"

alias nuplayer="cd frameworks/av/media/libmediaplayerservice/nuplayer"

alias msm="cd kernel/sound/soc/msm"

alias misc="cd kernel/drivers/misc/qcom/qdsp6v2"

alias audio_ion="cd kernel/drivers/soc/qcom/qdsp6v2"

alias codec="cd kernel/sound/soc/codecs"

alias dt="cd kernel/arch/arm64/boot/dts/qcom"

alias dtsi="cd kernel/arch/arm64/boot/dts/qcom"

alias defconfig="cd kernel/arch/arm64/configs"

alias kernel_driver="cd kernel/drivers/soc/qcom"

alias mm-audio="cd vendor/qcom/proprietary/mm-audio"

alias board="cd vendor/qcom/proprietary/common"

alias acdbdata="cd  vendor/qcom/proprietary/mm-audio/audcal/family-b/acdbdata"


#handy

alias path='echo -e ${PATH//:/\\n}'

alias now='date +"%T'

alias nowtime=now

alias nowdate='date +"%d-%m-%Y"'

# Stop after sending count ECHO_REQUEST packets #

alias ping='ping -c 5'

# Do not wait interval 1 second, go fast #

alias fastping='ping -c 100 -s.2'

#show open ports

alias ports='netstat -tulanp'

# distro specific  - Debian / Ubuntu and friends #

# install with apt-get

alias apt-get="sudo apt-get"

alias updatey="sudo apt-get --yes"


# update on one command

alias update='sudo apt-get update && sudo apt-get upgrade'

## pass options to free ##

alias meminfo='free -m -l -t'


## get top process eating memory

alias psmem='ps auxf | sort -nr -k 4'

alias psmem10='ps auxf | sort -nr -k 4 | head -10'


## get top process eating cpu ##

alias pscpu='ps auxf | sort -nr -k 3'

alias pscpu10='ps auxf | sort -nr -k 3 | head -10'


## Get server cpu info ##

alias cpuinfo='lscpu'

'Programming' 카테고리의 다른 글

file/directory 비교 tool - Meld  (0) 2015.09.24
git 과 repo  (0) 2015.09.19
codeaurora.org and linaro.org  (0) 2015.09.13
Natural Language Processing with Python  (0) 2015.08.24
파이썬 오디오 인식 - pydub, audiogrep  (0) 2015.08.24
Posted by 쁘레드