Friday, April 8, 2011

Is it possible to have a web browser scroll to show CSS fixed position items that are outside the viewport of the web browser?

I am trying to create a CSS layout where the page looks like it's in the middle of the forest. There is a left and right div with the background trees, some header divs that show the top of the page with various wildlife, and some footer divs that show the bottom with more wildlife that matches up with the left and right div background images, all of which is positioned using "position: fixed" in CSS.

Then there is content in the middle that is positioned normally and scrollable. That all works fine.

The problem I'm having is that the background forest layout is fixed at 1204x768 but of course some web browser windows may not be that large. Unfortunately while the content will scroll as intended, the fixed position elements will never be shown if they are outside the size of the browser window. Clearly not acceptable.

I've tried setting overflow: scroll and height: 768 on the .body and .html elements in the stylesheet but no luck.

Note that I am positioning everything with top: and left: values in the CSS. I know I could get around this by using bottom: and right: but the problem is that the footer images wouldn't line up.

This may just not be possible in which case I'll have to rework the graphic design, but if it is possible I'd love to know how!

From stackoverflow
  • You could have two pictures: 1) a right that contains the right trees and the bottom footer image and 2) and left image with the left trees. Make the bottom footer much wider than it needs to be and the trees (left and right) much taller than they need to be.

    Then set the right picture to bottom: and right: and set the left picture to bottom: left:. This will force the pictures to always be on the outsides of the page, no matter the browser size. Then set the z-index of the right picture to be just behind the left picture. It will then always look like the page will be bordered. Or you can set a firm width and height on the parent container, and they will always be on the border of the container. You can also set a min-width and -height if you need to have a certain minimum sizes.

    As for things not being visible at a certain resolution, you're really not going to get around this. You could have two sets of pictures, one for normal resolutions, and one for smaller resolutions. Then you can get the width and height of the browser with $(window).height() and $(window).width() with jQuery, and load the appropriate pictures.

    EDIT: After looking at your site, i'm pretty sure the second part of that (setting a fixed width for a container, then putting a bottom right picture and bottom left picture) will work for what you want. That will force the page to be a certain width, and thus have the entire border visible.

  • of course some web browser windows may not be that large

    Or indeed that small! The likelihood of the browser window actually being exactly the right size to put your decorations on the edges is quite small; that's always the problem with fixed layout.

    I know I could get around this by using bottom: and right: but the problem is that the footer images wouldn't line up.

    Yes, designing images that can alter their joins in response to page size changes is more work, but it's doable. You would have to export the ‘bird+foliage’ layer and the ‘squirrel+foliage’ layer as standalone transparent images, then lay them over the top of a longer side image.

    To make the object edges nice and smooth would require PNG's 8-bit transparency, which would necessitate a PNG-rendering hack for IE6. Not the end of the world though.

    Unfortunately while the content will scroll as intended, the fixed position elements will never be shown

    Is that a problem? They are only decorational in nature.

    I've tried setting overflow: scroll and height: 768 on the .body and .html elements

    For this approach you would need to set ‘overflow: auto; height: 768px;’ on a wrapper <div> which holds both your #sidebar-left and your #content.

How does one associate Google Analytics with a particular authenticated user?

What method would you use to associate tracking information in Google Analytics with a particular named user?

I want to be able to do custom reports, and ultimately drill down on usage by user.

EDIT
I was thinking that perhaps the EventTracking API would be able to help somehow.

Also, referring to this documentation.

From stackoverflow
  • Since Google Analytics isn't aware of users who are logged into your site you'd have to do that sort of tracking within your site's software itself. If there isn't some sort of plugin or extension out there already you'll probably have to write one yourself that keeps track of what your users do when their logged in.

  • You could add the user's username as a tracking/segmentation) variable...

    pageTracker._setVar(username);
    

    You can only use one _setVar per page, though...

    http://www.google.com/support/analytics/bin/answer.py?answer=57045

    http://groups.google.com/group/analytics-help-basics/browse_thread/thread/07e29dc610050971

    Jason : Yes, I found this too. Did you do this successfully?
    Stobor : No - I remembered seeing it when I was playing with getting GA set up for our environment, but we didn't end up wanting anything like that so I never got to try it. Seemed like it did what you wanted, though.
    ontangent : we found it more use for tracking logged in users vs not in general, they tend to use different parts of the site

flash AS3 how do I remove stage event listeners

hello,

I'm building an animation in flash and as3, I have a function in which I add a stage eventListener, stage.addEventListener(Event.ENTER_FRAME, setScrollPercent, false, 0, true);

Since this event is set inside a function of a function, "two functions deep," How can I reset all stage event listeners from outside of the functions without getting an error?

From stackoverflow
  • What errors are you seeing? The nesting level shouldn't have anything to do with it, since the listeners are just registered by the parameters, so as long you call remove with the same three key parameters you used for add, you should be fine.

    Is your real question how to get a reference to the listener object to the outside scope? If so, there are several possible solutions and the best way to do it depends on the structure of your code.

    -- MarkusQ

  • Best practices with AS eventlisteners are:

    • Make it weak (as you've done, the last parameter of addEventListener)
    • Set the event listener to null after handling (strictly speaking not required if you have set it to be weak)

    Flex does not give you destructors. It has its own Garbage Collector running behind the scenes managing memory. It cleans up a piece of memory once there are no references to it. Well, strong references. All objects by default have a strong reference. Event handlers, since they tend to be a performance bottleneck, have this special ability of declaring themselves weak -- a weak reference. This is of course possible only when you are attaching the event handlers using the addEventHandler() function. Weak references are not taken into account by the GC and hence, when all strong references are gone, they'll be automagically garbage collected, freeing you from the tension of having to do a =null manually. Which is what you'd otherwise do when you don't specify the parameter. By default, even handlers are created as strong references.

    However, marking them weak has a side-effect. They can vanish into thin air without you ever knowing about it. Eventually, you will know, but in terms of a nasty bug. Is that what's causing your problems? Maybe, may be not. You'll have to experiment. Also, it'll help if you can provide us with some more detail like the exact error code, some source.

    Hope this helps. Happy flexing :)

    Ole Media : can you add an example? I'm new to AS3 and I really don't know what does weak mean.
  • The answer to your question, and I realize you had a problem with scope, because I just answered a question you had on scope, is that you are working with stage. Consider the stage global as it is the canvas in which all of your display objects are drawn.

    The following will work anywhere!!!

    stage.addEventListener(Event.ENTER_FRAME, setScrollPercent, false, 0, true);
    

    Now, the error that your talking about, IM GUESSING, is that you merely set the above to removeEventListener when you were ready which will not work.

    The removeEventListener function DOES NOT accept five parameters like its sibling addEventListener, it only allows three ignoring priority and weak-reference, as the following shows.

    //The following removes YOUR stage Event.ENTER_FRAME listener from any scope.
    stage.removeEventListener(Event.ENTER_FRAME, setScrollPercent, false);
    

    hope this helps, remember that stage is the global root in a sense, and be careful of root, it actually works how it is supposed to now in the fact that calling root is now relative to the swf you call it from, not the stage, unless the stage is the root of the current scope.

    Brian Hodge
    hodgedev.com blog.hodgedev.com

