Friday, May 6, 2011

Configure Hibernate to use Oracle's SYS_GUID() for Primary Key

I am looking for a way to get hibernate to use oracle's SYS_GUID() function when inserting new rows. Currently my DB tables have SYS_GUID() as the default so if hibernate simply generated SQL that omited the value it should work.

I have everything working, but it is currently generating the UUID/GUID in code using the system-uuid generator:

@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(name = "PRODUCT_ID", unique = true, nullable = false)
public String getId() {
    return this.productId;
}

This is fine, but I would prefer that the guids were generated by the database so they will be sequential and potentially have better performance. Plus I would just like to know how to configure this.

I am using annotations for configuration, but xml configuration examples are awesome as well.

Here is a sample table definition (in case it matters):

CREATE TABLE SCHEMA_NAME.PRODUCT
(
    PRODUCT_ID RAW(16) DEFAULT SYS_GUID() NOT NULL,
    PRODUCT_CODE VARCHAR2(10 CHAR) NOT NULL,
    PRODUCT_NAME VARCHAR2(30 CHAR) NOT NULL,
    PRODUCT_DESC VARCHAR2(512 CHAR)
)

UPDATE:

Mat's sollution of using "guid" worked, here is the sql generated:

Hibernate: 
    select rawtohex(sys_guid()) 
    from dual
Hibernate: 
    insert into PRODUCT
    (PRODUCT_CODE, PRODUCT_DESC, LOB_ID, PRODUCT_NAME, PROVIDER_ID, PRODUCT_ID) 
    values (?, ?, ?, ?, ?, ?)


It seems that using the columns default value in an insert is not possible, so the choice is between an application generated guid and a database round trip.

From stackoverflow
  • I think you can do it by setting the generator to native. I'm not really sure how to do it in Hibernate but in NHibernate you'd do something like this in the XML:

    <id column="PRODUCT_ID">
      <generator class="native"/>
    </id>
    
    Adeel Ansari : "native" is sequence in Oracle. Therefore, I doubt it. But trying it out is not a bad idea.
    Adeel Ansari : By the way, you specified that you do this in NHibernate, but didn't specify the database and thats the primary much concern here.
    cdmckay : There's a very good chance I'm wrong, I've just started to use NHibernate.
  • Hi Ryan. You might be able to use the "guid" generator. See this post from the Hibernate forum. It looks like they added support for Oracle using SYS_GUID() a while back, but the documentation still says they only support SQL Server and MySQL.

    I haven't worked with JPA annotations yet, but here is an example using XML configuration:

    <id name="PRODUCT_ID">
      <generator class="guid" />
    </id>
    

    EDIT: In regards to your second question, I think you are asking why Hibernate can't do something like this:

    INSERT INTO PRODUCT (PRODUCT_ID, /* etc */)
    SELECT SYSGUID(), /* etc */
    

    The reason is that Hibernate must know what the object's ID is. For example, consider the following scenario:

    1. You create a new Product object and save it. Oracle assigns the ID.
    2. You detach the Product from the Hibernate session.
    3. You later re-attach it and make some changes.
    4. You now want to persist those changes.

    Without knowing the ID, Hibernate can't do this. It needs the ID in order to issue the UPDATE statement. So the implementation of org.hibernate.id.GUIDGenerator has to generate the ID beforehand, and then later on re-use it in the INSERT statement.

    This is the same reason why Hibernate cannot do any batching if you use a database-generated ID (including auto-increment on databases that support it). Using one of the hilo generators, or some other Hibernate-generated ID mechanism, is the only way to get good performance when inserting lots of objects at once.

    Ryan Cook : This worked but produced some extra sql, see my update. Thanks for your time.
    Matt Solnit : Hi Ryan. I edited my answer to try to respond to your follow-up question.
    Ryan Cook : FYI: Doing this via annotation is simple: @GenericGenerator(name = "guid", strategy = "guid")

Renaming XML nodes using E4X in AS3

I have an XML object in AS3 that is formatted as follows:

<data>
  <nodes>
    <item></item>
    <item></item>
    ...
  </nodes>
  <nodes>
    <item></item>
    <item></item>
    ...
  </nodes>
  ...
</data>

My problem is I want to rename the node names("nodes" and "item") to something more relevant e.g. "nodes" could be "author", and "item" could be "book".

So what would be the best way to do this with E4X in AS3?

From stackoverflow
  • Hi,

    As far as I know there is no way to do this natively within ActionScript, however here is a simple function that will accomplish just that. First I am converting it to a string, then using a simple regular expression to find and replace all instances.

    function replaceAll(findTag:String, replaceWith:String, source:XML):XML
     {
      var xmls:String = source.toXMLString();
      var findPattern:RegExp = new RegExp(findTag, "g");
      xmls = xmls.replace(findPattern, replaceWith);
      return new XML(xmls);
     }
    

    Hope it helps.

  • you can use the setName() method of XML Object in AS3.

    example:

       //extract all nodes named "nodes"
    
        var l:XMLList=data..nodes;
        for each(var n:XML in l){
           n.setName("new_node_name");
        }
    
        //extract all nodes named "item"
    
        var l2:XMLList=data..item;
        for each(var n2:XML in l2){
           n2.setName("new_item_name");
        }
    
    TandemAdam : I was hoping there would be something like: data..nodes.setName("new_node_name"); But that would be asking too much. Thanks!

How to select a row in table using jquery?

I have created a table in my application, I want to select (change background color) whole row on click of a checkbox, same as gmail is doing, When we click checkbox in gmail, the whole row becomes yellow.

<table>
<tbody>
<tr>
<td><input type="checkbox" name="chk" id="chk" /></td>
<td>My Name</td>
<td>Description of the job</td>
</tr>
</tbody>
</table>

