Wednesday, April 6, 2011

Limitation for google sitemap.xml file size

can any one please let me know the memory limitation(MB) of google sitemap.xml file size.

From stackoverflow
  • According to a claim in the Wikipedia article, the limit is 50,000 URLs and 10 MB (uncompressed) per sitemap. I think this number is from the Google Webmaster FAQ (can't find the official entry but this Google groups entry says the same.)

    Not sure whether this limit applies to the other search engine providers as well.

    Pekka : @methode the forum post I link to says that 10MB is the maximum size *after* gunzipping. Do you have a link to back up your claim? If you do, please do add it. Both the forum post and the Wikipedia entry are not necessarily 100% reliable info IMO.
    methode : i should really shut up before drinking the first coffee in the morning... yeah, you're absolutely right. I removed my comment. Then the only addition is to confirm that all major search engines follow these requirements since it's set in the Sitemaps protocol (http://sitemaps.org/protocol.php#index), and all of them rely on this protocol. (this was also tested but no link for that) Sorry for the previous, misleading comment.
    Pekka : @methode great info and link - that was the official confirmation I was looking for. Cheers!

Get the current URL within a django template

Hay, i was wondering how to get the current URL within a template.

Say my URL was

/user/profile/

How do i return this to the template?

Thanks

From stackoverflow
  • request.get_full_path

    dotty : Can i get it without passing the 'request' variable to the template?
    Brant : I believe request is always passed to the template... if not, render_to_response('template.html',{},context_instance=RequestContext(request)) .. at that point, request is definitely passed in.
    dotty : Bascially i'm making a 'logout' function which redirects back to the page they were on when a 'logout' button is clicked. I was going to append the current URL to the query string.
    Brant : Just use request.path then
    dotty : I decided to use request.META['HTTP_REFERER'] to redirect them.
    Jack M. : Be warned that HTTP_REFERRER isn't always reliable. Many of the "Internet Security Suites" will remove that variable. It is probably worth it to ensure that your site still works even when there isn't a referrer, using something like `request.META.get('HTTP_REFERRER', '/')` or similar.

Strange altered behaviour when linking from .so file with ctypes in python

I am writing a program to handle data from a high speed camera for my Ph.D. project. This camera comes with a SDK in the form a .so file on Linux, for communicating with the camera and getting images out. As said it is a high speed camera delivering lots of data, (several GB a minute). To handle this amount of data the SDK has a very handy spool function that spools data directly to the hard drive via DMA, in the form of a FITS file, a raw binary format with a header that is used in astronomy. This function works fine when I write a small C program, link the .so file in and call the spool function this way. But when I wrap the .so file with ctypes and call the functions from python, all the functions are working except the spool function. When I call the spool function it returns no errors, but the spooled data file are garbled up, the file has the right format but half of all the frames are 0's. In my world it does not make sense that a function in a .so file should behave different depending on which program its called from, my own little C program or python which after all is only a bigger C program. Does any body have any clue as to what is different when calling the .so from different programs?

I would be very thankful for any suggestions

Even though the camera is commercial, some the driver is GPLed and available, though a bit complicated. (unfortunately not the spool function it seems) I have an object in python for Handel the camera.

The begining of the class reads:

class Andor:
  def __init__(self,handle=100):
    #cdll.LoadLibrary("/usr/local/lib/libandor.so")
    self.dll = CDLL("/usr/local/lib/libandor.so")
error = self.dll.SetCurrentCamera(c_long(handle))
    error = self.dll.Initialize("/usr/local/etc/andor/")

    cw = c_int()
    ch = c_int()
    self.dll.GetDetector(byref(cw), byref(ch))

The relevant function reads:

def SetSpool(self, active, method, path, framebuffersize):
    error = self.dll.SetSpool(active, method, c_char_p(path), framebuffersize)
    self.verbose(ERROR_CODE[error], sys._getframe().f_code.co_name)
    return ERROR_CODE[error]

And in the corresponding header it reads:

unsigned int SetSingleTrackHBin(int bin);

unsigned int SetSpool(int active, int method, char * path, int framebuffersize);

unsigned int SetStorageMode(at_32 mode);

unsigned int SetTemperature(int temperature);

The code to get the camera running would read something like:

cam = andor.Andor()
cam.SetReadMode(4)
cam.SetFrameTransferMode(1)
cam.SetShutter(0,1,0,0)
cam.SetSpool(1,5,'/tmp/test.fits',10);
cam.GetStatus()
if cam.status == 'DRV_IDLE':
acquireEvent.clear()
cam.SetAcquisitionMode(3)
cam.SetExposureTime(0.0)
cam.SetNumberKinetics(exposureNumber)
cam.StartAcquisition()
From stackoverflow
  • My guess is that it isn't the call to the spooling function itself, but a call series which results in corrupted values being fed to/from the library.

    Are you on a 64-bit platform? Not specifying restype for anything which returns a 64-bit integer (long with gcc) or pointer will result in those values being silently truncated to 32 bits. Additionally, ctypes.c_voidp handling is a little surprising — restype values of ctypes.c_voidp aren't truncated, but are returned in the Python interpreter as type int, with predictably hilarious results if high pointers are fed back as parameters to other functions without a cast.

    I haven't tested it, but both these conditions might also affect 32-bit platforms for values larger than sys.maxint.

    The only way to be 100% certain you're passing and receiving the values you expect is to specify the argtypes and restype for all the functions you call. And that includes creating Structure classes and associated POINTERs for all structs those functions operate on, even opaque structs.

How to handle XML string %Like% search in C#

Hi, As I know I can search DB with Sql syntax %like%.

Now I am working with XML, how can I handle the same search condition for XML file in C#?

I want to search the string and find it with part of the Keyword. Not the full text of keyword.

   <bookstore>
     <book genre="autobiography">
       <title>The Autobiography of Benjamin Franklin</title>
       <author>
         <first-name>Benjamin</first-name>
         <last-name>Franklin</last-name>
       </author>
       <price>8.99</price>
     </book>
     <book genre="philosophy">
       <title>The Gorgias</title>
       <author>
         <name>Plato</name>
       </author>
       <price>9.99</price>
     </book>
   </bookstore>

Assume I am working with the sample XML above. How can I code in C# to search "%jami%", then return "Benjamin". Thank you.

From stackoverflow
  • Traverse the XML file and do a String.Contains(...).

    Nano HE : @PieterG,Thank you . I found a sample code about String.Containers(). It works quite well as I need.
    allonym : That'll work, but Garett's suggestion of XPath or Linq To XML is the more elegant approach.
  • There are a couple of ways this can be done, depending on the version of .NET you are working with. You can use XPath, or my preference Linq To XML.

    Here are a few useful links:

Why subtract a value from itself (x - x) in Python?

In NumPy functions, there are often initial lines that do checking of variable types, forcing them to be certain types, etc. Can someone explain the point of these lines in scipy.signal.square? What does subtracting a value from itself do?

t,w = asarray(t), asarray(duty)
w = asarray(w + (t-t))
t = asarray(t + (w-w))

source

From stackoverflow
  • I believe that this will make the final w and t have the same type. For example, if you start with float and int, you will end up with both being float arrays which is better for subsequent operations.

    Dingle : A good observation. I have used the same trick, too.
    iondiode : yes, and it will have the same dimension as well ( in case they started out with different)
    endolith : That's kind of weird considering t is an array and w is a scalar

Is it possible to access a BDB from pure Java?

Hi

I'm trying to access "cert8.db" mozilla file which is a BDB database. I know that there are bindings for languages, Java among them, but I'm trying to build a multiplatform app so I think that using JNI such as this one would be a problem.

Thanks in advance.

From stackoverflow
  • You don't need full BDB package to read that file. Check out this class,

    http://sam.nipl.net/code/mindterm/com/mindbright/bdb/DBHash.java

    ktulur : Interesting, much thanks. Reading.... What about writing?
    ZZ Coder : No. Read-only. If you are going to write, you should just convert it to the format used by Sleepycat Java library.

Evaluate or Show HTML using Javascript

Hello, I have this...portion of code in Javascript:

var description = document.createElement('P');

description.className='rssBoxDescription';

description.innerHTML = itemTokens[2];

div.appendChild(description);

I see that description gets the HTML value and displays as plain HTML coding not as HTML processing it shouldbe ... how to convert this HTML value in description to be appended to div element shown as HTML...which is not showing.

Also it has value something like:

<table><tr><td style="padding: 0 5px"><ahref="xttp://picasaweb.google.com/linktoimagepage"><imgtag style="border:1px solid #5C7FB9" s_rc="xttp://lh3.ggpht.com/imagepath" alt="image.jpg"/></a></td><td valign="top"><font color="#6B6B6B">Date: </font><font color="#333333">Jun 28, 2007 9:00 AM</font><br/><font color=\"#6B6B6B\">Number of Comments on Photo:</font><font color=\"#333333\">0</font><br/><p><ahref="xttp://picasaweb.google.com/linktoimage"><font color="#3964C2">View Photo</font></a></p></td></tr></table>

Pls help Anita

@SARFARAZ ... YES...I am using the script on dhtmlgoodies.com/scripts/rss-scroller/js/ajax.js

It worked as :: description.replace(/&lt;/g,"<"); and description.replace(/&gt;/g,">");

From stackoverflow
  • It could be that the > and the < have been encoded like &gt; and &lt;

    Try replacing &gt; with > and &lt; with < in itemTokens before assigning it as the DIV innerHTML and see if it works

  • It seems to be working for me. Try posting entire code including the div that is created dynamically.

mail script in php

I am hosting my web application(pnpmkt.com) from GODADDY.com they have given me some email account like info@pnpmkt.com. I want to send welcome message to new user's to their mail account in other mail servers like google, yahoo.for example, my mail function is-

<?php

$address = "piysuh@gmail.com";
$Subject = "PNP Solutions";
$body = "Welcome to PNP";
$mailsend = mail("$address", "$Subject", "$body.");
print("$mailsend");
?>

what other configurations are required?Any path name or server name??

From stackoverflow
  • Can you post the mail method? To send an email, the smtp address or something else is needed...

  • Here is a wrapper function I use to send emails (text or html):

    // $Sender: Sender email
    // $Recipient: Recipient email
    // $Subject: Email subject
    // $Detail: Plain text or HTML (should include <html> and <body> tags)
    // $Type: TEXT or HTML
    
    function sendmail( $Sender, $Recipient, $Subject, $Detail, $Type )
    {
        switch ( $Type )
        {
            case "TEXT":
                $Header  = "From: $Sender\n";
                break;
            case "HTML":
                $Header  = "From: $Sender\n";
                $Header .= "MIME-Version: 1.0\n";
                $Header .= "Content-type: text/html; charset=iso-8859-1\n";
                break;
        }
        return mail( $Recipient, $Subject, $Detail, $Header );
    }
    
  • Can you clarify whether you are having trouble sending emails using this method? From what I can see, your code is good, and should operate without any problems.

    I just tested this code, myself, and it works fine.

    It should be noted that the mail() function returns TRUE on success and FALSE on failure so echoing that is not a terribly useful thing to do. (You'll just get "1" if it worked and "0" if it didn't.)

    If you are wanting to include more advanced features and facilities in your emails, however, you may want to look at PHPmailer, which is a PHP Class allowing for the sending of HTML Emails, changing various settings like the Sender's email address and name, etc.

How to force HttpWebRequest to use cache in ASP.NET environment?

In my ASP.NET app I use HttpWebRequest for fetching external resources which I'd like to be cached. Consider the following code:

var req = WebRequest.Create("http://google.com/");
req.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);
var resp = req.GetResponse();
Console.WriteLine(resp.IsFromCache);
var answ = (new StreamReader(resp.GetResponseStream())).ReadToEnd();
Console.WriteLine(answ.Length);

HttpWebRequest uses IE cache, so when I run it as normal user (in tiny cmd test app), data is cached to %userprofile%\Local Settings\Temporary Internet Files and next responses are read from cache.

I thought that when such code is run inside ASP.NET app, data will be cached to ...\ASPNET\Local Settings\Temporary Internet Files but it is not and cache is never used.

What I am doing wrong? How to force HttpWebRequest to use cache in ASP.NET environment?

From stackoverflow
  • I could be wrong but I would suspect that HttpWebRequest respects cache headers from the resource regardless of your stated desires.

    Check the response headers and ensure that the resource is not explicitly asking to not be cached.

    piotrsz : I suspected headers too so I build a tiny cmd app that makes httprequest to the same resource. In cmd app it's cached. And in ASP.NET app it's not.
  • You can use the cache manually in your code like this:

     Cache.Insert("request", req, Nothing, DateTime.Now, TimeSpan.FromSeconds(30), TimeSpan.Zero)
    

    You can use this Method like you would use caching with in web.config.

    piotrsz : @MUG4N: I'll probably end up implementing custom cache but I was hoping for some straightforward "out of the box" solution...
    MUG4N : I think there is no out of the box for your problem but this shouldn't be a big problem to implement.
  • As I put in the comment above, add a line to dispose the response object...

    resp.Close();
    

    and then see if you still have problems.

    If you do, creating a log with the following app.config in your vdir might help figure out why it is not being cached...

    Creating a system.net debugging tracelog

    Note, that the IE cache is really not meant to be used in middle-tier scenarios. You are doing something that is not supported by microsoft.

    piotrsz : I put response into `using` block so it gets closed and disposed and data is cached now! Thanks :-) But I'll probably use different approach as you and MUG4N suggeseted.
    feroze : Glad it worked for you. I would look into IsolatedStorage in .NETFramework to see if it provides the functionality on top of which you could build your cache.