Differences in the Mac system_profiler

I am using system_profiler to view the USB hardware details connected to a Mac, however there are some differences between running this on Mac OS X 10.4 and 10.5. For example, in 10.5 the keys for various attributes have an alphabet letter prefix. More importantly, I can't get the location_id attribute (in the SPUSBDataType dataType) in 10.4. Any ideas on why this difference exists and ways to work around it?

From stackoverflow
  • Have you tried using ioreg? I don't have access to 10.4 but since ioreg is lower level, it might be a better approach for what you're trying to achieve.

    ioreg -l -n IOSerialBSDClient
    

How do I scroll the text on my div with limited height?

Hi guys,

So I have blocks of paragraphs that doesnt fit on my page, my solution is to have a scrolling method so when the user hovers on the down arrow, it will scroll down the paragraph and reveal more text.

So I attached an image of my project, as you can see I have scroll down and scroll up buttons.

Here's the HTML file of my project:

<div id="content1" class="scrolling-content">
                <div>
                    <div id="story" style="overflow:hidden; width:40%;">
                        <h2 style="font-size:30px;">Quirino's Story</h2>
                            <p>Elpidio Quirino was a Filipino politician, and the sixth President    of the Philippines.</p>
                            <p>He was born in Vigan, Ilocos Sur to Mariano Quirino and Gregoria Rivera, Quirino spent his early years in Aringay, La Union. He received secondary education at Vigan High School, then went to Manila where he worked as junior computer in the Bureau of Lands and as property clerk in the Manila police department. He graduated from Manila High School in 1911 and also passed the civil service examination, first-grade.</p>

                            <p>Quirino attended the University of the Philippines. In 1915, he earned his law degree from the university's College of Law, and was admitted to the bar later that year. He was engaged in the private practice of law until he was elected as member of the Philippine House of Representatives from 1919 to 1925, then as Senator from 1925 to 1931. He then served as Secretary of Finance and Secretary of the Interior in the Commonwealth government.</p>

                            <p>In 1934, Quirino was a member of the Philippine Independence mission to Washington D.C., headed by Manuel L. Quezon that secured the passage in the United States Congress of the Tydings-McDuffie Act. This legislation set the date for Philippine independence by 1945. Official declaration came on July 4, 1946.</p>

                            <p>During the Battle of Manila in World War II, his wife, Alicia Syquia, and three of his five children were killed as they were fleeing their home.</p>

                            <p>After the war, Quirino continued public service, becoming president pro tempore of the Senate. In 1946, he was elected first vice president of the independent Republic of the Philippines, serving under Manuel Roxas. He also served as secretary of state.</p>

                            <span onmouseover = "start_scroll_up()"; onmouseout="stopscrolling";  id="up"><img src="images/arrow_up.png" /></span>
                    <span id="down" onmouseover="start_scroll_down()"; onmouseout="stopscrolling"; ><img src="images/arrow_down.png" /></span>
                    </div>
                </div>
            </div>

And here's the Javascript file:

var UpdateInterval = 20;
var PixelPerInterval = 2;
var scrollInterval;

function startScrollUp() {
    scrollInterval = setInterval(scrollUp, UpdateInterval);
}

