Thursday, March 3, 2011

Rails: Is there an equivalent to save_without_validation which skips after_save filters?

I have an after_save filter which I dont want to trigger in a specific instance. Is there a way to do this similar to save_without_validation?

Thanks,

From stackoverflow

win32 select all on edit ctrl (textbox)

I am creating my textbox with these options. I can copy/cut/paste/undo, but when i hit select A it doesnt select all. I can right click and click select all but ctrl a doesnt do anything, why?

  wnd = CreateWindow("EDIT", 0,
   WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL,
   x, y, w, h,
   parentWnd,
   NULL, NULL, NULL);
From stackoverflow
  • You need to capture that keystroke and do the select all yourself.

    Here is some C# code for use with a RichTextBox:

        protected override void OnKeyDown(KeyEventArgs e)
        {
            // Ctrl-A does a Select All in the editor window
            if (e.Control && (e.KeyCode == Keys.A))
            {
                this.SelectAll();
                e.Handled = true;
            }
        }
    

    Sorry, I don't have Win32 code for you.

    Sheldon : mine says "does not contain a defintion for "selectALL" and no extension method accepting an argument of a type could be found"
  • Could it be that something else is stealing Ctrl-A? Use Spy++ to verify that it reaches your edit control.

  • I tend to use MFC (forgive me) instead of win32 so I cannot answer this definitively, but I noticed this comment added to a page on an MS site concerning talking with an Edit control (a simple editor within the Edit control):

    The edit control uses WM_CHAR for accepting characters, not WM_KEYDOWN etc. You must Translate() your messages or you ironically won't be able to edit the text in the edit control.

    I don't know if this applies to BoltBait's response, but I suspect it does.

    (I found this at http://msdn.microsoft.com/en-us/library/bb775462(VS.85).aspx)

    acidzombie24 : wow thanks, i wanted to select all so i can copy text faster. That link showed me WM_COPY which copys the text needed. thanks!
  • Why not add an accelerator for Ctrl+a to SelectAll?

    acidzombie24 : i guess i could but thats more code for me to write and learn how to do. BTW i used WM_COPY instead which is what i wanted. To copy the text into the clipboard :)
  • Ctrl-A is not a built-in accelerator like Ctrl-C and Ctrl-V. This is why you see WM_CUT, WM_PASTE and WM_COPY messages defined, but there is no WM_SELECTALL.

    You have to implement this functionality yourself. I did in my MFC app like this:

    static BOOL IsEdit( CWnd *pWnd ) 
    {
        if ( ! pWnd ) return FALSE ;
        HWND hWnd = pWnd->GetSafeHwnd();
        if (hWnd == NULL)
         return FALSE;
    
        TCHAR szClassName[6];
        return ::GetClassName(hWnd, szClassName, 6) &&
             _tcsicmp(szClassName, _T("Edit")) == 0;
    }
    
    BOOL LogWindowDlg::PreTranslateMessage(MSG* pMsg) 
    {
        if(pMsg->message==WM_KEYDOWN)
        {
            if ( pMsg->wParam=='A' && GetKeyState(VK_CONTROL)<0 )
            {
                // User pressed Ctrl-A.  Let's select-all
                CWnd * wnd = GetFocus() ;
                if ( wnd && IsEdit(wnd) )
                    ((CEdit *)wnd)->SetSel(0,-1) ;
            }
        }   
        return CDialog::PreTranslateMessage(pMsg);
    }
    

    Note, I stole IsEdit from this page: http://support.microsoft.com/kb/145616

    I point that out partly because I want to give credit, and partly because I think the IsEdit function (comparing classname strings) is dorky and I want to give blame.

Regex/Textmate Confusion

I'm trying to create a Textmate snippet, but have run into some difficulties. Basically, I want to type in a Name and split it into its parts.

Example,

Bill Gates: (Bill), (bill), (Gates), (gates), (Bill Gates), (Bill gates), (bill Gates), (bill gates)

EDIT**

So I most certainly can produce these results quite simply if I was using a programming language. For example, I could split the words and then call the uppercase or lowercase functions to produce this output.

But in my situation I am using Textmate and it regular expression capabilities to create a tab snippet. I want to type some trigger key, ie doit, press tab and then type in a username. Then the ouput above will be created. This won't save me that much time, but I feel like I come across this sort of stuff in Textmate quite frequently and want to figure it out.