Dynamically create sprite images for Cocos2d-iPhone

Hey guys,

I'm working on a platformer, and looking for a way to create a sprite for an arbitrarily sized platform. For example, I may know I have a platform that should appear 200 pixels wide by 32 pixels high, and, say, I have a texture of bricks that I can tile to fill that area. I may also want to draw a black border around the platform. Is this possible at all? Anyone have any ideas for how I might go about doing this? I could always try generating the image on the fly and building a sprite with that image, but I sincerely doubt (hope) that this isn't the most efficient way of doing something like this.

Cheers, Alex

From stackoverflow
  • You can use tiled maps for the platform. It will require you to plan your textures a bit differently, but it will probably yield better results.

    You can read more about tiled maps here.

    AlexC : Thanks, I guess this is probably going to be my best bet. It's a shame that there isn't any more flexible way to draw custom sprites. Still, I haven't contributed to the code so who am I to complain :)
    matt : This is the way these things have been done in games, since forever. ;)

riched32.dll or riched20.dll sourcode

Is the sourcecode of riched32.dll or riched20.dll available somewhere

If not - what could I do if i want to create a richedit textfield that behaves slightly different (like changing the control for the scrollbars, such that i can change the size and positions of them from outside)

thanks

From stackoverflow
  • In Windows, if one wants to create a common control that behaves differently, they would create it as usual and subclass it.

    genesys : hey! thanks i have already read about sub and super classing. but how would i extend it by subclassing such that i can actually change the logics of the control? let's say i want to be able to display two carets instead of only one. or that the textfield scrolls up if i move the scrollbar upwards (instead of wise versa) how can i do such things?
    GSerg : There can only be one caret, but you can emulate a second caret by hadling WM_PAINT in your subclass routine and drawing that caret on your own. Similarly, you can reverse the scrollbars logic by intercepting WM_VSCROLL and changing it's parameters before calling DefWindowProc.
    Mat : Thanks! Do you know any good tutorials that cover stuff like that?