function startScrollDown() {
    scrollInterval = setInterval(scrollDown, UpdateInterval);

function scrollDown() {
    document.getElementById('story').scrollHeight += PixelPerInterval;
}

function scrollUp() {
    document.getElementById('story').scrollHeight -= PixelPerInterval;
}

function stop_scrolling() {
    clearInterval(scrollInterval);
}

Thanks guys!!

From stackoverflow
  • I have amended your code and produced a working example. This is a complete html page.

    <html><head>
    <title></title>
    </head>
    <body>
    <div id="content1" class="scrolling-content" style="height:100px;overflow-y:auto;">
    
                            <h2 style="font-size:30px;">Quirino's Story</h2>
                                <p>Elpidio Quirino was a Filipino politician, and the sixth President                       of the Philippines.</p>
                                <p>He was born in Vigan, Ilocos Sur to Mariano Quirino and Gregoria Rivera, Quirino spent his early years in 
    
    Aringay, La Union. He received secondary education at Vigan High School, then went to Manila where he worked as junior computer in the Bureau 
    
    of Lands and as property clerk in the Manila police department. He graduated from Manila High School in 1911 and also passed the civil service 
    
    examination, first-grade.</p>
    
                                <p>Quirino attended the University of the Philippines. In 1915, he earned his law degree from the university's 
    
    College of Law, and was admitted to the bar later that year. He was engaged in the private practice of law until he was elected as member of 
    
    the Philippine House of Representatives from 1919 to 1925, then as Senator from 1925 to 1931. He then served as Secretary of Finance and 
    
    Secretary of the Interior in the Commonwealth government.</p>
    
                                <p>In 1934, Quirino was a member of the Philippine Independence mission to Washington D.C., headed by Manuel L. 
    
    Quezon that secured the passage in the United States Congress of the Tydings-McDuffie Act. This legislation set the date for Philippine 
    
    independence by 1945. Official declaration came on July 4, 1946.</p>
    
                                <p>During the Battle of Manila in World War II, his wife, Alicia Syquia, and three of his five children were killed 
    
    as they were fleeing their home.</p>
    
                                <p>After the war, Quirino continued public service, becoming president pro tempore of the Senate. In 1946, he was 
    
    elected first vice president of the independent Republic of the Philippines, serving under Manuel Roxas. He also served as secretary of 
    
    state.</p>
    
                </div>
                                <span onmouseover = "startScrollUp();" onmouseout="stop_scrolling();";  id="up"><img src="images/arrow_up.png" 
    
    /></span>
                        <span id="down" onmouseover="startScrollDown();" onmouseout="stop_scrolling();" ><img src="images/arrow_down.png" /></span>
    
    <script type="text/javascript">
    var UpdateInterval = 20;
    var PixelPerInterval = 2;
    var scrollInterval;
    
    function startScrollUp() {
        scrollInterval = setInterval(function(){scrollUp()}, UpdateInterval);
    }
    
    function startScrollDown() {
        scrollInterval = setInterval(function(){scrollDown()}, UpdateInterval);
    }
    function scrollDown() {
        document.getElementById('content1').scrollTop += PixelPerInterval;
    }
    
    function scrollUp() {
        document.getElementById('content1').scrollTop -= PixelPerInterval;
    }
    
    function stop_scrolling() {
        clearInterval(scrollInterval);
    }
    </script>
    </body>
    

    You were close though.

    Cheers,

    Andrew :-)

    REA_ANDREW : Glad I could be of some help. :-)

How to programatically pass arguments to OnStart method of a windows service ?

Hi All, How do i programatically pass in arguments to OnStart method of a Service, which I further need to propagate to the Elapsed event of the Timer inside the service.

  • Amit
From stackoverflow
  • You could consider having the OnStart method read the arguments from a configuration file and programatically update that, using either a separate application.

  • At the simplest level: when you call ServiceBase.Run, you get to give it the service instances to execute. Simply declare this as a public property on your service, and assign prior to calling Run:

            Service1 myService = new Service1();
            myService.SomeProp = 1;
            ServiceBase.Run(myService);
    

    Then read SomeProp in your service:

        public int SomeProp { get; set;}
        protected override void OnStart(string[] args)
        {
            int prop = SomeProp;
        }
    

    You can also use the service args, but that is from the external caller (service registration) - not programatically (per the question).

Rounding to nearest 100

First number needs to be rounded to nearest second number. There are many ways of doing this, but whats the best and shortest algorithm? Anyone up for a challenge :-)

1244->1200
1254->1300
123->100
178->200
1576->1600
1449->1400
123456->123500
654321->654300
23->00
83->100

From stackoverflow
  • Is this homework?

    Generally, mod 100, then if >50 add else subtract.

    Senthoor : No its not home work :-)
    John Leidegren : What the hell Brian! mod and if-then-else that's gonna be really slow. If you're using integers check David's answer. It's a branch-less common way to solve this problem. It works with floating-point numbers as well.
    Senthoor : I myself came up with this answer in Ruby. numbers.each {|number| puts number + '->' + number.gsub(/\d\d\d$/,(number[number.size-3,1].to_i + number[number.size-2,1].to_i / 5).to_s+'00')}
  • For input n:

    (n + 50) / 100 * 100
    

    using integer division.

    Note that many languages/libraries already have functions to do this.

  • This will do it, given you're using integer math:

    n = (n + 50) / 100 * 100
    

    Of course, you didn't specify the behavior of e.g., 1350 and 1450, so I've elected to round up. If you need round-to-even, that'll not work.

  • 100 * round(n/100.0)
    

What page-image generating technology should I use?

I'm building a desktop application right now that presents its human-readable output as XHTML displayed in a WebBrowser control. Eventually, this output is going to have to be converted from an XHTML file to a document image in an imaging system. Unlike XHTML documents, the document image has to be divided into physical pages; additionally - and this is the part that's killing me - there need to be headers and footers on these pages.

Much as I would like to, I can't simply make the WebBrowser print to a file - the header/footer options it supports aren't anywhere near sophisticated enough. So I'm casting about trying to figure out what the right technology is for generating these images.