Please tell me how to do the same in jquery ?

Thanks

From stackoverflow
  • $(function() {
      $("#chk").click(function() {
        $(this).parents("tr").toggleClass("diffColor");
      });
    });
    

    Create a CSS class (called "diffColor" above) and add the background color that way, something like:

    <style type="text/css">
    tr.diffColor td { background-color: yellow; }
    </style>
    

    Don't set CSS attributes directly. Use classes where possible.

    ichiban : Good explanation +1
  • Cletus's answer is right, but I think can be improved a little:

    $(function() {
        $("#chk").click(function() {
            $(this)
                .parents("tr:first")
                .toggleClass("diffColor", this.checked)
            ;
        });
    });
    

    The only real differences here is:

    1. that it only selects the first parent <tr>. ...you never know where your code might end up, plus, in theory it'll be a couple of ticks faster.
    2. it checks the new value of the checkbox and adds or removes the class as required. Without checking this, some other code might change the "diffColour" class on the row and then your checkbox would be inverted, if you know what i mean.

    Also, you might consider binding that function to the change handler as well:

    $('#chk').bind('click change', function() { // ... etc
    

BASIC Object-Relation Mapping question asked by a noob

I understand that, in the interest of efficiency, when you query the database you should only return the columns that are needed and no more.

But given that I like to use objects to store the query result, this leaves me in a dilemma:

If I only retrieve the column values that I need in a particular situation, I can only partially populate the object. This, I feel, leaves my object in a non-ideal state where only some of the properties and methods are available. Later, if a situation arises where I would like to the reuse the object but find that the new situation requires a different but overlapping set of columns to be returned, I am faced with a choice.

Should I reuse the existing SQL and add to the list of selected columns the additional fields that are required by the new situation so that the same query and object mapping logic can be reused for both? Or should I create another method that results in the execution of a slightly different SQL which results in the populating of only those object properties that were returned by the 2nd query?

I strongly suspect that there is no magic answer and that the answer really "depends" on the situation but I guess I am looking for general advice. In general, my approach has been to either return all columns from the queried table or to add to the query the additional columns as they are needed but to reuse the same SQL (and mapping code) that is, until performance becomes a concern. In general, I find that unless you are retrieving a large number of row - and I usually am not - that the cost of adding additional columns to the output does not have a noticable effect on performance and that the savings in development time and the simplified API that result are a good trade off.

But how do you deal with this situation when performance does become a factor? Do you create methods like

Employees.GetPersonalInfo Employees.GetLittleMorePersonlInfoButMinusSalary etc, etc etc

Or do you somehow end up creating an API where the user of your API has to specify which columns/properties he wants populated/returned, thereby adding complexity and making your API less friendly/easy to use?

Let's say you want to get Employee info. How many objects would typically be involved?

1) an Employee object 2) An Employees collection object containing one Employee object for each Employee row returned 3) An object, such as EmployeeQueries that returns contains methods such as "GetHiredThisWeek" which returns an Employees collection of 0 or more records.

I realize all of this is very subjective, but I am looking for suggestions on what you have found works best for you.