C# Drawing 2D objects with events

I need to draw several simple objects (polygons composed by lines and arcs, eventually placed on different layers) inside a form (or any other container) and then handle events like:

  • right click on object
  • zoom
  • pan

Is there a library/framework that can handle my need or do I need to create my own?

EDIT FOR CLARIFICATION:

My polygons come from SDO tables exported from AutoCAD Map 3D and I need to create a simple application that can show them (with pan, zoom, etc) and enable simple operations on them (like viewing properties, insert a point, etc).

May be I should look for an AutoCAD OEM license?

From stackoverflow
  • A good example can be found on codeproject called draw tools

    It has samples of drawing a rectanlge, ellipse, dragging, stretching etc and can be extended to add other basic objects. We used the same framework to write a program called Page Layout Pro.

    Keeper : I don't think it can fit my needs
  • Mindfusion have a range of diagramming libraries which support what you want, but may well be too complicated for your needs (and expensive).

    Keeper : That's not what I want to design, look at my edit

Corpus/data set of English words with syllabic stress information?

I know this is a long shot, but does anyone know of a dataset of English words that has stress information by syllable? Something as simple as the following would be fantastic:

AARD vark
A ble
a BOUT
ac COUNT
AC id
ad DIC tion
ad VERT ise ment
...

Thanks in advance!

