Friday, May 6, 2011

Generic-like behavior in PL/SQL procedure parameters

Suppose I have some data types defined in PL/SQL:

TYPE foo_t IS RECORD (...);
TYPE foo_table_t IS TABLE OF foo_t INDEX BY BINARY_INTEGER;

TYPE bar_t IS RECORD (...);
TYPE bar_table_t IS TABLE OF bar_t INDEX BY BINARY_INTEGER;

Is it possible for me to write a procedure capable of accepting any data type derived from TABLE (for example, either a foo_table_t or a bar_table_t) as a parameter? The procedure has no need for knowledge of the table's row types. A trivial example:

PROCEDURE remove_last(some_table ...) IS
BEGIN
    some_table.DELETE(some_table.LAST);
END;
From stackoverflow
  • Not directly. From the PL/SQL programmer's guide:

    "The actual parameter and its corresponding formal parameter must have compatible datatypes."

    PL/SQL does an implicit conversion of actual parameter datatypes to formal parameter datatypes. So, you could pass a number value to a procedure that wants a string, and it would work because you can do an implicit conversion.

    The best you could do would be to write overloaded procedures:

    PROCEDURE generic(foo IN OUT foo_t);

    PROCEDURE generic(bar IN OUT bar_t);

    Then you can call generic with either record type. This loses attractiveness in proportion to the number of record types to handle :-D

Generic List Equivalent of DataTable.Rows.Find using VB.NET?

I am converting DataTables to a generic list and need a quick and easy way to implement a Find function. It seems I am going to have to use a Predicate. Upon further investigation, I still can't seem to re-create the functionality. I have this predicate...

Private Function ByKey(ByVal Instance As MyClass) As Boolean
    Return Instance.Key = "I NEED THIS COMPARISON TO BE DYNAMIC!"
End Function

And then calling it like this...

Dim Blah As MyClass = MyList.Find(AddressOf ByKey)

But I have no way to pass in a key variable to this predicate to do the comparison, as I used to do with DataTable...

Dim MyRow as DataRow = MyTable.Rows.Find(KeyVariable)

How can I setup a predicate delegate function in VB.NET to accomplish this?

Do not recommend LINQ or lambdas because this is question is regarding .NET version 2.0.

From stackoverflow
  • Just put your predicate in a class instance:

    Public Class KeyMatcher
        Public Sub New(ByVal KeyToMatch As String)
           Me.KeyToMatch = KeyToMatch
        End Sub
    
        Private KeyToMatch As String
    
        Public Function Predicate(ByVal Instance As MyClass) As Boolean
           Return Instance.Key = KeyToMatch
        End Function
    End Class
    

    and then:

    Dim Blah As MyClass = MyList.Find(AddressOf New KeyMatcher("testKey").Predicate)
    

    We can even get a little fancy and make this generic:

    Public Interface IKeyed(Of KeyType)
        Public Key As KeyType
    End Interface
    
    Public Class KeyMatcher(Of KeyType)
        Public Sub New(ByVal KeyToMatch As KeyType)
           Me.KeyToMatch = KeyToMatch
        End Sub
    
        Private KeyToMatch As KeyType
    
        Public Function Predicate(ByVal Instance As IKeyed(Of KeyType)) As Boolean
           Return Instance.Key = KeyToMatch
        End Function
    End Class
    

    And then make your MyClass type implement the new IKeyed interface

    Josh Stodola : That looks like it will work. Thanks! I will do some testing and get back to ya.
    Josh Stodola : Thanks again! I ended up writing a generic class that also uses reflection so that it can be used to match any field to any value from any type. It is certainly not as efficient as without reflection, but I needed to flexibility.
  • Thank you great example vb.net list object find. The first example is working for 100%. But then I try make more generic class (your second example) I have a problems with interface defenition.

    Than I try add 'Public Key As KeyType' in interface defenition VS2008 say me what 'Interface members must be methods, properties, events, or type definitions.' In this case the code is not working. I was try add sub or function to interface but expect troubles to use interface in class.

    Could you please help me resolve this problem.

    Thank you for help and your time in advance.

    Regards, Andrejs.

Elementwise ifs in matlab - do they exist?

Say I have the following basic if-statement:

if (A ~= 0)
   % do something like divide your favorite number by A
else
   % do something like return NaN or infinity
end

The problem is that A is not a simple number but a vector. Matlab returns true if no element in A is 0. What I am looking for is a vectorized? way of perforimg the if-statement above for each element in A.

Actually, I simply want to do this as fast as possible.