It seems likely to me (though it's not mandatory) that what I'll end up doing is producing PDF versions of the HTML documents (so that I can add headers and footers) and then rendering the PDFs as TIFFs, which is the ultimate format that the imaging system wants. So what I'm considering:

  • Use some kind of XHTML-to-PDF conversion software. The problem with this is that without doing a lot of evaluation and testing I can't figure out if the products I've looked at even have the ability to do what I need, which is to take existing XHTML documents, decorate them with headers and footers and paginate them.

  • Use XSL-FO to generate the PDFs. Being a ninja-level XSLT geek helps here (that's how I'm producing the XHTML in the first place), but it still seems like an awkward and slow solution with a lot of moving parts. Also this means I'm sticking a big clunky Java program into the middle of my nice clean .NET system, though I'm certainly enough of a grownup to do that if it's the right answer.

  • Use some other technology that I haven't even thought of yet, like LaTeX. Maybe there's some miraculous page-imaging tool that turns XHTML directly into TIFFs with page headers and footers. That would be ideal.

My primary concerns are:

  • I'm building a commercial product; whatever technology I use needs to be affordable and supportable. It doesn't have to be free.

  • I don't want to disappear down a rabbit hole for three months banging on this stuff to get it to work. This intuitively seems like the kind of problem space where I can lose a lot of time just evaluating and rejecting tools.

  • Whatever solution I adopt needs to be relatively immune to formatting changes in the XHTML. The whole reason I'm using XSLT and producing XHTML in the first place is that the documents I'm producing are being dynamically assembled using business rules that change all the time.

I've spent a lot of time searching for alternatives and haven't found anything that's obviously the answer. But maybe one of you fine people has already solved this problem, and if so, I would like to stand on your shoulders.

From stackoverflow
  • have you thought about using postscript?

    ps: what kind of headers/footers you need - your custom ones to put pages in between? if so, postscript or PDF is probably the best. but it will be very difficult to create xhtml+css to pdf converter. basically, you would need to have library that is able to parse both xhtml and css (+any objects such as images, flash etc.)

  • PrinceXML is an XHTML/CSS to PDF converter. It seems to have the features you need:

    • Page headers/footers, page numbering and duplex printing.

    I realize you'll probably want more extensive answers than this one (I'm sorry, but I haven't evaluated the product), but nevertheless, I hope it helps!

    Robert Rossney : This was startlingly easy to implement in my prototype. Pity the server licensing is so pricey.
    onnodb : Yeah, I was also taken back by the high prices. Perhaps you could contact their sales department to see if you can get a special deal? Seems to work sometimes...
    Robert Rossney : Yeah, we could conceivably get OEM pricing. But even with a 50% discount, I'm adding $2K to the price of my software (or, more realistically, reducing my profits by $2K.) I'm pretty strongly motivated to find another solution. Though everything else about Prince is perfect.
  • If tiff is your goal, this might be a free and low risk approach:

    1. Use a component to create an image for a given url. I'm not sure which tool we used for it, but GIYF: I just stumbled upon SmallSharpTool's WebPreview that seems to do the job
    2. Make sure it can create an image of the entire page, ie the entire's scrollable area.
    3. Use ImageMagick to do all the image manipulation, such as cutting it into multiple pages, adding your own headers, footers and page numbering and conversion to tiff.

    I have personally used the above techniques separately in C# projects (console apps and websites) with success so I can almost guarantee this will work.

  • Edit (2009-03-29 9:00 AM PST) Posted sample conversion.
    Edit (2009-03-23 12:30 PM PST, published to CodePlex) I developed a solution for this and posted it to CodePlex. The published version 2.0 is written using the WPF MVVP pattern. TIFF files (one per page) are output to c:\Temp\XhtmlToTiff. XAML and XPS formats are created as well. A compiled,installable version is available at CricketSoft.com


    Have you tried the "Microsoft XPS Document Writer"? This a software-only printer that generates paged output from a variety of sources, including web pages.

    There is an SDK for working with XPS documents and Open XML docs in general. Here is a How-to article by Beth Massi: "Accessing Open XML Document Parts with the Open XML SDK".

    +tom

    Robert Rossney : I need more control over formatting than I can get by simply redirecting IE's printed output to a driver, unfortunately. Generating the underlying XPS seems, to put it mildly, non-trivial.
    Tom A : ah, i may have a bit of help for you here. I decided to code up a sample. Pls hold... (and thx for the "Answered".)
    Robert Rossney : Well the "answered" was done automatically when the bounty expired. Not actually what I intended, but the system works the way it works.
    Tom A : hmm, there must be more detail on how it works -- the automatic bounty was only 50%.
    Tom A : Ah, my temp link didn't take...
  • It all depends on how important quality is for the generated documents. It also matters what other operations you need to do with the document.

    I'm building a desktop application right now that presents its human-readable output as XHTML displayed in a WebBrowser control. Eventually, this output is going to have to be converted from an XHTML file to a document image in an imaging system.

    Looks like your application is a soft-form of sorts. You generate filled-in forms and save them.

    [...]there need to be headers and footers on these pages.

    This is the easy part. You can use templates and merge the data with the static header/footer template. You sound as if you are doing VDP. Hm. Let's move on.

    I can't simply make the WebBrowser print to a file - the header/footer options it supports aren't anywhere near sophisticated enough.

    Why so? All you need is a capable driver.

    It seems likely to me (though it's not mandatory) that what I'll end up doing is producing PDF versions of the HTML documents

    Again, it is not clear why you would want PDF right away. PDF is a document interchange format. Not a PDL per se. PostScript is a much better choice. Yes, I know there are things like XPS, PCL and what not. However, the amount of rendering control and quality you get with PS is far too much to risk a cheaper solution. I say cheaper, because, you also need to keep in mind the sort of printing you can avail of. PostScript printers (not the ones with the clone RIPs) are costlier in general.

    Now, back to your PDF thing. Yes, of course you can generate PDF. It has certain advantages like:

    • Better support for transparency (and in general quality)
    • Archival
    • Interchange
    • Share it across for review
    • Preview/Preflight/Correct
    • Security
    • Stream encryption (for both security and the amount of data you transfer to the printer)
    • Use templates

    But remember do you have any printers to do native PDF ripping? Because you are otherwise doing a lossy PDF to PS/PCL conversion. And you've just lost the game. Which brings me back to PostScript ;)

    Robert Rossney : Interchange and archiving are the most compelling arguments for PDF. I'm not sure how important rendering control and quality are - a lot of the documents this system is replacing are Word documents covered with handwritten amendments, so user expectations are presently pretty low.
    dirkgently : Does that mean you are taking the Word docs through OCR? In that case, the OCR engine will generate tiffs for you. Or, do you need to generate the different (C,M,Y,K) planes as well?
    Robert Rossney : No, the customer's not presently imaging the Word documents. Producing PDF isn't *really* the requirement at this point - producing TIFFs of the formatted documents is. So I could conceivably use PS. What sort of tools do I need? I'm a babe in the woods with PS.
    dirkgently : PS drivers come by default with Windows. CUPS (on *nix and Mac) can also generate PS. That's all. Create a virtual minidriver and you're done. Print happily ever after.
  • Just my 2p but if you are an XSLT ninja I'd suggest sticking with that. You can avoid the nasty java program by looking at nFop which is a C# port of the apache FOP project. What's great is that you can simply take the assembly and use directly passing your XML and XSLT to it to get the PDF output you want.

    http://sourceforge.net/projects/nfop/

    Hope that helps.

    Robert Rossney : It never occurred to me that some clever person would redo FOP in .Net. I may have to do a little more looking into XSL-FO. I know I can get it to work at least.
  • You can use PISA for Python. It uses the reportlab toolkit to generate a pdf from html (using html5lib)

    Robert Rossney : It's remarkable how poorly organized the documentation for PISA is. (Like, there's not even a link to it on the PISA site. And never mind getting a complete list of dependencies.) But it does seem to work, eventually.
    jle : I found an example that took me right through it... I do remember the documentation being a bit skimpy.
    Robert Rossney : I spent an hour and a half yesterday just writing down the procedure my non-technical colleagues would have to follow to get pisa installed. But functionally it's very close to what I need. Wish it supported floating elements. Another hidden cost of table-less layout.
  • You could also try using PDFCreator and simply printing the document to PDF. PDFCreator acts like any normal printer and uses ghostscript to convert printer output to pdf, tiff, jpeg, or whatever you want. I think you can change header and footer items through IE's com interface and print directly from IE. PDFCreator has examples for different languages in the com folder of the install directory. I have used it and can vouch for it. Windows only though.

    Robert Rossney : An interesting idea, except that IE doesn't give you the ability to (say) define a DIV as your page footer, which is really the level of formatting control I need.
    jle : You might be able to add that with PDFCreator...
  • Do you really need to use XHTML/Web browser?

    I have been in this exact dilemma trying to generate good looking HTML reports and the solution I found is .... to drop HTML and use a "real" report generator, there are a lot of them out there, they all support all the pagination and header/footer options you can think about they can usually print to pdf and sometimes directly to images.

    HTML is just not the right technology for reports.

    Robert Rossney : It's not the right technology for reports, agreed. It is without question the right technology for the documents my program's producing.
  • Use some other technology that I haven't even thought of yet, like LaTeX.

    TexML, which is LaTeX semantics with XML syntax. To use that you can create XSLT, which would decorate your XHTML with TexML commands (see example)

    Robert Rossney : That's...daunting. It may be a very good answer for someone who knows LaTeX. I don't, so that's two hills to climb. There's also this: http://www.w3.org/2004/04/xhlt91/.
    vartec : Ok, as you mentioned it, I've assumed that you know it. ;-) As of [X]HTML to LaTeX tools, most of them create documents that are too plain, often even ugly.
  • ExpertPDF HtmlToPdf Converter (www.html-to-pdf.net) should be able to do exactly what you need. It's really simple to use, just reference the assembly in your project and start using it. I've used this product with great success in a couple of work projects.

    Robert Rossney : I've already started evaluating this. The great problem with this component is that you have to do a lot of manipulation in code; you can't (for instance) use markup in the document to provide content to headers and footers.
  • You mentioned your current desktop app exports results in xhtml. Since xhtml is well formed xml, you should get away with using xsl fo to export it to pdf.

    XML -> XSL-FO = PDF

    Here's a beginner's guide: http://www.devx.com/xml/Article/16430

    My company has used this technique in a java+cocoon webaplication for the Dutch government.

    Robert Rossney : Right, that's why I listed it as a possibility. I've used XSL-FO before. It works, but it's slow and ungainly.
  • http://iecapt.sourceforge.net/

    quoting from above website:

    IECapt is a small command-line utility to capture Internet Explorer's rendering of a web page into a BMP, JPEG or PNG image file. The C++ version also has experimental support for Enhanced Metafile vector graphic output. IECapt is available in a C++ and a C# version.

Scrape web page contents

I am developing a project, for which I want to scrape the contents of a website in the background and get some limited content from that scraped website. For example, in my page I have "userid" and "password" fields, by using those I will access my mail and scrape my inbox contents and display it in my page. Please help me to solve the problem, thanks in advance.

i done the above by using javascript alone . But when i click the sign in button the URL of my page(http://localhost/web/Login.html) is changed to the URL(http://mail.in.com/mails/inbox.php?nomail=....)which i am scraped . But i scrap the details without changing my url. Please help me to find solve the problem,thanks in advance..

From stackoverflow
  • You can use the cURL extension of PHP to do HTTP requests to another web site from within your PHP page script. See the documentation here.

    Of course the downside here is that your site will respond slowly because you will have to scrape the external web site before you can present the full page/output to your user.

    Sakthivel : i scrap the page content , But it redirect the entire page to the new url . But i want the page contents only..
    cruizer : I don't think it's a good idea to scrape another page's HTML from client-side Javascript. It's best to do it server side, within PHP itself.
  • I have use PHP Simple HTML DOM parser and its good. I have used this for my stackoverflow favourites plugin.

  • Definitely go with PHP Simple HTML DOM Parser. It's fast, easy and super flexible. It basically sticks an entire HTML page in an object then you can access any element from that object.

    Like the example of the official site, to get all links on the main Google page:

    // Create DOM from URL or file
    $html = file_get_html('http://www.google.com/');
    
    // Find all images 
    foreach($html->find('img') as $element) 
           echo $element->src . '<br>';
    
    // Find all links 
    foreach($html->find('a') as $element) 
           echo $element->href . '<br>';
    

How do I build a parameterized PDO statement in PHP for a dynamic query?

Apologies if this has been asked already. I've seen answers regarding static SQLs, but in this case I'd like to use PDO->prepare() for a query string that is built dynamically at runtime.

Breaking down into a simple example:

$TempSQL = "SELECT field1, field2, field3 FROM table WHERE ";

if ($numberParams == 1) {
    $TempSQL = $TempSQL . " field1 = '$val1' ";
} else {
    $TempSQL = $TempSQL . " field2 = '$val2' ";
    $TempSQL = $TempSQL . " AND field3 = '$val3' ";
}

db->query($TempSQL);

How do I rewrite this as a db->prepare()?

Should I build the statement->execute(array(':param' => $var))) on the fly as well?

Is there a better / neater way?

From stackoverflow
  • Based on your example, a neater way would be a loop instead of switching.

    db->prepare() allows you to replace patterns (on php.net, the example is putting a colon in front of the field name) using bindParam() or an array on the PDOStatement->exec(). You can use the ? from examples 3 and 4 instead of naming the field values.

    It still requires that all the fields be known for the SQL statement.

  • Perhaps something like this. (untested)

    $TempSQL = "SELECT field1, field2, field3 FROM table WHERE ";
    $args=array();
    
    if ($numberParams == 1) {
        $TempSQL = $TempSQL . " field1 = :val1"
        $args[':val1']=$val1;
    } else {
        $TempSQL = $TempSQL . " field2 = :val2 and field3 = :val3";
        $args[':val2']=$val2;
        $args[':val3']=$val3;
    }
    
    $stmt=$db->prepare($TempSQL);
    $stmt->execute($args);
    
    Barry : This looks about right. I will test it out today, thanks!
    DisgruntledGoat : It should also be noted that `$TempSQL = $TempSQL . 'something'` can be shortened to `$TempSQL .= 'something'`

sed scripting - environment variable substitution

Hi all,

I have sed related question:

If I run these command from a scrip:

#my.sh
PWD=bla
sed 's/xxx/'$PWD'/'
...
$ ./my.sh
xxx
bla

Which is fine.

But, if i run:

#my.sh
sed 's/xxx/'$PWD'/'
...
$ ./my.sh
$ sed: -e expression #1, char 8: Unknown option to `s'

I read in tutorials that to substitute env. variables from shell you need to stop, and 'out quote' the $varname part so that it is not substituted directly, which is what I did, and which works only if the variable is defined immediately before.

How can I get sed to recognize a $var as a env. variable as it is defined in the shell ?

From stackoverflow
  • With your question edit, I see your problem. Let's say the current directory is /home/yourname ... in this case, your command below:

    sed 's/xxx/'$PWD'/'
    

    will be expanded to

    sed `s/xxx//home/yourname//
    

    which is not valid. You need to put a \ character in front of each / in your $PWD if you want to do this.

    Roman M : but PWD is defined by the shell ... if i go echo $PWD i get the pwd
  • Your two examples look identical, whcih makes problems hard to diagnose. Potential problems:

    1. You may need double quotes, as in sed 's/xxx/'"$PWD"'/'

    2. $PWD may contain a slash, in which case you need to find a character not contained in $PWD to use as a delimiter.

    Roman M : tnx Norman, 2. Was the problem ... I didn't realize im using '/' as the pattern deliminator and as part of the substitution string ... solved ...
    Roman M : but, then what character can i use i know for sure will not appear in a path name ?
    Norman Ramsey : You can have several candidates like @#%! and check with a case expression to find if $PWD has them. E.g., case "$PWD" of *@*) ;; *) delim="@" ;; esac; repeat until $delim is not empty.
  • In addition to Norman Ramsey's answer, I'd like to add that you can double-quote the entire string (which may make the statement more readable and less error prone).

    So if you want to search for 'foo' and replace it with the content of $BAR, you can enclose the sed command in double-quotes.

    sed 's/foo/$BAR/g'
    sed "s/foo/$BAR/g"
    

    In the first, $BAR will not expand correctly while in the second $BAR will expand correctly.

Javascript: better way to add dynamic methods?

I'm wondering if there's a better way to add dynamic methods to an existing object. Basically, I am trying to assemble new methods dynamically and then append them to an existing function.

This demo code works.

builder = function(fn, methods){

 //method builder
 for(p in methods){
  method = 'fn.' + p + '=' + methods[p];
  eval(method);
 }

 return fn;
}
test = {}
test = builder(test, {'one':'function(){ alert("one"); }','two':'function(){ alert("two"); }'} );

test.one();
test.two();
From stackoverflow
  • You don't need to eval them each time.

    You can create existing Function objects, then assign them as properties to your objects.

    var methods = {
      'increment': function() { this.value++; },
      'display' : function() { alert(this.value); }
    };
    
    functions addMethods(object, methods) {
      for (var name in methods) {
        object[name] = methods[name];
      }
    };
    
    var obj = { value: 3 };
    addMethods(obj, methods);
    obj.display();  // "3"
    obj.increment();
    obj.display();  // "4"
    

    Of course, the canonical, object-oriented way is to use constructors and prototypes (but this isn't really dynamic in that each object you construct will have the same methods):

    function MyObj(value) {
      this.value = value;
    };
    MyObj.prototype.increment = function() {
      this.value++;
    };
    MyObj.prototype.display = function() {
      alert(this.value);
    }
    var obj = new MyObj(3);
    obj.display();  // "3"
    obj.increment();
    obj.display();  // "4"
    
  • Do you have to build the methods from a string? If not there are plenty of ways including adding the methods to an object prototype or the object definition directly. Most of all the common javascript libraries have methods for defining objects/methods on existing or creating "namespaces". Check out YUI/Prototype/jQuery etc for examples of how they implement.

    Otherwise if you have to build from a string then evaling may be the best method for dynamically adding methods to an object definition.

  • Nothing is preventing you from using the object literal syntax to do that.

    var obj = {
      one: function() {
        //...
      },
      two: function() {
        //...
      }
    }
    

    And objects, are dictionaries, right? They are not as you say, statically typed. This means that it's perfectly fine to add new properties i.e. functions to any object at any time. How you do it, well, that a matter of great opinion, but JavaScript falls in the category of prototype-based programming languages and as such you should really take a look at this. I gives some good insight into what that entails and how to do it.

  • Your example could be accomplished without strings:

    builder = function(fn, methods){
    
            //method builder
            for(p in methods){
                    fn[p] = methods[p];
            }
    
            return fn;
    }
    test = {}
    test = builder(test, {'one': function(){ alert("one"); },'two':function(){ alert("two"); }} );
    
    test.one();
    test.two();
    

    I'm not sure how you are assembling these methods, but avoid using strings if you can. There is probably a better way.

Simulating connection problems for .NET HttpWebRequest

Are there ways to programmatically simulate connection problems (slow connection, response does not complete, connection gets dropped, etc.) when using the HttpWebRequest class?

Thanks

EDIT: To elaborate more, I need this for debugging but would want to turn it into a test eventually. I'm using the async methods BeginGetRequestStream, EndGetRequestStream, BeginGetResponse and EndGetResponse. I have wrapped them all in proper (I hope) Try Catch blocks which log the exceptions that happen.

I know this works for some cases (e.g. when I pull out the network cable). But on some rare occasions (i.e. only when the website I'm requesting is slow) then my system crashes and I get this in the Event Log

Exception: System.Net.WebException

Message: The request was aborted: The connection was closed unexpectedly.

StackTrace:    at System.Net.ConnectStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
   at System.IO.Compression.DeflateStream.ReadCallback(IAsyncResult baseStreamResult)
   at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
   at System.Net.ContextAwareResult.CompleteCallback(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Net.ContextAwareResult.Complete(IntPtr userToken)
   at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
   at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

I am making an assumption it's from HttpWebRequest but then again all my code is wrapped in Try Catch blocks.

Would mocks help in such a case?

From stackoverflow
  • If you're in control of the site that's responding to the request, I'd say putting the thread to sleep for a while would simulate a slow response. System.Threading.Thread.Sleep(number of milliseconds)

    As for a dropped connection, I can't think of anything programmatic, but I've literally pulled out my network cable to simulate that condition.

  • If this is for testing purposes - i.e. to inspect your's code behavior, I would suggest to create a class which inherits from from HttpWebRequest/HttpWebResponse, and override the methods you are interested in to behave the way you want - i.e. Thread.Sleep for delays, throw an exceptions, etc.

    Matthew Cole : I was going to suggest doing the same thing. :-)
  • Assuming you are writing unit tests to cover the code, you could use a mocking framework (I personally prefer Moq) to mock out the implementation of the HttpWebRequest for any virtual methods on the class. In your mock, you can do your own implementation of how you want the test case to behave.

  • @Chris Unfortunately, Microsoft neglected to make many of the BCL objects easily mockable, as they tend to use abstract classes, and .NET classes are closed by design (in other words, for a method to be overridden by a subclass, it needs to be explicitly marked as virtual), whereas Java is open by design (that is, a subclass can override any method, unless they are marked as final). Using interfaces or marking the methods as virtual would have saved a lot of headaches in the testing space. Microsoft may have the testability religion now (e.g. ASP.NET MVC), but it's a bit late for the BCL.

    Typemock Isolator may be able to help, but I don't believe Moq can, in this case.

Creating and intialising different sub-types without lots of casting

Boy, I am sure am messing around with a lot of casting and such in this code below. It seems like there should be a smoother way. I'm basically trying to use a builder method (CreateNewPattern) to handle creating new objects of the passed sub-class type (by the CreateNewCircularPattern and CreateNewLinePattern methods). I presently only have two sub-classed types CircularHolePattern and SingleLineHolePattern that inherit from HolePattern, but I expect to have more as my app grows.

Is this a place for using a delegate or a lambda? It know nothing about them, so please be as specific as possible with and code suggestions.

private CircularHolePattern CreateNewCircularPattern()
{
   var CreatedPattern = CreateNewPattern(typeof(CircularHolePattern));
   return (CircularHolePattern)CreatedPattern;
}


private SingleLineHolePattern CreateNewLinePattern()
{
   var CreatedPattern=CreateNewPattern(typeof(SingleLineHolePattern));
   return (SingleLineHolePattern)CreatedPattern;
}

private HolePattern CreateNewPattern(Type PatternTypeToCreate)
{
    var NewHolePattern = (HolePattern)Activator.CreateInstance(PatternTypeToCreate);
    NewHolePattern.PatternName = "Pattern #" + (HolePatterns.Count + 1).ToString();
    this.AddPattern(NewHolePattern);
    this.SetActivePattern(NewHolePattern);
    return NewHolePattern;
}
From stackoverflow
  • I suspect you want generics:

    private T CreateNewPattern<T>() where T : HolePattern, new()
    {
        var newHolePattern = new T();
        newHolePattern.PatternName = "Pattern #" +
            (HolePatterns.Count + 1).ToString();
        this.AddPattern(newHolePattern);
        this.SetActivePattern(newHolePattern);
        return newHolePattern;          
    }
    
    private SingleLineHolePattern CreateNewLinePattern() {
        return CreateNewPattern<SingleLineHolePattern>();
    }
    
    private CircularHolePattern CreateNewCircularPattern() {
        return CreateNewPattern<CircularHolePattern>();
    }
    

    The T is the generic-type-argument; the type we want to create. The where says "it must be HolePattern or a sub-type, and it must have a public parameterless constructor" - this lets us use new T() to create a new instance of it, and access all members of HolePattern against such instances (such as PatternName). This also allows us to call the methods that accept a HolePattern as an argument.

    MattSlay : I can certainly follow what generics is doing here. However, let me ask, respectfully, because I am a newbie to C# (coming from FoxPro mostly), since I want to develop good practices and an undertanding that I can own with conviction, so, what in the world have I really gained with this approach?
    Marc Gravell : One thing is type safety; you can't call `CreateNewPattern`, but you can call `CreateNewPattern(typeof(int))`; it knows that T is a HolePattern with a usable constructor. A second is you no longer have any casting - the compiler can prove that you are doing things right.
    Marc Gravell : Depending on your point of view, you have also removed all useful functionality from 2 methods: CreateNewLinePattern/CreateNewCircularPattern - you could even remove them completely and have the caller use CreateNewPattern() etc; less code to maintain.
  • For one, you could reduce the Create...Pattern methods to

    private CircularHolePattern CreateNewCircularPattern()
    {
       return CreateNewPattern(typeof(CircularHolePattern));
    }
    

    Another suggestion might be to only work in abstractions. For example, only return HolePattern types from the Create...Pattern methods instead of their concrete types such as CircularHolePattern. You are casting them down to HolePattern in any case.

    So, CreateNewCircularPattern becomes

    private HolePattern CreateNewCircularPattern()
    {
       return CreateNewPattern(typeof(CircularHolePattern));
    }
    

Apache Derby - Check Database Already Created?

Hey,

Using Apache Derby with Java (J2ME, but I don't think that makes a difference) is there any way of checking if a database already exists and contains a table?

Cheers,

Pete

From stackoverflow
  • I know of none, except few work around, unlike MySQL where we have that facility of IF EXIST.

    What you do is, try to connect to the database, if couldn't its likely its not there. And after a successful connection, you can do a simple select, like SELECT count(*) FROM TABLE_NAME, to know whether the table exist or not. You would be depending on the exception. Even in an official example from Sun, I have seen the similar work around.

    In Oracle we have dictionary tables to know about the database objects. I doubt if we have anything like that in Derby.

    [Edited]

    Well, I found that there is a way to know if the table exist. Try, SELECT tablename FROM SYSTABLES. It is for checking the existence of a table, for checking database you may need to do similar thing, I explained above.

  • Vinegar You could also use Connection.getMetaData to return a DatabaseMetaData object, then use the getTables, once you have the connection to the database of course. This has the advantage of working for any database with a JDBC driver worth it's salt.

    For checking if the database exists, if you are using Derby in the embedded way, or the server is on the same machine, you could check if the folder for the database exists. Is a bit kludgy though. I would do as Vinegar suggests and try to connect, catching the exception if it's not there.

  • I would suggest getting the DatabaseMetaData object, then using the getTables(null, null, null, new String[]{"TABLE"}) method from it, which returns a ResultSet. Use the next() method of the ResultSet, which returns a boolean, to test if any tables exist. If it tests true, you have tables in existence. False, and the database is empty.

Why ‘No database selected’ SQLException?

why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected"

//import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.Vector;

public class DataBase {

    public void LoadDriver() {

        // Load the JDBC-ODBC bridge driver
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        } catch (ClassNotFoundException ee) {
            ee.printStackTrace();
        }
    }

    // 2.open a data source name by means of the jdbcodbcdriver.

    static void connect() throws SQLException {

        // Connect to the database
        Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin");
        Statement stmt = con.createStatement();
        // Shut off autocommit
        con.setAutoCommit(false);


        System.out.println("1.Insert 2.Delete 3.Update 4.Select");
        Scanner s = new Scanner(System.in);
        int x;
        x = s.nextInt();

        String query; // SQL select string
        ResultSet rs; // SQL query results
        boolean more; // "more rows found" switch
        String v1, v2; // Temporary storage results

        Vector<Object> results = new Vector<Object>(10);


        if (x == 1) {

            try {
                stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) ");
            } catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();}
        }

        if (x == 2) {

            try {
                stmt.executeUpdate("DELETE from employee where emp_id='102' ");
            }catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} 
        }

        if (x == 3) {

            try {
                stmt
                        .executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; ");
            } catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} 
        }


        query = "SELECT * FROM employee ";
        try {
            rs = stmt.executeQuery(query);
            // Check to see if any rows were read
            more = rs.next();
            if (!more) {

                System.out.println("No rows found.");
                return;
            }

            // Loop through the rows retrieved from the query
            while (more) {

                v1 = "ID: " + rs.getInt("emp_id");
                v2 = "Name: " + rs.getString("emp_name");

                System.out.println(v1);
                System.out.println(v2);
                System.out.println("");

                results.addElement(v1 + "\n" + v2 + "\n");

                more = rs.next();
            }
            rs.close();

        } catch (SQLException e) {
            System.out.println("" + results.size() + "results where found.");
        } 
        finally{stmt.close();}
    }

    public static void main(String[] args) throws SQLException {
        String str = "y";
        do {
            DataBase s = new DataBase();
            s.LoadDriver();
            DataBase.connect();
        Scanner sc = new Scanner(System.in);
        System.out.println("DO u Want to PROCEED TO QUERY : ");
        str = sc.next();
        } while (str !="n");
    }

}
From stackoverflow
  • Just from looking at the exception.. I would guess that you are not specifying the database. How can you do a select on a table without telling it which schema to select from ? This is typically set in the connection string..

    Jeremy Wilde : I would presume its contained in the ODBC definition since is is using JdbcOdbcDriver
    markt : Interesting.. the schema name is MySql??
    Jeremy Wilde : That would be the name of an ODBC definition on their computer
    markt : Ahh. gotcha. bridge..
  • Unless you have to use the jdbc/odbc driver I would use the straight mysql jdbc driver. You can download it free from mysql.

    then

    public void LoadDriver() {
    
            // Load the JDBC-ODBC bridge driver
            try {
                    Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ee) {
                    ee.printStackTrace();
            }
    }
    
    static void connect() throws SQLException {
    
            // Connect to the database
            Connection con = DriverManager.getConnection("jdbc:mysql:host/databasename", "root", "admin");
            Statement stmt = con.createStatement();
    ...
    
  • Found a bug listing at MySQL that gives this error but with different technologies. However, in the description it indicates that it is related to reauthorization not sending the database information, so perhaps that is what you are encountering here as well.

    Some things that stick out as odd to me (although no clue if they will have any impact on your error)

    • You only need to load the Driver Manager once
    • You aren't closing your connection, so either close it or refactor to use the same one.

    Perhaps move these two lines to just before the do loop

    DataBase s = new DataBase();
    s.LoadDriver();
    
  • Is the ODBC source actually set up to select a database? eg. can you access the database through another ODBC client tool?

    If you need to select a database explicitly in the JDBC string you can do that using the ‘database’ parameter.

    But having the database chosen in the ODBC setup would be more usual. And indeed, as Clint mentioned, using the normal MySQL JDBC driver instead of ODBC would be more usual still.

    while (str !="n")

    That's not how you compare strings in Java.