From stackoverflow
  • I closest thing I'm aware of is the CMU Pronouncing Dictionary. I don't think it explicitly marks the stressed syllable, but it should be a start.

    dmcer : I would add that it does actually mark primary and secondary lexical stress. See the 1s and 0s on the phones here https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/cmudict/cmudict.0.7a .
    endtime : Thanks guys, that's perfect.

How to diganose an unlogged Error 500 on Apache?

We are running a very simple Symfony script, that randomly returns an Error 500. The system administrator says he can't find any trace of an Error 500 on the error logs, however using Curl or Firebug, it is obvious that an Error 500 is being returned.

The script simply parses a POST request submitted to an URL on our server. We already checked for performance, memory etc but nothing seems to be the problem.

How is this possible? We already enabled all debugging, logging, on Apache, PHP, etc and nothing.

From stackoverflow
  • The following testscript also won't generate any error messages/logs.

    <?php
    header($_SERVER['SERVER_PROTOCOL'].' 500 Internal server error');
    echo 'Something went gaga';
    ?>
    

    However the access_log will show the "500" response code (assuming apache's default access_log settings)

    Search the code for "HTTP/1.1 500", "500" or "header(" and add:

    trigger_error('Peep', E_USER_NOTICE);  // or error_log()
    

    This will generate an entry in the errorlog (with filename and line-numbers)

Get objc_exception_throw when setting cookie with ASIHTTPRequest

I got objc_exception_throw when trying to set cookies for a ASIHTTPRequest request. I tried both of these but it didn't work out.

ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];

NSMutableDictionary *properties = [[NSMutableDictionary alloc] init];

[properties setValue:@".google.com" forKey:@"Domain"];
[properties setValue:@"/" forKey:@"path"];
[properties setValue:@"1600000000" forKey:@"expires"];


NSHTTPCookie *cookie = [[NSHTTPCookie alloc] initWithProperties:properties];
[request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];

or replacing initiating code for cookie with this one

NSHTTPCookie *cookie = [[NSHTTPCookie alloc] init];