From stackoverflow
  • ...the cost of adding additional columns to the output does not have a noticable effect on performance...

    Right. I don't quite understand what "new situation" could arise, but either way, it would be a much better idea (IMO) to get all the columns rather than run multiple queries. There isn't much of a performance penalty at all for getting more columns than you need (although the queries will take more RAM, but that shouldn't be a big issue; besides, hardware is cheap). Also, you'd save yourself quite a bit of development time.

    As for the second part of your question, it's really up to you. As an example, Rails takes more of a "usability first, performance last" approach, but that may not be what you want. It just depends on your needs. If you're willing to sacrifice a little usability for performance, by all means, go for it. I would.

  • I would say make your application correct first, then worry about performance in this case.

    You could be optimizing away your queries only to realize you won't use that query anyway. Create the most generalized queries that your entire app can use, and then as you are confident things are working properly, look for problem areas if needed.

    It is likely that you won't have a great need for huge performance up front. Some people say the lazy programmers are the best programmers. Don't over-complicate things up front, make a single Employee object.

    If you find a need to optimize, you'll create a method/class, or however your ORM library does it. This should be an exception to the rule; only do it if you have reason to do so.

  • If you are using your Objects in a "row at a time" CRUD type application, then, by all means copy all the columns into your object, the extra overhead is minimal, and you object becomes truly re-usable for any program wanting row access to the table.

    However if your SQL is doing a complex join or returning a large set of rows, then request precisely and only what you want. You get two performance penalties here, one handling each column each time will eat up cpu for no benefit, and, two most DBMS systems have a bag of tricks for optimising queries (such as index only access) which can only be used if you specify precisely which columns you want.

    There is no reuse issue in most of these cases as scan/search processes tend to very specific to a particular use case.

Carrying over dependencies in Maven

I am working on 3 maven projects. They're all separate projects, but they share a common base framework. Let's call the framework A and its dependencies B and C.

There is a library L that A depends on. Any package that uses A will also need to use L, and it will need to use the same version of L that A does. For this reason, I would like a way to specify L in A's pom and only in A's pom. I don't want to have to go and edit B and C's poms every time I upgrade L.

Is there a way to do this? There's not a parent pom that A, B, and C share.

From stackoverflow
  • If B and C also uses library L directly then you should define that in B and C pom file. Since its a direct dependency it should be clear by looking into POM file.

    Second option is if library L is common to A, B and C projects then you should define a parent pom.

how to set permission to device /dev/rfcomm0 ?

I am trying to run kannel bearer box but i got error something like could not write/read device. I think kannel doest have permission to read/write bluetooth device /dev/rfcomm0

Thanks for reading. Any help would be appreciated.

From stackoverflow
  • with root account do

    chmod a+rw /dev/rfcomm0
    
  • If you know which program is generating the error message, run the program with strace and see which system call yields the error. If it's open, then the chmod solution recommended by Francis should do the trick. If it's read or write, then you should investigate further: is there a problem in the kernel or the appication code.

An impasse with hooking calls to HeapAlloc for a memory tracking application.

I am writing a memory tracking application that hooks all the calls to HeapAlloc using IAT patching mechanism. The idea is to capture all the calls to HeapAlloc and get a callstack.

However I am currently facing a problem with getting the callstack using DBGHELP Apis. I found that the dbghelp dll itself is linking to MSVCRT dll and this dependancy results in a recursive call. When I try to get a callstack for any of the calls from the target application, dbghelp internally calls some method from MSVCRT that again calls HeapAlloc. And since I have already patched MSVCRT it results in an infinite loop.

Has anyone faced this problem and solved it ? Is there any way out of this impasse?

From stackoverflow
  • What about using some real memory tracking products like GlowCode?

  • This is a standard problem in function interception code. We had a similar issue with a logging library that used shared memory for storing log level information, while the shared memory library had to log information.

    The way we fixed it could be applied to your situation, I believe.

    In your intercept code, maintain a static flag that indicates whether or not you're in the middle of an intercept. When your intercept is called and the flag isn't set, set the flag then do what you currently do, including calling DbgHelp, then clear the flag.

    If your intercept is called while the flag is set, only call the back-end HeapAlloc code without doing any of the other stuff (including calling DbgHelp which is what's causing your infinite recursion).

    Something along the lines of (pseudo-code):

    function MyHookCode:
        static flag inInterceptMode = false
        if inInterceptMode:
            call HeapAlloc
            return
        inInterceptMode = true
        call DbgHelp stuff
        call HeapAlloc
        inInterceptMode = false
        return
    
    function main:
        hook HeapAlloc with MyHookCode
        : : :
        return
    
    Canopus : Thanks for the idea, static may not help me as the calls can come from multiple threads. I think i can use TLS for this purpose.
    paxdiablo : Assuming that TLS is the Windows variant of thread-specific data (i.e., a 'static' per thread), then yes, I would think so. But is HeapAlloc and DbgHelp thread-specific or process-wide? If the latter, you really need a flag that crosses thread boundaries (and is mutex-protected).
    Canopus : Thanks again for the hint. I just found that DbgHelp is not thread-safe. So I also need to have a guard.

Rotating Div using javascript

Hi everyone

Here is a link: http://www.avineon.com/

Open this link see on the top. Four images are rotating.

I need something similiar using Javascript.

Is it possible by using Javascript.

Thanks & Regards

Ravi Kumar

From stackoverflow
  • I don't think you'll have much luck if you try to do that in pure javascript. It might be possible using the emerging canvas and SVG libraries such as Raphael, but you'll still have cross-browser issues. That site used Flash, and I'd recommend using that if you wanted such an effect.

    ...why you'd want that on your website is another story though...

    alex : +1 agree with that last point!
  • You could so something similar, but not exact.

    Transparency = Supported in FF, Safari, IE7+ Changing image width = Place image in div with this Css

    .class img {
    display: block;
    width: 100%;
    height: 100%
    }
    

    This will make the image stretch to fill the .class div. You can then use JS to make this div narrower like the carousel does, and the image contained will animate within the div.

    You would then need to track the mouse locations to determine how fast it spins.

    You can use an equation using cosine for smooth acceleration from the far ends (IIRC)

    You will not however be able to get the images in reverse, unless you create a copy in a server side language or use canvas.

  • Your best bet would not be to attempt to render something in actual 3D, but rather to use visual tricks to approximate a 3D effect. That is, use perspective / image deformation to make it look like a cube is rotating, similar to what is implemented at this page, which has a better explanation of the math involved.

    Really, though, you're probably better off just using Flash.

  • That effect is possible in JavaScript simply by modifying each of the images width, height, and left styles over time. It's an involved script, but only needs to interpolate those three styles on the each of the image elements.

    To get the rotation effect, decrement the width style of the image in a setInterval function while moving the left style property. There is a slight decrement on the height also.

    You'll need two images for each side, a front and reverse. When the width decrements to zero, swap the image with it's flipped version and start incrementing the width.

    Alternatively use Webkit's, and Firefox's transform css properties.

    Or try one of these coverflow components that look similar: Protoflow, ImageFlow

  • if (document.all || document.getElementById){ //if IE4 or NS6+ document.write('\n'); document.write('.dyncontent{display: none; width: 728px; height: 90px;}\n'); document.write(''); } var curcontentindex=0; var messages=new Array(); function getElementByClass(classname){ var inc=0; var alltags=document.all? document.all : document.getElementsByTagName("*"); for (i=0; i first second Third

hpricot with firebug's XPath

I'm trying to extract some info from a table based website with hpricot. I get the XPath with FireBug.

/html/body/div/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td[2]/table/tbody/tr[3]/td/table[3]/tbody/tr

This doesn't work... Apparently, the FireBug's XPath, is the path of the rendered HTML, and no the actual HTML from the site. I read that removing tbody may resolve the problem.

I try with:

/html/body/div/table/tr/td/table/tr[2]/td/table/tr/td[2]/table/tr[3]/td/table[3]/tr

And still doesn't work... I do a little more research, and some people report they get their XPath removing the numbers, so I try this:

/html/body/div/table/tr/td/table/tr/td/table/tr/td/table/tr/td/table/tr

Still no luck...

So I decide to do it step by step like this:

(doc/"html/body/div/table/tr").each do |aaa |
  (aaa/"td").each do | bbb|
        pp bbb
        (bbb/"table/tr").each do | ccc|
            pp ccc 
      end
  end
end

I find the info I need in bbb, but not in ccc.

What am I doing wrong, or is there better tool to scrap HTML with long/complex XPath.

From stackoverflow
  • You are probably better off using hpricot's CSS parsing instead of XPath. _why was talking about possibly depricating XPath at one point.

    Do you have a better example of the data? Do they use css tags that are easily referenced?

    It's much easier to search like:

    doc.search("#id_tag > table > tr.class_tag > td").each do |aaa|
        aaa.search("blah > blah").each do |bbb|
            bbb.inner_html
    

    There was an older page on _why's website (which I can't seem to find now) that was discussing hpricot, and some of the comments hinted at how the CSS version was a better choice over XPath when doing nested searches similar to what you are.

    Wish I could give a better answer, but I seriously recommend giving the CSS method a shot and see how it goes before tearing your hair out with XPath.

  • I'm now using css and I "figure" it with this great tool : www.selectorgadget.com

  • It's probably worth noting that Nokogiri uses the same API as Hpricot, but also supports XPath expressions.

  • Your problem is in XPather (or firebug XPath). Firefox i think is internally fixing badly formated tables to have tbody element even if in HTML there is none. Nokogiri is not doing that, instead it allows tr tag to be inside table.

    so there's a big chance your path looks to nokogiri like this:

    /html/body/div/table/tr/td/table/tr[2]/td/table/tr/td[2]/table/tr[3]/td/table[3]/tr
    

    and that's how nokogiri will accept it :)

    you might want to check out this

    require 'open-uri'
    require 'nokogiri'
    
    class String
      def relative_to(base)
        (base == self[0..base.length-1]) &&
          self[base.length..-1]
      end
    end
    
    module Importer
      module XUtils
        module_function
    
        def match(text, source)
          case text
          when String
            source.include? text
          when Regexp
            text.match(source)
          when Array
            text.all? {|tt| source.include?(tt)}
          else
            false
          end
        end
    
        def find_xpath (doc, start, texts)
          xpath = start
          found = true
    
          while(found)
            found = [:inner_html, :inner_text].any? do |m|
              doc.xpath(xpath+"/*").any? do |tag|
                tag_text = tag.send(m).strip.gsub(/[\302\240]+/, ' ')
                if tag_text && texts.all?{|text| match(text, tag_text)}
                  xpath = tag.path.to_s
                end
              end
            end
          end
    
          (xpath != start) && xpath
        end
    
        def fetch(url)
          Nokogiri::HTML(open(url).read)
        end
      end
    end
    

    I wrote this little module to help me work with Nokogiri when webscraping and data mining.

    basic usage:

     include XUtils
     doc = fetch("http://some.url.here") # http:// is impotrtant!
    
     base = find_xpath(doc, '/html/body', ["what to find1", "What to find 2"]) # when you provide array, then it'll find element conaining ALL words
    
     precise = find_xpath(doc, base, "what to find1")
     precise.relative_to base
    

    Good luck

  • There is no the TBODY tag in your HTML code. Firebug generates it automatically.

Use of "this" keyword in formal parameters for static methods in C#

I've come across several instances of C# code like the following:

public static int Foo(this MyClass arg)

I haven't been able to find an explanation of what the this keyword means in this case. Any insights?

From stackoverflow
  • This is an extention method. See here for an explanation.

    it means that you can call

    MyClass myClass = new MyClass();
    int i = myClass.Foo();
    

    rather than

    MyClass myClass = new MyClass();
    int i = Foo(myClass);
    

    This allows the construction of fluent interfaces as stated below.

  • I just learnt this myself the other day: the this keyword defines that method has being an extension of the class that proceeds it. So for your example, MyClass will have a new extension method called Foo (which doesn't accept any parameter and returns an int; it can be used as with any other public method).

  • They are extension methods. Welcome to a whole new fluent world. :)

Commercial software using open source projects?

Can any open source library be used in a commercial software or any specific licensed open source library?

The open source library is used in the software and gets bundled in the package. No changes done in the open source code.

From stackoverflow
  • That depends on the license. You should read the license agreements in your target open source library.

    For example, GPL has a good FAQ: http://www.gnu.org/licenses/gpl-faq.html

  • Here's a bunch of answers to this question:

    http://stackoverflow.com/questions/493959/creating-software-derivative-works-from-open-source/494745#494745

  • I think you need to distinguish between commercial software used in-house/privately and commercial software bundled for sale or distribution.

    Most licenses (including GPL) allow for private customizations of open source software.

    Does the GPL require that source code of modified versions be posted to the public?

    The GPL does not require you to release your modified version, or any part of it. You are free to make modifications and use them privately, without ever releasing them. This applies to organizations (including companies), too; an organization can make a modified version and use it internally without ever releasing it outside the organization.

    But if you release the modified version to the public in some way, the GPL requires you to make the modified source code available to the program's users, under the GPL.

    Thus, the GPL gives permission to release the modified program in certain ways, and not in other ways; but the decision of whether to release it is up to you.

    If you are redistributing/selling your software, it depends on the license for details. For example, GPL does not allow it without distributing source of your new work.

    This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.

    and LGPL does allow it if you link in the library, but not if you create an executable containing the library.

    A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses > the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License.

    However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables.

    Read up on the specific open source license you are trying to use.

LINQ To SQL - Select a constant value

In SQL you can selecta constant value:

Select "Constant Text", Column1, Column2 From TableX

and each row returned from TableX starts with a column containing the text "Constant Text".
Any ideas on how I can do this in LINQ to SQL?
If I do the above I get the error message "Range variable name can be inferred only from a simple or qualified name with no arguments."

From stackoverflow
  • from tx in dc.TableX select new { "constant text", tx.Column1, tx.Column2 };

  • var db = new DataContext();
    
    var query = from x in db.TableX
                select new {"Constant Text", x.Column1, x.Column2};
    

    ..i think it's something like that.

  • Actually, each property in the resulting anonymous class needs a name, so in the following code, we are naming the constant column ConstantColumn. The 2nd and 3rd properties will by default take the names of the queried columns, so they will be named Column1 and Column2 respectively:

    var query = from x in db.TableX
                select new
                {
                    ConstantColumn = "Constant Text",
                    x.Column1,
                    x.Column2
                };
    

XML Schema Validation in Android

Hi, I have created an XML and i want to validate with schema i.e, xsd file but there are no direct classes provided by android for the same if i am not wrong ......... and there is an external jar named jaxp1.3 which doesnt allow me to compile the code is it because the bytecode of desktop and android are different? which has the classes schema factory and validator which does the validation stuff ......Is there an other option available . Any help would be appreciated ..... desperately searching for the ans..........

From stackoverflow

multiple delegate, attached and one fails...

Hi, I am having a scenario, in which i have multiple delegates attached to the event (multicast delegate).

What could be the sequence of calling these methods/delegates (if any) ???

In case one of the method attached with the delegate throws the exception.

  1. Will the event stop processing further...???
  2. Will the rest of the methods attached continue...???

I am not clear on this how to handle this scenario.

Any help is highly appreciated.

From stackoverflow
  • Yes, the event handler that throws the exception will stop executing further, and the exception will propogate up the call stack. This means that any subsequent event handlers will not get called. If you want to guarantee that each event handler gets called in the class that raises the event, then you'll need to iterate over each delegate within the MulticastDelegate and invoke it individually within a try-catch block. The easy solution, of course, is just catching any possible errors within your handlers, and I would say this is advisable in most cases.

  • Methods in multicast delegates get invoked in any order. (Generally, they get invoked in the order they were added to the delegate. But this is not always true.) Therefore, programmers should not depend on an invocation order.

    You need to loop through all the methods in the multicast delegate using delegatename.GetInvocationList() and use a try catch block inside the loop to catch the exception and continue with the next method invocation.

    See this article on how you can make sure rest of the methods are invoked inspite of exceptions in a few.

is it safe to refactor my django models?

My model is similar to this. Is this ok or should I make the common base class abstract? What are the differcenes between this or makeing it abstract and not having an extra table? It seems odd that there is only one primary key now that I have factored stuff out.

class Input(models.Model):
        details = models.CharField(max_length=1000)
        user = models.ForeignKey(User)
        pub_date = models.DateTimeField('date published')
        rating = models.IntegerField()

        def __unicode__(self):
            return self.details

    class Case(Input):
        title  = models.CharField(max_length=200)
        views = models.IntegerField()

    class Argument(Input):
        case = models.ForeignKey(Case)
        side = models.BooleanField()

is this ok to factor stuff out intpu Input? I noticed Cases and Arguments share a primary Key.

like this:

    CREATE TABLE "cases_input" (
        "id" integer NOT NULL PRIMARY KEY,
        "details" varchar(1000) NOT NULL,
        "user_id" integer NOT NULL REFERENCES "auth_user" ("id"),
        "pub_date" datetime NOT NULL,
        "rating" integer NOT NULL
    )
    ;
    CREATE TABLE "cases_case" (
        "input_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "cases_input" ("id"),
        "title" varchar(200) NOT NULL,
        "views" integer NOT NULL
    )
    ;
    CREATE TABLE "cases_argument" (
        "input_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "cases_input" ("id"),
        "case_id" integer NOT NULL REFERENCES "cases_case" ("input_ptr_id"),
        "side" bool NOT NULL
    )
From stackoverflow
  • From: django web site

    Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class.

HTML/ASPX textbox to store non-english characters to SQL database

I have this textbox on an .aspx page, which when submitted it stores whatever typed in the textbox into a nvarchar column in MS SQL 2005.

It works fine, until you try putting chinese characters.
These characters are converted to question marks (?) in the database.

How do you store non-english characters from a <input type="text"> to database?

From stackoverflow
  • The main thing would be to ensure that every step of the pipeline supports international characters; i.e. - at what point do you first see "?" ? In the aspx code? Or only once it gets into the database table?

    The web page should already be using an encoding such as UTF8, so that should be OK - but what data type are you using at the database? It would need to be nchar/nvarchar(n)/nvarchar(max) (or ntext on older versions of SQL Server).

    : Hi thanks. When I pasted a chinese character in the textbox it looks fine. But in the database (and when you read back from the database to an aspx page) they become ????. And I forgot to mention it's nvarchar(50), I edited the question thanks.
    Marc Gravell : So when does it first become ??? - have you looked at fiddler? debugged the ASP.NET app?

Oracle view with multiple join is only recognize when use a quotes around - why ?

I have encountered a strange behavior while executing an sql query on the Oracle view. The view contains multiple join. When I type a regular sql: select * from vView - I receive the error that view is not find select * from "vView" - The query is executed. I am wondering why ?

[url=http://www.freeimagehosting.net/image.php?138bcd008e.jpg][img]http://www.freeimagehosting.net/uploads/th.138bcd008e.jpg[/img][/url]
[url=http://www.freeimagehosting.net/image.php?e0738a36dd.jpg][img]http://www.freeimagehosting.net/uploads/th.e0738a36dd.jpg[/img][/url]

Below is my sql:

 CREATE OR REPLACE FORCE VIEW "TMSCODE"."vCountEventsData" ("EV_ID_NUMBER", "SI_ID", "EV_YEAR", "EV_INS_DATE", "EV_REM_DATE", "EV_AADT_TOT", "EV_AADT_DIR1", "EV_AADT_DIR2", "EV_REPORT", "DIRECTION", "CNAME", "STATION_DESC") AS

SELECT "TMSCODE"."STC_EVENTS".EV_ID_NUMBER, "TMSCODE"."STC_EVENTS".SI_ID, "TMSCODE"."STC_EVENTS".EV_YEAR, "TMSCODE"."STC_EVENTS".EV_INS_DATE, "TMSCODE"."STC_EVENTS".EV_REM_DATE, "TMSCODE"."STC_EVENTS".EV_AADT_TOT, "TMSCODE"."STC_EVENTS".EV_AADT_DIR1, "TMSCODE"."STC_EVENTS".EV_AADT_DIR2, "TMSCODE"."STC_EVENTS".EV_REPORT, "TMSCODE"."D_DIRECTION".DIRECTION, "TMSCODE"."D_CONSULTANT".CNAME, "TMSCODE"."D_STATION_TYPE".STATION_DESC FROM "TMSCODE"."STC_EVENTS" INNER JOIN "TMSCODE"."D_DIRECTION" ON ("TMSCODE"."STC_EVENTS".EV_DIR = "TMSCODE"."D_DIRECTION".ID) INNER JOIN "TMSCODE"."D_CONSULTANT" ON ("TMSCODE"."STC_EVENTS".EV_CONS = "TMSCODE"."D_CONSULTANT".ID) INNER JOIN "TMSCODE"."D_STATION_TYPE" ON ("TMSCODE"."STC_EVENTS".EV_STATION_TYPE = "TMSCODE"."D_STATION_TYPE".ID) WITH READ ONLY

From stackoverflow
  • The view was created with a mixed case name. If you issue the following (note no quotes around object names)

    create view karl.vView 
    as 
    (select * from dba_tables);
    

    The RDBMS will create the view and you will then find a line in dba_views (or user_views if you can't see dba_views) with the name VVIEW in upper case. Then select * from karl.vview or ... from KARL.VVIEW will work

    If however you quote the objects names retains the case and you have to explicitly match it again with quotes. (This will also allow spaces in names and other bad scenarios. Worth knowing about to avoid and to be able to resolve when it does happen.

    SYS@icedev> create table "TesT" (a int);
    
    Table created.
    
    SYS@icedev> insert into TesT values (1);
    insert into TesT values (1)
                *
    ERROR at line 1:
    ORA-00942: table or view does not exist
    
    
    SYS@icedev> insert into test values (1);
    insert into test values (1)
                *
    ERROR at line 1:
    ORA-00942: table or view does not exist
    
    
    SYS@icedev> insert into "TesT" values (1);
    
    1 row created.
    
    

    Of course to drop this table I had to use Drop table "TesT";

    Greener : Thanks Karl, I appreciated. It worked. Now I can see my view. Lesson learned.
  • In Oracle, objects have an uppercase name unless quoted. You used quotes to create an object with a mixed case name, so you must now ALWAYS refer to the object using a quoted identifier to say "Don't change this to uppercase".

css: how to format contact entry screen

I am trying to nicely format contact screen in my aspx page using CSS. With the following code, I am unable to click into the txtEmailAddress. If I take out padding:100px from the txtSubject Span element, then I am able to click into txtEmailaddress and edit. please help...

<div>
<span>
Your Email Address :    
</span>
<span style="padding:100px">
<asp:TextBox ID="txtEmailAddress" runat="server"></asp:TextBox>        
</span>

<br />
<span>
                    Subject :    
</span>
<span  style="padding:100px">
                <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>        
</span>                
<br />
</div>
From stackoverflow
  • i tried copying and pasting and experienced the same behaviour, i.e. with padding on the subject span i couldn't click into txtEmailAddress. I am running IE8 on vista SP1 if that helps at all. I also noticed that the text boxes were not aligned.

    Whilst it doesn't answer your question, have you thought about using Label tag and styling these tags. The form will be more accessible this way. You can find out more about this approach on alistapart here:

  • Perhaps the following would suit your purposes better:

    <fieldset>
    <legend>Add a heading if you want one</legend>
    <div>
    <asp:Label id="lblEmail" runat="server" text="Your Email Address:" AssociatedControlID="txtEmailAddress">
    </asp:Label>
    <asp:TextBox ID="txtEmailAddress" runat="server"></asp:TextBox>        
    </div>
    <div>
    <asp:Label id="lblSubject" runat="server" text="Subject:" AssociatedControlID="txtSubject">
    </asp:Label>
    <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>        
    </div>
    </fieldset>
    

    You can then add your layout using CSS to the fieldset, label and input elements specifically, e.g.

    fieldset label
    {
      margin-right: 2em;
      width: 20em;
    }
    
    fieldset input
    {
      display: inline;
    }
    

    Or some variation thereof.

Accessing Google Spreadsheets with C# using Google Data API

I'm having some information in Google Spreadsheets as a single sheet. Is there any way by which I can read this information from .NET by providing the google credentials and spreadsheet address. Is it possible using Google Data APIs. Ultimately I need to get the information from Google spreadsheet in a DataTable. How can I do it? If anyone has attempted it, pls share some information.

From stackoverflow
  • I'm pretty sure there'll be some C# SDKs / toolkits on Google Code for this. I found this one, but there may be others so it's worth having a browse around.

  • http://code.google.com/apis/gdata/articles/dotnet_client_lib.html

    This should get you started. I haven't played with it lately but I downloaded a very old version a while back and it seemed pretty solid. This one is updated to Visual Studio 2008 as well so check out the docs!

  • You can do what you're asking several ways:

    1. Using Google's spreadsheet C# library (as in Tacoman667's answer) to fetch a ListFeed which can return a list of rows (ListEntry in Google parlance) each of which has a list of name-value pairs. The Google spreadsheet API (http://code.google.com/apis/spreadsheets/code.html) documentation has more than enough information to get you started.

    2. Using the Google visualization API which lets you submit more sophisticated (almost like SQL) queries to fetch only the rows/columns you require.

    3. The spreadsheet contents are returned as Atom feeds so you can use XPath or SAX parsing to extract the contents of a list feed. There is an example of doing it this way (in Java and Javascript only though I'm afraid) at http://gqlx.twyst.co.za.

  • According to the .Net user guide: http://code.google.com/apis/spreadsheets/docs/2.0/developers_guide_dotnet.html

    Download the .Net client library: http://code.google.com/p/google-gdata/

    Add these using statements:

    using Google.GData.Client;
    using Google.GData.Extensions;
    using Google.GData.Spreadsheets;
    

    Authenticate:

    SpreadsheetsService myService = new SpreadsheetsService("exampleCo-exampleApp-1");
    myService.setUserCredentials("jo@gmail.com", "mypassword");
    

    Get a list of spreadsheets:

    SpreadsheetQuery query = new SpreadsheetQuery();
    SpreadsheetFeed feed = service.Query(query);
    
    Console.WriteLine("Your spreadsheets:");
    foreach (SpreadsheetEntry entry in feed.Entries)
    {
        Console.WriteLine(entry.Title.Text);
    }
    

    Given a SpreadsheetEntry you've already retrieved, you can get a list of all worksheets in this spreadsheet as follows:

    AtomLink link = entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null);
    
    WorksheetQuery query = new WorksheetQuery(link.HRef.ToString());
    WorksheetFeed feed = service.Query(query);
    
    foreach (WorksheetEntry worksheet in feed.Entries)
    {
        Console.WriteLine(worksheet.Title.Text);
    }
    

    And get a cell based feed:

    AtomLink cellFeedLink = worksheetentry.Links.FindService(GDataSpreadsheetsNameTable.CellRel, null);
    
    CellQuery query = new CellQuery(cellFeedLink.HRef.ToString());
    CellFeed feed = service.Query(query);
    
    Console.WriteLine("Cells in this worksheet:");
    foreach (CellEntry curCell in feed.Entries)
    {
        Console.WriteLine("Row {0}, column {1}: {2}", curCell.Cell.Row,
            curCell.Cell.Column, curCell.Cell.Value);
    }
    
  • I wrote a simple wrapper around Google's .Net client library, it exposes a simpler database-like interface, with strongly-typed record types. Here's some sample code:

    public class Entity {
        public int IntProp { get; set; }
        public string StringProp { get; set; }
    }
    
    var e1 = new Entity { IntProp = 2 };
    var e2 = new Entity { StringProp = "hello" };
    var client = new DatabaseClient("you@gmail.com", "password");
    const string dbName = "IntegrationTests";
    Console.WriteLine("Opening or creating database");
    db = client.GetDatabase(dbName) ?? client.CreateDatabase(dbName); // databases are spreadsheets
    const string tableName = "IntegrationTests";
    Console.WriteLine("Opening or creating table");
    table = db.GetTable<Entity>(tableName) ?? db.CreateTable<Entity>(tableName); // tables are worksheets
    table.DeleteAll();
    table.Add(e1);
    table.Add(e2);
    var r1 = table.Get(1);
    

    There's also a LINQ provider that translates to google's structured query operators:

    var q = from r in table.AsQueryable()
            where r.IntProp > -1000 && r.StringProp == "hello"
            orderby r.IntProp
            select r;
    

Why only basicHttpBinding with silverlight and wcf?

Exact duplicate: http://stackoverflow.com/questions/661479/why-does-silverlight-2-only-support-wcf-basichttp-binding

Why only basicHttpBinding with silverlight and wcf? Perhaps you have a link that covers this, you don't have to do a bunch of typing :+>

From stackoverflow
  • Hm, I am pretty sure this is duplicate, but can't find it. I think the short answer is that BasicHttpBinding is the only binding that works in Partial Trust.

    (EDIT: found the dup, linked in question now)

  • I found several links for this but no definitive answer. Smells like Silverlight was designed against ASMX web services for Web service style communication and the way to get WCF to play with older clients expecting an ASMX web service is to use the basicHttp binding.

    This link gives you a fully worked example (using Beta2 of Silverlight).
    http://msdn.microsoft.com/en-us/magazine/cc794260.aspx

    A standard WCF service can be invoked by a Silverlight app as long as the Silverlight app has a binding of type basicHttpBinding. You must either make sure you change the default binding of the WCF service from wsHttpBinding to basic­HttpBinding or create a new binding of type basicHttpBinding

    This Reference says the same thing but again offers no explanation. http://timheuer.com/blog/archive/2008/03/14/calling-web-services-with-silverlight-2.aspx

    Silverlight communicates using the BasicHttpBinding for WCF

  • A couple of answers: (1) Silverlight 4 now makes the Net.TCP binding available, which is darned handy when it's not blocked, since it's dramatically faster (see here for details). So clearly there's nothing inherent in the Silverlight architecture which prevents it from using other bindings.

    (2) As for why Silverlight doesn't make use of the other WS* Http-based bindings, it's just a guess, but I wouldn't be surprised if those bindings made use of the HTTP protocol in ways that Silverlight's limited HTTP stack won't support, probably for security reasons. For instance, I know that Silverlight limits the content headers that you can place on an HTTP request, and if any of the WS-* protocols require custom headers, or headers that might represent a security risk, MS would want to prevent that.

    (3) Of course, it's also possible that MS just hasn't gotten around to it yet. They've done a lot with Silverlight in the last couple years -- but presumably they have to prioritize their features.

JSON.Net: Convert JSON string from XML string to instance issue

I have the following function:

public static T GetInstance<T>(string xmlString)
{
   var xmlDoc = new XmlDocument();
   xmlDoc.Load(new StringReader(xmlString));
   string jsonString = JsonConvert.SerializeXmlNode(xmlDoc.DocumentElement);
   T instance = JsonConvert.DeserializeObject(jsonString, typeof(T)) as T;
   return instance;
}

It works fine for normal XML strings. However, if the input XML string contains comments such as :

....
<!-- some comments ... 
-->
....

Then the function call to JsonConvert.DeserializeObject() will throw an exception:

Newtonsoft.Json.JsonSerializationException was unhandled
Message="Unexpected token when deserializing object: Comment"
Source="Newtonsoft.Json"
StackTrace:
   at Newtonsoft.Json.JsonSerializer.PopulateObject(Object newObject, JsonReader reader, Type objectType)
   ....

Either I have to trim out all the comments in the XML string, or if I can use any option settings in JsonConvert to ignore comments.

For the first option, if I have to take all the comments out by using XmlDocument, is there any options in XmlDocument available to convert an XML string to nodes-only XML string?

For the second option, I prefer, if there is any option in Json.Net to ignore comments when desialize to object?

From stackoverflow
  • I think the best way for me right now is to remove all the comment nodes from the xml string first.

    public static string RemoveComments(
            string xmlString,
            int indention)
    {
       XmlDocument xDoc = new XmlDocument();
       xDoc.PreserveWhitespace = false;
       xDoc.LoadXml(xmlString);
       XmlNodeList list = xDoc.SelectNodes("//comment()");
    
       foreach (XmlNode node in list)
       {
          node.ParentNode.RemoveChild(node);
       }
    
       string xml;
       using (StringWriter sw = new StringWriter())
       {
          using (XmlTextWriter xtw = new XmlTextWriter(sw))
          {
            if (indention > 0)
            {
              xtw.IndentChar = ' ';
              xtw.Indentation = indention;
              xtw.Formatting = System.Xml.Formatting.Indented;
            }
    
            xDoc.WriteContentTo(xtw);
            xtw.Close();
            sw.Close();
          }
          xml = sw.ToString();
        }
    
      return xml;
      }
    

    And this is my function to get instance from xml string:

    public static T GetInstance<T>(string xmlString)
    {
      srring xml = RemoveComments(xmlString);
      var xmlDoc = new XmlDocument();
      xmlDoc.Load(new StringReader(xml));
      string jsonString = JsonConvert.SerializeXmlNode(xmlDoc.DocumentElement);
      T instance = JsonConvert.DeserializeObject(jsonString, typeof(T)) as T;
      return instance;
    }
    

Git ignore file for C projects

I've just started to learn C (using Thinking In C) and I'm wondering about what files I should be ignoring in a C project's git repository.

No suggestion can be too obvious -- I'm a total noob. Thanks!

From stackoverflow
  • I guess there will be a few generated files that you don't wan't to be sticking in your repo (assuming your build output dir is in your git heirachy):

    • object files (.o, o.obj)
    • libraries (.lib)
    • DLLs, shared objects (.so, .dll)
    • Executables (.exe, a.out ?)

    GIT ignore files are something I tend to do iteratively. "Hey, I don't need those things in my repo" ...

    Edit: re dmckee's comment

    Yep, you definately want to be ignoring swap files, temp files etc. I have the following as a baseline for my .gitignore:

    • *.swp
    • .~
    • thumbs.db
    dmckee : If you editor makes automatic backups (ala emacs' *~ files), you can probably do without those too.
    Jakub Narębski : Usually you put ignoring of generated files in version controlled and transferred `.gitignore` file (so everybody will have generated files ignored), but ignoring backup files and other types of files depending on your environment (backup files can be *~ or *.bak) in not transferred repository .git/info/exclude (or in core.excludesfile set in ~/.gitconfig).
  • You can also setup your build to happen in a subdirectory say build and then you can ignore the whole thing inside .gitignore

    build/

    And you're done.

Overlaying a UIImage with a color?

I'm attempting to add a black overlay over some current UIImage's (which are white). I've been trying to use:

[[UIColor blackColor] set]; [image drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeOverlay alpha:1.0];

But it's not working, and I'm pretty sure set isn't supposed to be there.

From stackoverflow
  • -set is used to set the colour of subsequent drawing operations which doesn't include blits. I suggest as a first call, displaying another (empty) UIView over yout UIImageView and stting it's background colour:

    myView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    

    Obviously you should use the white and alpha values you want.

    Oliver : The problem with this is my UIImage isn't a rectangle block, it's an icon. Wouldn't this method also draw the color around the image? Basically, I just want to convert a white UIImage to a black UIImage.
  • You will want to clip the context to an image mask and then fill with a solid color:

    - (void)drawRect:(CGRect)rect
    {
        CGRect bounds = [self bounds];
        [[UIColor blackColor] set];
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextClipToMask(context, bounds, [myImage CGImage]);
        CGContextFillRect(context, bounds);
    }
    

    Note: myImage should be an instance variable that contains an UIImage. I'm not sure whether it takes the mask from the alpha channel or the intensity so try both.

  • In addition to the solution by rpetrich (which is great by the way - help me superbly), you can also replace the CGContextClipToMask line with:

        CGContextSetBlendMode(context, kCGBlendModeSourceIn); //this is the main bit!
    

    It's the SourceIn blendmode that does the job of masking the color by whatever is in the GetCurrentContext.

  • I just wrote a tutorial that will help with this. My approach gives you a copy of a UIImage, with the color alterations that you want. rpetrich's approach is great, but requires that you're creating a subclass. My approach is just a few lines of code that can be dropped in wherever you need them. http://coffeeshopped.com/2010/09/iphone-how-to-dynamically-color-a-uiimage