港股即時

Economic Calendar

Friday, September 29, 2017

Python With statement


As most other things in Python, the with statement is actually very simple, once you understand the problem it’s trying to solve. Consider this piece of code:
    set things up
    try:
        do something
    finally:
        tear things down
Here, “set things up” could be opening a file, or acquiring some sort of external resource, and “tear things down” would then be closing the file, or releasing or removing the resource. The try-finally construct guarantees that the “tear things down” part is always executed, even if the code that does the work doesn’t finish.
If you do this a lot, it would be quite convenient if you could put the “set things up” and “tear things down” code in a library function, to make it easy to reuse. You can of course do something like
    def controlled_execution(callback):
        set things up
        try:
            callback(thing)
        finally:
            tear things down

    def my_function(thing):
        do something

    controlled_execution(my_function)
But that’s a bit verbose, especially if you need to modify local variables. Another approach is to use a one-shot generator, and use the for-in statement to “wrap” the code:
    def controlled_execution():
        set things up
        try:
            yield thing
        finally:
            tear things down

    for thing in controlled_execution():
        do something with thing
But yield isn’t even allowed inside a try-finally in 2.4 and earlier. And while that could be fixed (and it has been fixed in 2.5), it’s still a bit weird to use a loop construct when you know that you only want to execute something once.
So after contemplating a number of alternatives, GvR and the python-dev team finally came up with a generalization of the latter, using an object instead of a generator to control the behaviour of an external piece of code:
    class controlled_execution:
        def __enter__(self):
            set things up
            return thing
        def __exit__(self, type, value, traceback):
            tear things down

    with controlled_execution() as thing:
         some code
Now, when the “with” statement is executed, Python evaluates the expression, calls the __enter__ method on the resulting value (which is called a “context guard”), and assigns whatever __enter__ returns to the variable given by as. Python will then execute the code body, and no matter what happens in that code, call the guard object’s __exit__ method.
As an extra bonus, the __exit__ method can look at the exception, if any, and suppress it or act on it as necessary. To suppress the exception, just return a true value. For example, the following __exit__ method swallows any TypeError, but lets all other exceptions through:
    def __exit__(self, type, value, traceback):
        return isinstance(value, TypeError)