When I commented out the following line, everything worked fine.

[request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];

Can you guys tell me what the problem here!

From stackoverflow
  • Don't know if this is your problem or not, but you should be using the defined NSHTTPCookie property keys like NSHTTPCookieDomain instead of literal strings like @"Domain".

    You might be able to get more information about what's going wrong by catching the exception and logging it. For example:

    @try {
        [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];}
    @catch (NSException *exception) {
        NSLog(@"Caught %@: %@", [exception name], [exception reason]);
    }
    @finally {
    }
    
    TuanCM : David, thank for your advice. It's definitely look nicer using the defined property keys. However I couldn't catch the exception using your code. Did I miss something?
    TuanCM : I'm wondering if my Macbook having problem or just my code. I tried to add just this line into a working code. NSHTTPCookie *cookie = [[NSHTTPCookie alloc] init]; My app crashed with EXC_BAD_ACCESS error. This really confused me. Can anyone tell me why?

click() not working on FireFox

<script>
function attachFile(){
  document.getElementById("file").click(); 
  return;
}
</script>

<form name="novsh" style="margin: 0px; padding: 0px;">
<input type="file" name="file" style="display:none" id="file" />
</form>

<a href="javascript:attachFile()">Attach File</a>
<input type="button" name="btn" value="click me" onclick="attachFile()"/>

I've written like this and it's working on IE but not working on FireFox

From stackoverflow
  • The click() function on elements that aren't form inputs is a non-standard feature that only exists in IE.

    If you're trying to call the element's onclick handler, you can do this:

    document.getElementById("file").onclick();
    

    Edit:

    Turns out this is a form input, so...never mind.

    But it looks like what you're trying to do is get the file picker dialog to pop up. I'm not aware of any programmatic way to do that. I would agree with RoToRa's comment that such a capability is probably a security flaw.

    If your ultimate goal is to create a file input element that can be styled differently from the browser's defaults, check out this article.

    T.J. Crowder : For completeness: That will call the DOM0-style handler (which is what he has). Any DOM2-style handlers will not get called.
    Pointy : I was going to write that too, but I checked the Mozilla documentation and wrote a test file, and there is indeed a "click" function on input elements in Firefox.
    T.J. Crowder : @Pointy: He did say "...that aren't form inputs..."
    Pointy : oh durr well I haven't had enough coffee apparently. However the question does in fact seem to have to do with inputs, so there is a "click" to call. Firefox doesn't obey that, however, for inputs of type "file" as far as I can tell.
    T-joe : Thank you guys.
  • Firefox does not allow you to programatically call click() on a file input.

  • This article achieves the same in a different way Styling an input type="file"

Mod Rewrite - Redirecting based on having GET parameters or not

I want to redirect these URLs:

http://example.com/search to http://example.com/?page=search

http://example.com/search?q=keyword to http://example.com/?page=search&q=keyword

I am trying to use this in .htaccess but doesn't work:

RewriteRule ^search$ ?page=search [nc]
RewriteRule ^search\?(.*)$ ?page=search&$1 [nc]

What am I doing wrong?

From stackoverflow
  • Assuming you want to direct the request to the index.php file include the file in the rules. E.g.

    RewriteRule ^search$ index.php?page=search [L]
    

    Give it a try.

    XaviEsteve : Hi Andreas, it is working for the "/search" but not when adding parameters. Any ideas for passing the parameters?
    andreas : RewriteRule ^search/([^/])+?$ index.php?page=search&q=$1 [L] (please try and let me know)
    andreas : Also check out: http://www.modrewrite.com/
    XaviEsteve : Thanks Andreas! I've replaced the `+` to `*` and moved the quantifiers inside the parenthesis and it works now. Here it is: `RewriteRule ^search/([^/]*?)$ index.php?page=search&q=$1 [L]`.

Wpf binding with nested properties

ViewModel

I have a property of type Member called KeyMember. The 'Member' type has an ObservableCollection called Addresses. The Address is composed of two strings - street and postcode .

View

I have a ListBox whose item source need to be set to ViewModels's KeyMember property and it should display the Street of all the Past Addresses in the Address collection.

Question

My ViewModel and View relationship is established properly.

I am able to write a data template for the above simple case as below

<ListBox ItemsSource="{Binding KeyMember.Addresses}">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="Address">
            <TextBlock Text="{Binding Street}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I am curios to know how to write the DataTemplate if I change KeyMember from type Member to ObservableCollection< Member > assuming that the collection has only one element. I am not sure whether this is a valid scenrio and it's implementation feasibility.

PS: I know that for multiple elements in collection, I will have to implement the Master-Detail pattern/scenario. I am looking into this at the moment.