I have been using this as a reference, but still don't know how use regexps to be selective with the words and upper and lowercase the values (\u \U \l \L)

http://manual.macromates.com/en/snippets

From stackoverflow

Properly formatted example for Python iMAP email access?

tldr: Can someone show me how to properly format this Python iMAP example so it works?

from http://www.python.org/doc/2.5.2/lib/imap4-example.html "

import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()

" Assuming my email is "email@gmail.com" and the password is "password," how should this look? I tried "M.login(getpass.getuser(email@gmail.com), getpass.getpass(password))" and it timed out. Complete newb here, so it's very likely I missed something obvious (like creating an iMAP object first? Not sure).

From stackoverflow
  • Try:

    >>> import getpass
    >>> help(getpass)
    
  • Did you forget to specify the IMAP host and port? Use something to the effect of:

    M = imaplib.IMAP4_SSL( 'imap.gmail.com' )
    

    or,

    M = imaplib.IMAP4_SSL()
    M.open( 'imap.gmail.com' )
    
  • import imaplib
    
    # you want to connect to a server; specify which server
    server= imaplib.IMAP4_SSL('imap.googlemail.com')
    # after connecting, tell the server who you are
    server.login('email@gmail.com', 'password')
    # this will show you a list of available folders
    # possibly your Inbox is called INBOX, but check the list of mailboxes
    code, mailboxen= server.list()
    print mailboxen
    # if it's called INBOX, then…
    server.select("INBOX")
    

    The rest of your code seems correct.

    ocdcoder : Just to save others time who might see this...it's "IMAP4_SSL" not just "IMAP_SSL".
    ΤΖΩΤΖΙΟΥ : @ocdcoder: nice catch, thanks.
  • Here is a script I used to use to grab logwatch info from my mailbox. Presented at LFNW 2008 -

    #!/usr/bin/env python
    
    ''' Utility to scan my mailbox for new mesages from Logwatch on systems and then
        grab useful info from the message and output a summary page.
    
        by Brian C. Lane <bcl@brianlane.com>
    '''
    import os, sys, imaplib, rfc822, re, StringIO
    
    server  ='mail.brianlane.com'
    username='yourusername'
    password='yourpassword'
    
    M = imaplib.IMAP4_SSL(server)
    M.login(username, password)
    M.select()
    typ, data = M.search(None, '(UNSEEN SUBJECT "Logwatch")')
    for num in data[0].split():
        typ, data = M.fetch(num, '(RFC822)')
    #   print 'Message %s\n%s\n' % (num, data[0][1])
    
        match = re.search( "^(Users logging in.*?)^\w",
              data[0][1],
              re.MULTILINE|re.DOTALL )
        if match:
         file = StringIO.StringIO(data[0][1])
         message = rfc822.Message(file)
         print message['from']
         print match.group(1).strip()
         print '----'
    
    M.close()
    M.logout()
    

How can I read from an IO::Socket::INET filehandle only if there is a complete line?

When reading from a IO::Socket::INET filehandle it can not be assumed that there will always be data available on the stream. What techniques are available to either peek at the stream to check if data is available or when doing the read take no data without a valid line termination and immediately pass through the read?

From stackoverflow
  • Set the Blocking option to 0 when creating the socket:

    $sock = IO::Socket::INET->new(Blocking => 0, ...);
    
    Erick : File this one under 'RTFD... correctly'
  • Checkout IO::Select; it's very often what I end up using when handling sockets in a non-blocking way.

encode avi with given output file size

I have an avi file which i want to re-encode to fit on a cd of 650 mb how can i encode it, so that the file size does not succeed the given size, what program to use?