From stackoverflow
  • Are you looking for all non-zero elements? You can do this a couple of ways.

    nonzero = find(A); % returns indicies to all non-zero elements of A
    y = x./A(nonzero); % divides x by all non-zero elements of A
                       % y will be the same size as nonzero
    

    Or for a one-liner, you can use a conditional in place of indicies

    y = x./A(A~=0); % divides x by all non-zero elements of A
    
    Mark Ruzon : This statement will cause y to be shorter than A if any element of A is zero, which may or may not be desired.
  • What you need to do is identify the elements you want to operate on. I would use FIND. I store the results in VI (Valid Indicies) and use that to populate the matrix.

    clear
    clc
    
    den = [2 0 2; 0 2 0; -2 -2 -2]
    num = ones(size(den));
    frac = nan(size(den));
    
    vi = (den ~=0)
    
    frac(vi) = num(vi)./den(vi)
    
    vi = (den == 0)
    
    frac(vi) = nan %just for good measure...
    
    Jason S : fyi: you don't need to use find, you can use boolean matrices directly. The value of find is to extract particular index values, and/or to save memory space if only a few values are true.
    MatlabDoug : removed FIND as requested by JASON S
  • Vectorized ifs don't exist, but there are some options. If you want to test for all or any elements true, use the all or any function.

    Here's one example of conditionally modifying values of a matrix:

    b = A ~= 0;      % b is a boolean matrix pointing to nonzero indices
                     % (b could be derived from some other condition,
                     %  like b = sin(A)>0
    A(b) = f(A(b))   % do something with the indices that pass
    A(~b) = g(A(~b)) % do something else with the indices that fail
    
    AnnaR : I didn't realise b (the boolean matrix) existed until you pointed it out. Thanks!
  • B = zeros(size(A));
    B(A~=0) = FAV./A(A~=0);  
    B(A==0) = NaN;
    
  • In general, to perform one operation on some elements of a matrix and another operation on the remaining elements, a one-line solution is:

    Z = B .* X + ~B .* Y;
    

    where B is a logical matrix. As an example,

    Z = (A == 0) .* -1 + (A ~= 0) .* A;
    

    copies A but assigns -1 everywhere that A is zero.

    However, because the question deals with infinity or NaNs, it can be done even more succinctly:

    Z = FAV ./ A; % produces inf where A == 0
    Z = (A ~= 0) .* FAV ./ A; % produces NaN where A == 0
    
    gnovice : +1: Clever one-liner!

Floating another div next to a main centered div

Ok so I have a website and the entire thing is wrapped in a container. This container is centered with margin:auto. I would like to float a piece of content to the right of this centered container and have it sort of stick to the side of it no matter if the user resizes the browser window, etc. I'm wondering if there's a real simple way to do this rather than adding another huge div, giving it width and floating the centered portion to the left and the piece of content to the right. Thanks!

From stackoverflow
  • Floating is the way to go for this. They will always stick together, unless the container is smaller than the sum of their widths.

    Tip: make sure your container is wide enough to hold both inner divs; if not, and the user has a narrower window, they will show one below the other.

    Nick Allen - Tungle139 : The only problem with this is that it will push the container div off center
    Seb : It will not, if you set margins accordingly.
  • Give the container div the property position: relative; place your floating div as the first child of the container div and give it

    #floatingDiv
    {
        position: absolute;
        top: 0;
        right: -{widthOfFloatedDiv};
    }
    

    I think that will work, but untested

    Okay so tested it and it works

    <div style="position: relative; width: 980px; margin: 0 auto; border: 1px solid #000; height: 400px;">
        <div style="position: absolute; top: 0; right: -200px; width: 200px;">
            <p>Floated DIV</p>
        </div>
        <p>container div</p>
    </div>
    
  • Piggybacking on @NickAllen, you want to use absolute positioning so that the width of the sidebar isn't included in the centering on the primary container.

    <style type="text/css">
        #container {
         position: relative;
         width: 500px;
         border: 1px solid #f00;
         margin: 0px auto;
        }
        #sidebar {
         position: absolute;
         width: 200px;
         right: -200px;
         border: 1px solid #0f0;
        }
    
    </style>
    
    <div id="container">
        <div id="sidebar">
         [ sidebar content ]<br>
         [ sidebar content ]<br>
        </div>
        [content]<br>
        [content]<br>
        [content]<br>
    </div>
    
    great_llama : ... with a caveat that because the sidebar is taken out of the layout calculations that you'll always want your primary content to be longer than the sidebar!
    Nick Allen - Tungle139 : very weird that we both went for a 200px sidebar in our examples! lol
    great_llama : 200px leaves plenty of padding for those 160 x 600 banner ads... =)
  • Maybe I'm misunderstanding your question, but isn't this what you want:

    <div id="container">
        <div id="sidebar">
        some content
        </div>
    </div>
    
    #container {
        width: 960px;
        margin: 0px auto;
    }
    
    #sidebar {
        float: right;
    }
    

ASP.NET - Internal messaging system

I want to implement a messaging system in my Web application similar to the one Chase and Facebook have on their websites. Should I develop this on my own, or should I find a 3rd party control or other solution? Would google provide some sort of API to make this easy? I'm leaning towards developing this on my own because it probably won't involve too much but wanted to know my options.

All suggestions/comments are appreciated!

From stackoverflow
  • In that case it would be much better to build a messaging system of your own.

Bus error vs Segmentation fault