From stackoverflow
  • If you want to bind to the 0th element, you can do {Binding Path=[0].Addresses}, and likewise for any other elements in a collection that supports array-style indexing. I agree with Wonko though that this is a rather unusual requirement.

    byte : JustABill, Thank you for the reply. As I mentioned earlier this is not a requirement for my work. This question is more on lines of curiosity. Being a novice, bindings like {Binding Path=[0].Addresses} is something new that I didn't know and is exactly what I wanted to know - whether explicityly binding to a particular element in collection is possible or not. Ofcourse I would not be using this in my work as I will not explicitly bind to a particular element from collection. But it's always good to know what is possible even when, in practice, it might not be the best thing to do.
    JustABill : Ah, curiosity is fine. You'll see the [0] in Binding Paths commonly when you get to validation - it's a common (but poor) way to retrieve the current error message. Both in that specific case and possibly in yours, if the collection is ever null you should not do this because trying to get the [0] element from a null collection will make WPF throw an exception, which you won't see but which will slow down your program.
    byte : Thanks. Is there any online resource where I can read advance data binding techniques?
    JustABill : I'm not aware of anything specific to recommend, but most of the fun stuff I've seen involves the RelativeSource parameter. So you can (to use a stupid example) make a UserControl the same background color as that of its parent Window. So maybe look at that.

Testing methods called on yielded object

I have the following controller test case:

def test_showplain
  Cleaner.expect(:parse).with(@somecontent)
  Cleaner.any_instance.stubs(:plainversion).returns(@returnvalue)

  post :showplain, {:content => @somecontent}

end

This works fine, except that I want the "stubs(:plainversion)" to be an "expects(:plainversion)".

Here's the controller code:

def showplain
   Cleaner.parse(params[:content]) do | cleaner |
      @output = cleaner.plainversion
   end
end

And the Cleaner is simply:

class Cleaner

   ### other code and methods ###

   def self.parse(@content) 
     cleaner = Cleaner.new(@content)
     yield cleaner
     cleaner.close
   end

   def plainversion
      ### operate on @content and return ###
   end

end

Again, I can't figure out how to reliably test the "cleaner" that is made available from the "parse" method. Any suggestions?

From stackoverflow
  • This is a little tricky. The easiest a approach will be to break the problem into two pieces: the testing of the controller and the testing of the controller.

    You have the testing of the controller set-- just remove your expectation around plainversion call.

    Then, separately, you want to test the Cleaner.parse method.

    cleaner = Cleaner.new('x');
    cleaner.expects :close
    
    Cleaner.expects(:new).returns(cleaner)
    
    called_with = nil
    Cleaner.parse('test') do |p|
      called_with = p
    end
    assert_equal p, cleaner
    

    That is not very clear what's going on. Makes me think that there is a simpler version of this. Can cleaner just be a simple function that takes a string and returns another one? Skip all the yielding and variable scoping? That will be much easier to test.

    Todd R : The nice thing about the parse method is that it gives a Cleaner that is completely ready to use, and ensures close is called. This is fully tested in the Cleaner class. Even though the above code show using the Cleaner to retrieve "plainvesion", there are other operations that could be done with a fully prepared Cleaner. In the Controller, we could create a new Cleaner, make sure it is fully inited, use it, then make sure we close it. But that just seems so . . . not Rubyish. Especially when it's so convenient to use parse, use the Cleaner, and be done with it.
    ndp : Maybe if you just take the @output out of the block and pass it back to the caller then your controller method will be easier to test-- just test that the cleaner was called and you're done. As you say, your cleaner is tested elsewhere.

Flex: How can I use the @ContextRoot in a Button or LinkButton

I'm trying to create a button that will simply link back to the context root. I noticed flex has a @ContextRoot attribute that appears to work only in certain cases. For example, if I try to use it in the following mxml:

<mx:Button label="Back to Root" click="navigateToURL(new URLRequest(@ContextRoot()), '_parent')"/>

I get the following error: Error: Attributes are not callable.

I can't seem to find this technique explained anywhere, is there another way?

Thanks for the help! Dave

From stackoverflow
  • Well, the cleanest way I found was to use a function in the script block, and not use @ContextRoot like:

    private function goBacktoHompage():void
     {
      baseURL = Application.application.url;
      var tempUrl:String = baseURL.substr(7,baseURL.length);
      var tempUrlArr:Array = tempUrl.split("/");
      var contextRoot:String = tempUrlArr[1];
      var u:URLRequest = new URLRequest("/" + contextRoot);
      navigateToURL(u,"_parent");
     }
    

    I would assume there is an easier way that could use @ContextRoot, so any other answers that don't use relative paths would be welcomed!

    Thanks to these sites for the help:

    http://blog.devsandbox.co.uk/?p=174

    [Adobe help docs on passing arguments]

    -Dave

  • Thanks to http://devgirl.wordpress.com/ for this solution! I think it is better than the Application.application.url solution:

    Use the HTTPService control:

    <mx:HTTPService id="home" url="@ContextRoot()"/> 
    

    And then in Action Script:

     navigateToURL(new URLRequest(home.url),"_parent");
    

    works like a charm!