From stackoverflow
  • AutoGK can do this very effectively. Primarily designed for DVD **cough** backup purposes, but it will also accept AVI as source. It's more of a collection of opensource programs with a co-ordinating GUI, so don't worry when the installer installs several items.

  • I assume you want to do this programmatically:

    For Windows:

    You can use directshow to transcode your video by building a filter graph.

    Get (if you don't already have) the platform SDK for windows. Then browse here to check out some of the directshow examples which construct filter graphs for transcoding.

    To build you will need the base classes. You can build them here:

    C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\Multimedia\DirectShow\BaseClasses
    

    Then check out the examples here:

    C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\Multimedia\DirectShow
    

    You can also manually create filter graphs to get a hang for how they are used and see how these things make sense (such as the enumeration of the encoders you will learn about in the examples):

    C:\Program Files\Microsoft SDKs\Windows\v6.1\Bin\graphedt.exe
    

    Once you have gone this far and understand how directshow works you can use some math to figure out how to transcode your video to fit in the size you want. To do this you may want to look at how many frames/sec your input video is and how big each frame is.

    Different encoders work in different ways:

    Lets assume you are transcoding avi file to a smaller or lesser quality avi file. Look at your input frame sizes and fps to determine the whole file size, then use some algebra to figure how to either reduce frame size or reduce # of frames per second (or a combination of both) to achieve the desired size (which can be your input variable).

    As for other encoders you may want to see how they work. Lossy encoders such as mp4 perform estimations to find out what video has changed from frame to frame- and that information is stored in the file to reconstruct frames. You will have to read about how they work - or check to see how to use your particular encoder for more details.

    For Linux (and also windows):

    You can use ffmpeg which is an all-in-one for transcoding and other things to video. You can even find prebuilt exe of the command line application, although the main page does not host it (just the source). This application uses open source video libraries to do a lot of the video transcoding as well as many other things. If you can locate a good dependable exe file you should probably check this out if you want something that is easy to use for your application. Check out their homepage here.

    I hope this gets you started.

  • To make it fit a specific size, you must use an appropriate bit-rate.

    For fixed bit-rate video, to get the target bit-rate you would take the target size, in bits, and the length of the source in seconds.

    target bit-rate = size / seconds
    

    For example:

    seconds = (90mins * 60) = 5400
    size = ((650MB * 1024) * 8) = 5324800
    target bit-rate = ~986 kilobytes per second
    

    With variable bit-rate, things are rather more complicated. Not quite sure if there's a way to accurately make the output file a set size. The easiest way is to calculate the maximum bit-rate using the above method,

  • Calculate the number of seconds the AVI is. Then, take the file size and divide by the length. Convert to kilobits per second, and use that as your bitrate median. (Use Google to do the math and conversion easily.)

    You can weigh the video and audio bitrates as you desire. Usually 96 kbps is good enough with AAC, but you may want more or less. Experiment.

Techniques for Caching SQL Query Data

Having read some on this subject:

http://stackoverflow.com/questions/37157/caching-mysql-queries

http://www.danga.com/memcached/

My SQL Caching problem: http://www.petefreitag.com/item/390.cfm

http://framework.zend.com/manual/en/zend.cache.html#zend.cache.introduction

I have a very unique (narrow) set of Queries and I think I could implement some caching quite easily within my current FastCGI C API executables (NOT PHP).

Zend describes their framework as: cache records are stored through backend adapters (File, Sqlite, Memcache...) through a flexible system of IDs and tags.

HOW is this implemented?

Since the same query can return different results if the Table has been changed, I need to monitor not only Queries, but UPDATE, INSERT and DELETE also (MySQL for now) Since this only happens from one of my processes, I could easily add a statement that deletes the cache when a table change is made.

Only SELECTs are permitted by the clients, in which case I could hash the queries and store them in a hash table or btree index along with a pointer to the file containing the results.

Is there a better way?

From stackoverflow
  • Oh man, that is a good question. Being a .NET developer, I have been fortunate enough to not have to worry about this at all over the last 7 years. I don't have to worry because .NET implements a quite powerful caching mechanism to do what you want to do.

    There is no way to do this at a middle tier or presentation tier layer?

  • .NET is certainly convenient for fast development but it has some undesirable consequences as MS makes a deaf bedfellow!

    I also prefer to develop me own solutions as I can tailor them to my needs. I don't need a lot fo sophistication, just some mechanism to tie inbound queries to results sets on the server side. The presentation is don on the client side where a seperate database exists. Requests are really only to update the client side database so in answer to your question, the client side caching is allready implemented.

  • As I think about this, I realize that allthough Caching results to disk is faster, the load on the disk will increase significantly. In my case the DB is not that slow for queries, it is the memory required for the result set that is the biggest issue, up to 3MB per result set. This will eat up server memory in no time If I keep it all in mempry while the xfer proceeds

  • Do I only get one shot at an answer?