Difference between a bus error and a segmentation fault? Can it happen that a program gives a seg fault and stops for the first time and for the second time it may give a bus error and exit ?

From stackoverflow
  • I assume you're talking about the SIGSEGV and SIGBUS signals defined by Posix.

    SIGSEGV occurs when the program references an invalid address. SIGBUS is an implementation-defined hardware fault. The default action for these two signals is to terminate the program.

    The program can catch these signals, and even ignore them.

  • For instance, a bus error might be caused when your program tries to do something that the hardware bus doesn't support. On SPARCs, for instance, trying to read a multi-byte value (such as an int, 32-bits) from an odd address generated a bus error.

    Segmentation faults happen for instance when you do an access that violate the segmentation rules, i.e. trying to read or write memory that you don't own.

    Thunderboltz : what do mean when you say "read or write memory that you don't own ? " when you do a malloc you have allocated like say 5 bytes of memory. If you read/write memory you don't own it does not give you a Seg fault in C.
    Geek : On the contrary overwriting a memory owned by some other object in the same address space gives a Segmentation fault ??
    David Schmitt : "What you own" on the OS level is typically much more than what the runtime surfaces (e.g. via malloc) to you. Thus there is much space for memory to access which you own, but still shouldn't and there is much address space which you may read, but not write (most mapped libraries) as well as specific functions to write protect memory regions (mprotect).
    David Schmitt : @Geek: the OS has no way of knowing "who" is doing the write within the same address space. Thus it cannot protect you from overwriting memory within the same program. That's the reason why most security exploits work.
    unwind : I obviously suck, compared to Pax and Bastien. :) But yeah, @Thunderboltz, as other commenters (and P&B) explained, segfaults happen when you try to access memory that doesn't belong to you.
  • On most architectures I've used, the distinction is that:

    • a SEGV is caused when you access memory you're not meant to (e.g., outside of your address space).
    • a SIGBUS is caused due to alignment issues with the CPU (e.g., trying to read a long from an address which isn't a multiple of 4).
    bk1e : Memory mapped files can also generate SIGBUS.
  • This would be a dup of What is a bus error?, if it weren't for the

    Can it happen that a program gives a seg fault and stops for the first time and for the second time it may give a bus error and exit ?

    part of the question. You should be able to answer this for yourself with the information found here.


    Insanity: doing the same thing over and over again and expecting different results.
    -- Albert Einstein


    Of course, taking the question literally...

    #include <signal.h>
    #include <stdlib.h>
    #include <time.h>
    #include <unistd.h>
    int main() {
        srand(time(NULL));
        if (rand() % 2)
            kill(getpid(), SIGBUS);
        else
            kill(getpid(), SIGSEGV);
        return 0;
    }
    

    Tada, a program that can exit with a segmentation fault on one run and exit with a bus error on another run.

  • Interpreting your question (possibly incorrectly) as meaning "I am intermittently getting a SIGSEGV or a SIGBUS, why isn't it consistent?", it's worth noting that doing dodgy things with pointers is not guaranteed by the C or C++ standards to result in a segfault; it's just "undefined behaviour", which as a professor I had once put it means that it may instead cause crocodiles to emerge from the floorboards and eat you.

    So your situation could be that you have two bugs, where the first to occur sometimes causes SIGSEGV, and the second (if the segfault didn't happen and the program is still running) causes a SIGBUS.

    I recommend you step through with a debugger, and look out for crocodiles.

  • SIGBUS will also be raised if you mmap() a file and attempt to access part of the mapped buffer that extends past the end of the file, as well as for error conditions such as out of space. If you register a signal handler using sigaction() and you set SA_SIGINFO, it may be possible to have your program examine the faulting memory address and handle only memory mapped file errors.

How to react to Excel events in Ruby?

I can find 10^1000 examples of scripting Excel using Ruby, but I can't for the life of me figure out how to have Ruby react to events in Excel. I'm trying retrieve the contents of a row in a worksheet when it's selected, but such an event-based retrieval I can't find any methods or examples for.

From stackoverflow
  • Use the *WIN32OLE_EVENT.new* method to create an OLE Event object, then call its *on_event* method. Call the *WIN32OLE_EVENT.message_loop* method to launch the event-monitoring loop.

    Here's an example that prints out the selected range's value, then halts event monitoring before the workbook is saved:

    require 'win32ole'
    
    def exit_event_loop
        $LOOP = false
    end
    
    xl = WIN32OLE.connect('Excel.Application')
    wb = xl.ActiveWorkbook
    
    ev = WIN32OLE_EVENT.new(wb, 'WorkbookEvents')
    ev.on_event('SheetSelectionChange') do
        range = xl.Selection
        puts(range.Value)
        STDOUT.flush
    end
    
    ev.on_event('BeforeSave') do
        exit_event_loop
    end
    
    $LOOP = true
    while $LOOP
        WIN32OLE_EVENT.message_loop
        sleep 0.1
    end
    

    Hope that helps.