In Python 2.5, the file object has been equipped with __enter__ and __exit__ methods; the former simply returns the file object itself, and the latter closes the file:
    >>> f = open("x.txt")
    >>> f
    <open file 'x.txt', mode 'r' at 0x00AE82F0>
    >>> f.__enter__()
    <open file 'x.txt', mode 'r' at 0x00AE82F0>
    >>> f.read(1)
    'X'
    >>> f.__exit__(None, None, None)
    >>> f.read(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: I/O operation on closed file
so to open a file, process its contents, and make sure to close it, you can simply do:
with open("x.txt") as f:
    data = f.read()
    do something with data


http://effbot.org/zone/python-with-statement.htm

Monday, September 25, 2017

send e-mail via python


http://naelshiab.com/tutorial-send-email-python/

E-mail RFC821, RFC2821

RFC822

SMTP Procedure

  • Mail command
    • MAIL <SP> FROM:<reverse-path> <CRLF>
      •          This command tells the SMTP-receiver that a new mail transaction is starting and to reset all its state tables and buffers, including any recipients or mail data.  It gives the reverse-path which can be used to report errors.  If accepted, the receiver-SMTP returns a 250 OK reply.
      • The <reverse-path> can contain more than just a mailbox.  The <reverse-path> is a reverse source routing list of hosts and source mailbox.  The first host in the <reverse-path> should be the host sending this command.
  • RCPT command
    • RCPT <SP> TO:<forward-path> <CRLF>
      • This command gives a forward-path identifying one recipient. If accepted, the receiver-SMTP returns a 250 OK reply, and stores the forward-path.  If the recipient is unknown the receiver-SMTP returns a 550 Failure reply.  This second step of  the procedure can be repeated any number of times.
      • The <forward-path> can contain more than just a mailbox.  The <forward-path> is a source routing list of hosts and the destination mailbox.  The first host in the <forward-path> should be the host receiving this command.
      • (Forwarding) some cases where the destination information in the  <forward-path> is incorrect, but the receiver-SMTP knows the correct destination.  In such cases, one of the following replies should be used to allow the sender to contact the correct destination. 
        • 251 User not local; will forward to <forward-path>
        • 551 User not local; please try <forward-path>
      • VERIFYING AND EXPANDING
        • VRFY command, the string is a user name, and the response may include the full name of the user and must include the mailbox of the user.
          • E.G
            • S: VRFY Smith
            • R: 250 Fred Smith <Smith@USC-ISIF.ARPA>
            • S: VRFY Smith
            • R: 251 User not local; will forward to <Smith@USCISIQ.ARPA>
            • S: VRFY Jones
            • R: 550 String does not match anything.
            • S: VRFY Jones
            • R: 551 User not local; please try <Jones@USC-ISIQ.ARPA>
            • S: VRFY Gourzenkyinplatz
            • R: 553 User ambiguous.
        • EXPN command, the string identifies a mailing list, and the multiline response may include the full name of the users and must give the mailboxes on the mailing list.
          • E.G.
            • S: EXPN Example-People
            • R: 250-Jon Postel <Postel@USC-ISIF.ARPA>
            • R: 250-Fred Fonebone <Fonebone@USC-ISIQ.ARPA>
            • R: 250-Sam Q. Smith <SQSmith@USC-ISIQ.ARPA>
            • R: 250-Quincy Smith <@USC-ISIF.ARPA:Q-Smith@ISI-VAXA.ARPA>
            • R: 250-<joe@foo-unix.ARPA>
            • R: 250 <xyz@bar-unix.ARPA>
            • S: EXPN Executive-Washroom-List
            • R: 550 Access Denied to You.
  • Data command
    • DATA <CRLF>
      • If accepted, the receiver-SMTP returns a 354 Intermediate reply and considers all succeeding lines to be the message text. When the end of text is received and stored the SMTP-receiver sends a 250 OK reply.
      • Since the mail data is sent on the transmission channel the end of the mail data must be indicated so that the command and reply dialog can be resumed.  SMTP indicates the end of the mail data by sending a line containing only a period.  A transparency procedure is used to prevent this from interfering with the user's text.
      • Mail data includes the memo header items such as Date, Subject, To, Cc, From.
      • SENDING AND MAILING
        • The main purpose of SMTP is to deliver messages to user's mailboxes.  A very similar service provided by some hosts is to deliver messages to user's terminals (provided the user is active on the host).  The delivery to the user's mailbox is called "mailing", the delivery to the user's terminal is called "sending".  Because in many hosts the implementation of sending is nearly identical to the implementation of mailing these two functions are combined in SMTP.
        • The following three command are defined to support the sending options.
          • SEND <SP> FROM:<reverse-path> <CRLF>
            • The SEND command requires that the mail data be delivered to the user's terminal.  If the user is not active (or not accepting terminal messages) on the host a 450 reply may returned to a RCPT command.  The mail transaction is successful if the message is delivered the terminal.
          • SOML <SP> FROM:<reverse-path> <CRLF>
            • The Send Or MaiL command requires that the mail data be delivered to the user's terminal if the user is active (and accepting terminal messages) on the host.  If the user is not active (or not accepting terminal messages) then the mail data is entered into the user's mailbox.  The mail transaction is successful if the message is delivered either to the terminal or the mailbox.
      • OPENING AND CLOSING
        • At the time the transmission channel is opened there is an exchange to ensure that the hosts are communicating with the hosts they think they are.
          • Opening
            • HELO <SP> <domain> <CRLF>
            • E.G.
              • R: 220 BBN-UNIX.ARPA Simple Mail Transfer Service Ready
              • S: HELO USC-ISIF.ARPA
              • R: 250 BBN-UNIX.ARPA
          • Closeing
            • QUIT <CRLF>
            • E.G.
              • S: QUIT
              • R: 221 BBN-UNIX.ARPA Service closing transmission channel
      • RELAYING
        • The forward-path may be a source route of the form"@ONE,@TWO:JOE@THREE", where ONE, TWO, and THREE are hosts.  This form is used to emphasize the distinction between an address and a route.  The mailbox is an absolute address, and the route is information about how to get there.  The two concepts should not be confused.



電子郵件的結構

  • 如傳統郵一樣,由「信封」和「信件」組成,但整個郵件是一個純文本檔案。純文件檔案按照RFC822標準框架組成,只要按此框架組成純文件檔案,就成為標準郵件。
  • RFC822:
    • 純文件檔案頭幾行是「信封」,然後一個空行後便是「信件」。
    • RFC822 規定字符必須為ASCII
    • 信封的正式名稱為 Header 。
    • Header由幾個部份 (header field) 組成
      • field-name: [field-body] CRLF
        • field name 是段名,RFC822定義了一部份段名及其語義,應用程序可自定義新段名,但不得與已有段名重覆。
        • field body 是段體, 與段名用 冒號分隔。
          • E.g.
          • From: Derek Wai <Group @ Hosta>
          • Sender: Haze@Hostb
          •  Reply-To:Hazze@Hostb
          • From, Sender, Reply-To 是 field name, 後面是field body
        • CRLF : 每個field 理論上是一行,若多於一行,則新一行要有一 space 或 tab 來代表是上一行的延續,稱Carriage-Return Line-Feed。
          • E.g.
          • Received: from m15-40.126.com (220.181.15.40)CRLF by localhost with SMTP;
          • Received: from m15-40.126.com (220.181.15.40)
          •  by localhost with SMTP;
    • 頭段功能
      1. 源地址
        •     From: mailbox   //  mail box 可以 username@domain, 或 user < user@doman>//
        •     Sender: mailbox  //若信件並非由寫信人的地址發出,則必須用sender再加上from。 即 sender:  1@abc.com  from 2@abc.com //
        •     Return-path: < [route] local-part@domain >  //由最後的轉發站回送郵件給發信人的路由。可選項route 指出路由,形式為domain_1, @domain_2, ... ..., @domian_n//
        •     Reply-To: mailbox
        •     Received[from domain][by domain][via atom][with atom]
          • [id msg-id][for local-part@domain]
          • ; date-time

http://003317.blog.51cto.com/2005292/611104

Monday, September 11, 2017

VBA

' ------------------------------------------------------------
' 查看目前開啟excel檔案數量

Dim OpenCnt as Integer
OpenCnt = Application.Workbooks.Count

' ------------------------------------------------------------
' 依序查已開檔名 - 方法一

    Dim i As Integer
    For i = 1 To Workbooks.Count
        MsgBox i & " " & Workbooks(i).Name
    Next

' ------------------------------------------------------------
' 依序查已開檔名 - 方法二

Dim my Sheet As WorkSheet
For Each mySheet In Worksheets
    MsgBox mySheet.Name
Next mySheet

' ------------------------------------------------------------
' 開啟特定檔案 - 方法一

filename = "C:\VBA\test.xls"
Workbooks.Open filename

' ------------------------------------------------------------
' 開啟特定檔案 - 方法二

Dim filename As String
filename = "C:\VBA\test.xls"

    Dim sn As Object
    Set sn = Excel.Application
    sn.Workbooks.Open filename
    ' sn.Workbooks(filename).Close ' 關閉
    Set sn = Nothing

' ------------------------------------------------------------
' 關閉指定檔案, 不提示訊息

    Dim filename As String
    filename = "Test.xls"  ' 這裡只可以給短名,給全名會錯
    ' 假設 Test.xls 已於開啟狀態

    Application.DisplayAlerts = False ' 關閉警告訊息
    Workbooks(filename).Close
    Application.DisplayAlerts = True ' 再打開警告訊息

' ------------------------------------------------------------
' 關閉所有開啟檔案, 但留下主視窗

Workbooks.Close

' ------------------------------------------------------------
' 關閉 excel 程式

Application.Quit

' ------------------------------------------------------------
' 直接進行存檔

Dim filename As String
filename = "a.xls" ' 只可為短檔名
WorkBooks(filename).Save


' ------------------------------------------------------------
' 指定檔名進行另存新檔,並關閉

' 假設要將 "a.xls" 存成 "C:\b.xls"

Application.DisplayAlerts = False ' 關閉警告訊息
Workbooks("a.xls").SaveAs "C:\b.xls" ' 另存新檔
Workbooks("b.xls").Close ' 關閉 b.xls
Application.DisplayAlerts = True ' 開啟警告訊息

' ------------------------------------------------------------
' 指定當前活頁簿

Dim Caption as String
Caption = "a.xls"
Workbooks(Caption).Activate ' 將視窗切到 a.xls

' ------------------------------------------------------------
Data Type Cheat

End with:

$ : String
% : Integer (Int32)
& : Long (Int64)
! : Single
# : Double
@ : Decimal

Start with:

&H : Hex
&O : Octal
' ------------------------------------------------------------

Monday, September 4, 2017

SQL (Structured Query Language)

SQL四大語言:


  • 資料定義語言 (DDL - Data Definition Language)
    • 定義語言到底是要定義什麼東西,CREATE、ALTER與DROP這就是定義TABLE名稱
  • 資料操縱語言 (DML - Data Manipulation Language)
    • 操作語言就是要操作你的資料,當你有大量的資料要輸入怎麼做,這時候就有INSERT、UPDATE、DELETE,這三個東西其中兩個東西很可怕,因為命令打錯資料就是消失,所以UPDATE、DELETE使用時要非常的謹慎。
  • 資料查詢語言 (DQL - Data Query Language)
    • 當你都新增好資料後,當然就會需要做查詢動作
  • 資料控制語言 (DCL - Data Control Language)
  • (DTL- Data Transaction Language)