Is there a bug/issue tracking system which integrates with Mercurial?

I've used Trac/Subversion before and really like the integration. My current project is using Mercurial for distributed development and it'd be nice to be able to track issues/bugs and have this be integrated with Mercurial. I realized this could be tricky with the nature of DVCS.

From stackoverflow
  • TracMercurial integrates Trac with Mercurial. Assembla provides free Mercurial hosting with Trac integration.

    The idea is that you have a central repository as your master and upload all the subsidiary changes from local repositories into the main one.

  • Fogbugz, here is the page to config Fogbugz and Mercurial

    tghw : Kiln (http://kilnhg.com/) provides even tighter integration between FogBugz and Mercurial
  • There is also a plugin to integrate Mercurial with Jira. See the webpage for the plugin.

  • I'd also like to add Redmine to the list. I started with Trac, but I found the mercurial support (and the administrative interface for everything) to be much better in Redmine.

    Matthew Schinckel : And Redmine is way better if you are running multiple projects.
  • BugTracker.NET now supports Mercurial integration in the same way it supports Subversion and git. BugTracker.NET is a free, open source, ASP.NET bug tracking system.

    Other free, open source bug trackers that support Mercurial:

  • Bugs Everywhere is a distributed bugtracking system that supports Mercurial.

    dimo414 : This looks promising, but very experimental. Do you know of any kind of tutorial for installing, setting up, and using? The website seems pretty limited and/or broken at the moment.
  • If you're open to another suggestion, you can try [Artemis].[1]

    Though I haven't used it yet, it looks easy enough.

  • There's a BugzillaExtension for adding a comment to a Bugzilla bug each time you mention its number.

  • Mantis has a beta integration for Mercurial: blog-post and code (currently offline).

  • Jira integrates using a plugin. Its a great tool.

    http://www.atlassian.com

  • I just put together a command-line bug tracker called b for Mercurial which, although it's not as powerful as Trac and the like, is exactly what a lot of situations call for. It's best feature is how easy it is to set up - install the Mercurial extension, and all your repos have a bug tracker at their disposal. I find this incredibly useful on smaller projects that I can't/don't want to set up with a fully fledged tracker living on a server somewhere, just hg b and go.

  • I recently developed a Trac plugin that integrates some Mercurial functionality that TracMercurial Plugin doesn't support yet, it's called TracMercurialChangesetPlugin. It allows you to search in your changesets, to have the cache synced, to view a changelog in your related tickets...

    You can read about it at http://tumblr.com/x8tg5xbsh

Are there ways to improve NHibernate's performance regarding entity instantiation?

Hi folks,

while profiling NHibernate with NHProf I noticed that a lot of time is spend for entity building or at least spend outside the query duration (database roundtrip). The project I'm currently working on prefetches some static data (which goes into the 2nd level cache) at application start. There are about 3000 rows in the result set (and maybe 30 columns) that is queried in 75 ms. The overall duration observed by NHProf is about 13 SECONDS! Is this typical beheviour? I know that NHibernate shouldn't be used for bulk operations, but I didn't thought that entity instantiation would be so expensive.

Are there ways to improve performance in such situations or do I have to live with it?

Thx, denny_ch

From stackoverflow
  • I've not done this but I think you may ned to imlement your own entity creation interceptor. There are some specs here.

    By providing your own implementation you can decide on the allocation and disposal strategy and thus optimise your performance in the entity creation.

    denny_ch : How will an additional interceptor help on improving performance?
    mxmissile : implementation != additional

i need help with using string template with .net mvc2, where do i get started?

Hi, I'm trying to try out string template with .net mvc, but i can't find any tutorial that is good for newbies and give me a step for step guidance through how to implement string template with c# and .net mvc2... any help is really very very very very ........ very appreciated Lina

From stackoverflow

ASP.NET Webforms Membership sample application

Is there a quickstart application sample that demonstrates using the Login controls, roles, profile and uses best practices?

From stackoverflow
  • Find following links useful

    http://authors.aspalliance.com/aspxtreme/webapps/security/AspNetMembership.aspx

    http://aspalliance.com/1658_Using_Forms_Authentication_with_Membership_Providers_in_ASPNET_20.2

    This is one of the best link I found for membership authentication

    http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx

    Hope this will help!

    : Jinal - I am looking for a quickstart coding sample demonstrating the use of the membership API and none of hte links mentioned have any code samples.
  • The ASP.NET Web Site Administration Tool uses the Membership API. I think all of the source code is in there, you'll just have to import it into a project by yourself.

    C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles

    : Does the WS Admin tool demonstrate the use of roles, login controls and profile? (I have used it to add members). Also, can you explain what you mean when you say "import it into a project"?
    Sky Sanders : @user there are no profile management features and is in no way an example of best practices. It also relies heavily on impersonation making it's usefulness as an example of production use of the Membership and Roles providers questionable. In any case I have already created an updated vs08 web app project and fixed some bugs that MS has left in for the last 7 years. You can find it here: http://spikes.codeplex.com/releases/view/40655 Be sure to check the readme on how to start it up.
    Greg : @code poet: I see we meet again. If you post your answer in an answer, I'll delete this.
    Sky Sanders : How bout I just give you an upvote and leave it as is. You can add the URL and recap to your answer. While the OP may get some value from studying the app, it really does not meet the criteria stated in the question. But the reference you provide does have merit - I just provide some code. Cheers
  • I am sure following link will be useful..

    It is step by step guide

    http://aspnet.4guysfromrolla.com/articles/120705-1.aspx

    : @Jinal - I do have a number of links with tutorials and articles. What I am looking for is a code sample. Please do not post multiple answers. Instead, edit your earlier answer.

Using view in several pages

Hi, everybody! I have a view (let's say x) that I want to use at some parts of several pages (let's say y, z, t). The action (let's say a) that called from view (x) calls a web service that returns me an id (let's say i) and returns the same view (x) again. And in the pages (y, z and t) I want to do different things using this id (i). How can I realise this scenario? Thanks in advance.

From stackoverflow
  • Why not have the view (x) just be a form that you control with AJAX (JQuery) from each of the parent views (y,z,t)?

Apache rewrite_mod: RewriteRule path and query string

I currently have a website with a standard web interface on index.php, and I made an iPhone-friendly version in iphone.php.
Both pages handle the same arguments.

It works fine when I manually go to .../iphone.php, but I'd like to rewrite anything on .../path/ and .../path/index.php to iphone.php if %{HTTP_USER_AGENT} contains mobile, and optionally add the query string (not sure if/when I'd need to add it).

So far, this is what I have in my .../path/.htaccess:

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^.+mobile.+$ [NC]
RewriteRule index.php?(.*) iphone.php?$1 [L]
RewriteRule index.php      iphone.php [L]

The problems are, it matches index.php in any subfolder, and it won't match .../path/?args

From stackoverflow
  • How about

    RewriteEngine On
    RewriteCond %{HTTP_USER_AGENT} ^.*mobile.*$ [NC]
    RewriteRule /path/index.php /path/iphone.php [QSA,L]
    

    EDIT: QSA is Query string append, so you don't need to handle that differently. If you want you can add an extra parameter too, like:

    RewriteRule /path/index.php /path/iphone.php?extra=param [QSA,L]
    
    1. RewriteCond is applied to exactly one rewrite rule.
    2. To match all user agents containing 'mobile' in it's name .* - 0 or more any character should be used in ^.+mobile.+$ statement.
    3. RewriteRule by default doesn't include query string - [QSA] flag should be used to include query string.
    4. RewriteRule uses regexp - you should use \. to escape dots.
    5. RewriteRule automatically saves query string the same, if not specified another.

    UPDATED:

    Complete .htacess:

    RewriteEngine On
    
    RewriteCond %{HTTP_USER_AGENT} ^.*mobile.*$ [NC]
    RewriteRule ^(.*)index\.php $1iphone.php [L]
    
    RewriteCond %{HTTP_USER_AGENT} ^.*mobile.*$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule ^(.*)$ $1iphone.php [L]
    
    1ace : Thanks a lot for all those clarifications, but this does not resolve my main concern: `.../path/?args` is still not handled…
    SergeanT : I've added possible fix of this problem. Do you need to rewrite `.../path?args` (without trailing slash) too?
    1ace : I did try that, but Apache returns a 500 when I do. My guess is `^(.*)$` goes in some kind of a loop, and never gets out.
    SergeanT : You're right. I've added `RewriteCond %{REQUEST_URI} !^.*iphone\.php.*` to prevent loop. It's strange to me that `[L]` seems not work.
    1ace : For a second here, I thought you had _the_ solution... It does help with the `/?` problem, but any other requested URI (like, say, my `style.css`) now returns a 404 :( There has to be some way to match `.../?` without matching everything... The only option I see is to counter-match every request URI I still need to let through
    SergeanT : To prevent rewriting existing files I've added `RewriteCond %{REQUEST_FILENAME} !-f` (sounds like not existings file) for `^(.*)$` rewrite rule.
    1ace : It works ! Thank you very much, you saved me quite a lot of tries and testings :)
    1ace : Actually, we don't need `RewriteCond %{REQUEST_URI} !^.*iphone\.php` anymore, as it's taken care of by `RewriteCond %{REQUEST_FILENAME} !-f` and `iphone.php` has to be a file for the whole thing to work.