input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Hide a DIV [Rails] <p>Hiding a DIV would be easy enough in Javascript, but is there some Rails-y way to do it? I can think of some ways to do it by calling Javascript from a partial (.erb), of course, but I'd prefer not to write any Javascript at all. Possible?</p>
<p><strong>Edit:</strong> The page is loaded and I would like to hide the DIV <strong>after</strong> (well, on) an Ajax call, so I'm in one of those <code>render :update</code> blocks.</p>
| <p>Or, right in your view:</p>
<p>For a class-specified div: </p>
<pre><code><%= link_to_function "Toggle", "$('.some_div').toggle()" %>
</code></pre>
<p>For an ID-specified div: </p>
<pre><code><%= link_to_function "Toggle", "$('#some_div').toggle()" %>
</code></pre>
<p>(notice the hash-mark)</p>
<p>Added period to class specific div and hash to id specific div</p>
|
Rails inline Javascript and Best Practices <p>I'm <em>kinda</em> new to using Rails, and an app I am working on is progressing well - however I'm looking though the generated HTML and noticed things like...</p>
<pre><code><script type="text/javascript">
//<![CDATA[
Droppables.add(...);
//]]>
</script>
</code></pre>
<p>Sprinkled around the HTML, which of course matches up with places where I use:</p>
<pre><code><%= drop_receiving_element ... %>
</code></pre>
<p>What I'm wondering is... is there a better way to do this, or make it cleaner? Some of these script tags are coming from partials so putting them at the 'bottom of the page' doesn't really help in this situation.</p>
<p>Another option may be pushing all these 'tag blocks' into an array then writing them out in the <strong>application.rhtml</strong> file, but its still a bit messy...</p>
| <p>Well if you really want to use best practices...Do not use inline javascript. Keep your HTML, CSS and Javascript clean and seperated from eachother. Ideally the html file should be usable without CSS and javascript.</p>
<p>The cleanest way, imo, is to just build your app using plain html/css, and enhance it with unobtrusive javascript to provide a better user experience.</p>
<p>A pattern for this is to include all your JS files at the bottom of your page, and start running your code with functionality like onDomReady.</p>
<p>Based on the comments I would like to add some possible options to get you started:</p>
<ul>
<li>JQuery</li>
<li>YUI</li>
<li>Prototype</li>
</ul>
|
How to Set User-Agents in an HttpRequest (Unit Testing) <p>I've got a method that takes in an HttpRequest object and performs differently based on what User Agent is set. I'm trying to unit test it and am having a heck of a time tracking down how to set the User Agent string. I've tried the raw HttpRequest object and a variety of other objects that eventually yield it to no avail.</p>
<p>Does anyone have any idea how to set the user agent string for an HttpRequest object?</p>
<p>Thanks!</p>
| <p>You can set the UserAgent property on an HttpWebRequest, are you able to use that type instead?</p>
|
In ASP.NET MVC, preserve URL when return RedirectToAction <p>I have an action method, and depending on what is passed to it, I want to redirect to another action in another controller. The action and controller names are determined at run time. </p>
<p>If I return RedirectToAction(), it will force a redirect and change the URL in the browser. What I would like is something like TransferToAction() that can transfer processing of the current request to another action, without doing a redirect. I seem to remember a method behaving like this in earlier previews, but I can't seem to find it in the RC of ASP.NET MVC.</p>
<p>Do you know how I would do this?</p>
<p>UPDATE</p>
<p>I added the following route:</p>
<pre><code>routes.MapRoute(
"PageRouter",
"{site}/{*url}",
new { controller = "PageRouter",
action = "RoutePage", site = "", url = "" }
);
</code></pre>
<p>And the PageRouter controller action RoutePage:</p>
<pre><code>public ActionResult RoutePage(string site, string url)
{
var controller = new HomeController {ControllerContext = ControllerContext};
controller.RouteData.Values["controller"] = "Home";
controller.RouteData.Values["action"] = "Index";
return controller.Index(site, url);
}
</code></pre>
<p>I had to set the controller and action in RouteData for the Home Index view to be rendered. Otherwise, it would look for an Index view in PageRouterController.</p>
<p>I still need to figure out how to create a controller and its action knowing only their names. e.g. I'd like to be able to just call something like this:</p>
<pre><code>public ActionResult RoutePage(string site, string url)
{
return InvokeAction("Home", "Index");
}
</code></pre>
<p>What should go in InvokeAction() ? Do I need to pass it any context?</p>
| <p>You should be able to just call the other method directly and, assuming that it returns a ViewResult, it will render that view in response to the request and the url will not change. Note, you'll be responsible for making sure that all of the data that the other method needs is available to it. For example if your other method requires some form parameters that weren't provided, you may need to construct a suitable FormCollection and set the ValueProvider of the controller to a ValueProvider based on your FormCollection. Likewise with any arguments required by the method.</p>
|
Difference between div id versus div class <p>What's the difference between <code><div class=""></code> and <code><div id=""></code> when it comes to CSS? Is it right to use <code><div id=""></code>?</p>
<p>I see different developers doing this in both ways, and since I'm self taught, I've never really figured it out.</p>
| <p><code>ids</code> must be unique where as <code>class</code> can be applied to many things. In CSS, <code>id</code>s look like <code>#elementID</code> and <code>class</code> elements look like <code>.someClass</code></p>
<p>In general, use <code>id</code> whenever you want to refer to a specific element and <code>class</code> when you have a number of things that are all alike. For instance, common <code>id</code> elements are things like <code>header</code>, <code>footer</code>, <code>sidebar</code>. Common <code>class</code> elements are things like <code>highlight</code> or <code>external-link</code>.</p>
<p>It's a good idea to read up on the cascade and understand the precedence assigned to various selectors: <a href="http://www.w3.org/TR/CSS2/cascade.html">http://www.w3.org/TR/CSS2/cascade.html</a></p>
<p>The most basic precedence you should understand, however, is that <code>id</code> selectors take precedence over <code>class</code> selectors. If you had this:</p>
<pre><code><p id="intro" class="foo">Hello!</p>
</code></pre>
<p>and:</p>
<pre class="lang-css prettyprint-override"><code>#intro { color: red }
.foo { color: blue }
</code></pre>
<p>The text would be red because the <code>id</code> selector takes precedence over the <code>class</code> selector.</p>
|
Are there reasons to still use the "@import" css rule? <p>I recently came across a use of the @import rule on Coda.com. They're actually using to import the main style sheet for the site, specifically the format:</p>
<pre><code><style type="text/css" media="screen">
@import url(./coda.css);
</style>
</code></pre>
<p>Which will hide the rules from Netscape 3 and IE 3 and 4. Since a web development tools primary audience will be using modern browsers, what other reasons would there be to use this rather then a link?</p>
| <p>None. Using a <code><link></code> element also has the advantage of getting rid of the <a href="http://bluerobot.com/web/css/fouc.asp/" rel="nofollow">FOUC</a>.</p>
<p><strong>EDIT</strong>: Using <code>@import</code> in another stylesheet (<code>.css</code> file) can be used like an <code>#include</code> in C, but there isn't any reason to use <code>@import</code> <em>in</em> a <code><style></code> block.</p>
|
XAMPP shows error for .exe from non-local domains <p>In FireFox3 when I go to URL's such as:</p>
<p><a href="http://download.microsoft.com/download/4/A/A/4AA524C6-239D-47FF-860B-5B397199CBF8/windows-kb890830-v2.7.exe" rel="nofollow">http://download.microsoft.com/download/4/A/A/4AA524C6-239D-47FF-860B-5B397199CBF8/windows-kb890830-v2.7.exe</a></p>
<p>I get a 404 error for the URL locally on my XAMPP installation I use for local development.</p>
<p>It has to do with the .exe I think but I can't figure out why.</p>
<p>Whats the problem?</p>
<p>Object not found!</p>
<p><hr /></p>
<p>ERROR:</p>
<p><hr /></p>
<p>The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.</p>
<p>If you think this is a server error, please contact the webmaster.
Error 404
download.microsoft.com
02/12/09 15:47:20
Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5 </p>
| <p>This issue was caused by a root kit.</p>
|
Does visibility affect DOM manipulation performance? <p>IE7/Windows XP</p>
<p>I have a third party component in my page that does a lot of DOM manipulation to adjust itself each time the browser window is resized.</p>
<p>Unfortunately I have little control of what it does internally and I have optimized everything else (such as callbacks and event handlers) as much as I can. I can't take the component off the flow by setting display:none because it fails measuring itself if I do so.</p>
<p>In general, does setting visibility of the container to invisible during the resize help improve DOM rendering performance?</p>
| <p>Caveat: I have not specifically tested this with IE7, but I am reasonably confident based on what I know about its DOM manipulation model.</p>
<p>Changing CSS properties (whether <code>display: none</code> or <code>visibility: hidden</code> or what-have-you) will not affect the performance of DOM manipulation in any version of any browser I've worked with. The primary way to improve the speed of DOM manipulation is to remove the node(s) you will be working with from the document tree, performing your manipulations, and adding them back in. This involves keeping track of their succeeding sibling nodes, if any (for use with <code>insertBefore</code>), which can become complex if you're working with nodes which are scattered around the document.</p>
<p>One technique I have seen when performing a large number of DOM manipulations all at once is to get a list of the <code>body</code> element's children, remove them, perform your manipulations (wherever they fall in the document tree), and then reappend the body's child nodes. Depending on how long your DOM manipulations take (which is itself partially dependent on the speed of your visitor's computer!), this can produce a noticeable flicker. This is why sites manipulating content via AJAX will usually replace any temporarily-removed content with a "spinner" or loading screen.</p>
|
Sharepoint 2007 document management <p>We are developing a document management solution with Sharepoint 2007 and I'm having some issues figuring out a couple items with the structure. The documents are templates that are used to merge data into letters sent to clients. While the templates will be managed in Sharepoint, the actual letters that will be generated will be handled through a web application. The rules to which template is to be pulled up would be "assigned" through Sharepoint via Meta-Data. This data would be sent over to the other system (which would keep track of the rules and an identifier to the raw template). A web service would be created on the SP side so the front end application would simply call it to pull up the template (once it was determined which one to use). </p>
<p>Okay that said the real question is how to deal with the rules? I originally thought meta-data and write the data out (via web service call) to the web application db. For example when saving the document have a meta data field for Template Type (for this custom contenttype). First problem how to populate a drop down available for sharepoint to load a list of templatetypes? Can I drive this from a database or do I have to use a static xml list.</p>
| <p>Aaak.
You can create a field based on a lookup of information on the BDC.
You can also create a lookup based on a list in SharePoint.</p>
|
Linking to Boost.Signals using Xcode <p>I can't for the life of me get Xcode to link to Boost.Signals properly. I've built Boost using MacPorts, and I even went as far as downloading Boost myself and manually building it.</p>
<p>I've set the Library Search Paths to include /opt/local/lib, and I've added "-lboost_signals-mt" to the Other Linker Flags. I've tried dragging and dropping the libraries into the Frameworks folder. I've tried adding the libraries to the build target.</p>
<p>I always get the error that the "file is not of required architecture."</p>
<p>Just to make sure the problem was with Xcode, I went ahead and wrote a makefile to build the project--it works fine, using the same linker flag shown above.</p>
<p>Any ideas?</p>
| <p>Check the target architecture in your Xcode project. It looks like you're trying to compile a universal binary. Unless you explicitly ask for it, boost will be built for the architecture of the build machine only.</p>
|
C++ wrappers for ncurses? <p>Can anyone recommend a C++ wrapper for ncurses?</p>
| <p>ncurses itself includes a set of C++ bindings. I don't know if any of the major distributions include the C++ bindings but if you get the <a href="http://ftp.gnu.org/pub/gnu/ncurses/">ncurses source</a> you will find them in the c++ directory.</p>
<p>I don't know if I would necessarily recommend them but they are probably the best C++ bindings and it includes bindings for the Forms, Panel, and Menu extensions. They are a bit rough around the edges and there isn't much documentation.</p>
|
Best way to change the value of an element in C# <p>I'm trying to look at the best way of changing the value of an element in XML.</p>
<pre><code><MyXmlType>
<MyXmlElement>Value</MyXmlElement>
</MyXmlType>
</code></pre>
<p>What is the easiest and/or best way to change "Value" in C#?</p>
<p>I've looked at XMLDocument and it will cause a load of the whole XML document to memory. Could you do it safely with the XMLReader. The problem is changing the value and emitting it back seems like an interesting conundrum. </p>
<p>Cheers :D</p>
| <p>You could use the System.Xml.Linq namespace stuff for the easiest to read code. This will load the full file into memory. </p>
<pre><code>XDocument xdoc = XDocument.Load("file.xml");
var element = xdoc.Elements("MyXmlElement").Single();
element.Value = "foo";
xdoc.Save("file.xml");
</code></pre>
|
Are there any software guarantees in critical systems? <p>Are there systems or is there software out there that is developed with a proof of correctness to back it up? Or are all critical systems developed merely with an aggressive code review and test cycle?</p>
| <p>See <a href="http://www.fastcompany.com/magazine/06/writestuff.html" rel="nofollow"><strong>They Write The Right Stuff</strong></a> for an interesting look at how they develop software for the Space Shuttle. </p>
<p>Excerpt: </p>
<blockquote>
<p>But how much work the software does is
not what makes it remarkable. What
makes it remarkable is how well the
software works. This software never
crashes. It never needs to be
re-booted. This software is bug-free.
It is perfect, as perfect as human
beings have achieved. Consider these
stats : the last three versions of the
program -- each 420,000 lines long-had
just one error each. The last 11
versions of this software had a total
of 17 errors. Commercial programs of
equivalent complexity would have 5,000
errors.</p>
</blockquote>
|
Detecting honest web crawlers <p>I would like to detect (on the server side) which requests are from bots. I don't care about malicious bots at this point, just the ones that are playing nice. I've seen a few approaches that mostly involve matching the user agent string against keywords like 'bot'. But that seems awkward, incomplete, and unmaintainable. So does anyone have any more solid approaches? If not, do you have any resources you use to keep up to date with all the friendly user agents?</p>
<p>If you're curious: I'm not trying to do anything against any search engine policy. We have a section of the site where a user is randomly presented with one of several slightly different versions of a page. However if a web crawler is detected, we'd always give them the same version so that the index is consistent.</p>
<p>Also I'm using Java, but I would imagine the approach would be similar for any server-side technology.</p>
| <p>You said matching the user agent on âbotâ may be awkward, but weâve found it to be a pretty good match. Our studies have shown that it will cover about 98% of the hits you receive. We also havenât come across any false positive matches yet either. If you want to raise this up to 99.9% you can include a few other well-known matches such as âcrawlerâ, âbaiduspiderâ, âia_archiverâ, âcurlâ etc. Weâve tested this on our production systems over millions of hits. </p>
<p>Here are a few c# solutions for you:</p>
<h3>1) Simplest</h3>
<p>Is the fastest when processing a miss. i.e. traffic from a non-bot â a normal user.
Catches 99+% of crawlers.</p>
<pre><code>bool iscrawler = Regex.IsMatch(Request.UserAgent, @"bot|crawler|baiduspider|80legs|ia_archiver|voyager|curl|wget|yahoo! slurp|mediapartners-google", RegexOptions.IgnoreCase);
</code></pre>
<h3>2) Medium</h3>
<p>Is the fastest when processing a hit. i.e. traffic from a bot. Pretty fast for misses too.
Catches close to 100% of crawlers.
Matches âbotâ, âcrawlerâ, âspiderâ upfront.
You can add to it any other known crawlers.</p>
<pre><code>List<string> Crawlers3 = new List<string>()
{
"bot","crawler","spider","80legs","baidu","yahoo! slurp","ia_archiver","mediapartners-google",
"lwp-trivial","nederland.zoek","ahoy","anthill","appie","arale","araneo","ariadne",
"atn_worldwide","atomz","bjaaland","ukonline","calif","combine","cosmos","cusco",
"cyberspyder","digger","grabber","downloadexpress","ecollector","ebiness","esculapio",
"esther","felix ide","hamahakki","kit-fireball","fouineur","freecrawl","desertrealm",
"gcreep","golem","griffon","gromit","gulliver","gulper","whowhere","havindex","hotwired",
"htdig","ingrid","informant","inspectorwww","iron33","teoma","ask jeeves","jeeves",
"image.kapsi.net","kdd-explorer","label-grabber","larbin","linkidator","linkwalker",
"lockon","marvin","mattie","mediafox","merzscope","nec-meshexplorer","udmsearch","moget",
"motor","muncher","muninn","muscatferret","mwdsearch","sharp-info-agent","webmechanic",
"netscoop","newscan-online","objectssearch","orbsearch","packrat","pageboy","parasite",
"patric","pegasus","phpdig","piltdownman","pimptrain","plumtreewebaccessor","getterrobo-plus",
"raven","roadrunner","robbie","robocrawl","robofox","webbandit","scooter","search-au",
"searchprocess","senrigan","shagseeker","site valet","skymob","slurp","snooper","speedy",
"curl_image_client","suke","www.sygol.com","tach_bw","templeton","titin","topiclink","udmsearch",
"urlck","valkyrie libwww-perl","verticrawl","victoria","webscout","voyager","crawlpaper",
"webcatcher","t-h-u-n-d-e-r-s-t-o-n-e","webmoose","pagesinventory","webquest","webreaper",
"webwalker","winona","occam","robi","fdse","jobo","rhcs","gazz","dwcp","yeti","fido","wlm",
"wolp","wwwc","xget","legs","curl","webs","wget","sift","cmc"
};
string ua = Request.UserAgent.ToLower();
bool iscrawler = Crawlers3.Exists(x => ua.Contains(x));
</code></pre>
<h3>3) Paranoid</h3>
<p>Is pretty fast, but a little slower than options 1 and 2.
Itâs the most accurate, and allows you to maintain the lists if you want.
You can maintain a separate list of names with âbotâ in them if you are afraid of false positives in future.
If we get a short match we log it and check it for a false positive.</p>
<pre><code>// crawlers that have 'bot' in their useragent
List<string> Crawlers1 = new List<string>()
{
"googlebot","bingbot","yandexbot","ahrefsbot","msnbot","linkedinbot","exabot","compspybot",
"yesupbot","paperlibot","tweetmemebot","semrushbot","gigabot","voilabot","adsbot-google",
"botlink","alkalinebot","araybot","undrip bot","borg-bot","boxseabot","yodaobot","admedia bot",
"ezooms.bot","confuzzledbot","coolbot","internet cruiser robot","yolinkbot","diibot","musobot",
"dragonbot","elfinbot","wikiobot","twitterbot","contextad bot","hambot","iajabot","news bot",
"irobot","socialradarbot","ko_yappo_robot","skimbot","psbot","rixbot","seznambot","careerbot",
"simbot","solbot","mail.ru_bot","spiderbot","blekkobot","bitlybot","techbot","void-bot",
"vwbot_k","diffbot","friendfeedbot","archive.org_bot","woriobot","crystalsemanticsbot","wepbot",
"spbot","tweetedtimes bot","mj12bot","who.is bot","psbot","robot","jbot","bbot","bot"
};
// crawlers that don't have 'bot' in their useragent
List<string> Crawlers2 = new List<string>()
{
"baiduspider","80legs","baidu","yahoo! slurp","ia_archiver","mediapartners-google","lwp-trivial",
"nederland.zoek","ahoy","anthill","appie","arale","araneo","ariadne","atn_worldwide","atomz",
"bjaaland","ukonline","bspider","calif","christcrawler","combine","cosmos","cusco","cyberspyder",
"cydralspider","digger","grabber","downloadexpress","ecollector","ebiness","esculapio","esther",
"fastcrawler","felix ide","hamahakki","kit-fireball","fouineur","freecrawl","desertrealm",
"gammaspider","gcreep","golem","griffon","gromit","gulliver","gulper","whowhere","portalbspider",
"havindex","hotwired","htdig","ingrid","informant","infospiders","inspectorwww","iron33",
"jcrawler","teoma","ask jeeves","jeeves","image.kapsi.net","kdd-explorer","label-grabber",
"larbin","linkidator","linkwalker","lockon","logo_gif_crawler","marvin","mattie","mediafox",
"merzscope","nec-meshexplorer","mindcrawler","udmsearch","moget","motor","muncher","muninn",
"muscatferret","mwdsearch","sharp-info-agent","webmechanic","netscoop","newscan-online",
"objectssearch","orbsearch","packrat","pageboy","parasite","patric","pegasus","perlcrawler",
"phpdig","piltdownman","pimptrain","pjspider","plumtreewebaccessor","getterrobo-plus","raven",
"roadrunner","robbie","robocrawl","robofox","webbandit","scooter","search-au","searchprocess",
"senrigan","shagseeker","site valet","skymob","slcrawler","slurp","snooper","speedy",
"spider_monkey","spiderline","curl_image_client","suke","www.sygol.com","tach_bw","templeton",
"titin","topiclink","udmsearch","urlck","valkyrie libwww-perl","verticrawl","victoria",
"webscout","voyager","crawlpaper","wapspider","webcatcher","t-h-u-n-d-e-r-s-t-o-n-e",
"webmoose","pagesinventory","webquest","webreaper","webspider","webwalker","winona","occam",
"robi","fdse","jobo","rhcs","gazz","dwcp","yeti","crawler","fido","wlm","wolp","wwwc","xget",
"legs","curl","webs","wget","sift","cmc"
};
string ua = Request.UserAgent.ToLower();
string match = null;
if (ua.Contains("bot")) match = Crawlers1.FirstOrDefault(x => ua.Contains(x));
else match = Crawlers2.FirstOrDefault(x => ua.Contains(x));
if (match != null && match.Length < 5) Log("Possible new crawler found: ", ua);
bool iscrawler = match != null;
</code></pre>
<p><strong>Notes:</strong></p>
<ul>
<li>Itâs tempting to just keep adding names to the regex option 1. But if you do this it will become slower. If you want a more complete list then linq with lambda is faster.</li>
<li>Make sure .ToLower() is outside of your linq method â remember the method is a loop and you would be modifying the string during each iteration.</li>
<li>Always put the heaviest bots at the start of the list, so they match sooner.</li>
<li>Put the lists into a static class so that they are not rebuilt on every pageview.</li>
</ul>
<p><strong>Honeypots</strong></p>
<p>The only real alternative to this is to create a âhoneypotâ link on your site that only a bot will reach. You then log the user agent strings that hit the honeypot page to a database. You can then use those logged strings to classify crawlers.</p>
<p><code>Postives:</code> It will match some unknown crawlers that arenât declaring themselves.</p>
<p><code>Negatives:</code> Not all crawlers dig deep enough to hit every link on your site, and so they may not reach your honeypot.</p>
|
Spring embedded ldap server in unit tests <p>I am currently trying to use an embedded ldap server for unit tests.</p>
<p>In Spring Security, you can quickly define an embedded ldap server for testing with the tag with some sample data loaded from the specified ldif.</p>
<p>I will be using Spring Ldap to perform ldap operations, and thinking of testing the usual CRUD features of my User service object.</p>
<p>Is there, however, a way to ensure that the entries in the embedded server to be in the same consistent state (sort of like a delete all and reload the ldif entries) for each test I am running?</p>
<p>I thought of the following:
1) Indicate that the method dirties the context, and force a recreation of the embedded ldap server, which sounds painful as it would have to restart the server for every method
2) Create the test entries in a test organization, such that I can unbind them and simply load in the ldif file again there.</p>
<p>I prefer 2, but it seems like the Spring LDAP has no good helpers to load and send across the content of a ldif file.</p>
<p>Any suggestions on how you perform ldap testing with an embedded ldap server of spring, or of the two possible solutions I mention?</p>
<p>Thanks</p>
| <p>Doesn't Spring LDAP provide transactional control around LDAP operations? If so, why not use Spring test framework with its auto-rollback capability? </p>
<p>I also know of a JDBC-LDAP bridge driver that wraps an LDAP repository, presenting it as a relational database. I've used iBatis to connect to this (I've written this up at <a href="http://lokibear.blogspot.com" rel="nofollow">http://lokibear.blogspot.com</a>, see articles from July). I've not yet tried applying transactional control, but the website for the driver mentions the ability to ignore transactions (which means you can also <em>not</em> ignore them...right?). </p>
<p>Like I say, I haven't tried this yet; but, if this provides transactions around LDAP, then you can again use the Spring test framework to get auto-rollback in place. I've put out a quick cheatsheet around that framework - see the September posts at my blog.</p>
<p>Sorry, I might be missing your goal here; but perhaps these suggestions are useful. Good luck!</p>
|
How can I view Flash Source Code? <p>I found a Flash program online that would be perfect for a project I'm working on. Obviously with web content you can usually just use your browser to view the source code of whatever HTML, PHP, etc that you may be looking at. But when it comes to Flash it seems we're left in the dark in terms of viewing source code.</p>
<p>Is there any way to view the source code for a Flash swf that you download?</p>
<p>Note: As to whether stealing Flash code is morally reprehensible, perhaps that would be better suited for a different question.</p>
| <p>There's no source code in a .swf - that's the compiled product. The source code is in the .fla. </p>
|
Regular expression that returns a constant value as part of a match <p>I have a regular expression to match 2 different number formats: <i>\=(?[0-9]+)\?|\+(?[0-9]+)\?</i></p>
<p>This should return 9876543 as its Value for <i>;1234567890123456?+1234567890123456789012345123=9876543?</i><br> and <i>;1234567890123456?+9876543?</i>
What I would like is to be able to return another value along with the matched 'Value'.</p>
<p>
So, for example, if the first string was matched, I'd like it to return:</p>
Value:
9876543
Format:
LongFormat
<p><br></p>
<p>And if matched in the second string:</p>
Value:
9876543
Format:
ShortFormat
<p><br></p>
<p>Is this possible?</p>
| <p>Another option, which is not quite the solution you wanted, but saves you using two separate regexes, is to use named groups, if your implementation supports it.</p>
<p>Here is some C#:</p>
<pre><code>var regex = new Regex(@"\=(?<Long>[0-9]+)\?|\+(?<Short>[0-9]+)\?");
string test1 = ";1234567890123456?+1234567890123456789012345123=9876543?";
string test2 = ";1234567890123456?+9876543?";
var match = regex.Match(test1);
Console.WriteLine("Long: {0}", match.Groups["Long"]); // 9876543
Console.WriteLine("Short: {0}", match.Groups["Short"]); // blank
match = regex.Match(test2);
Console.WriteLine("Long: {0}", match.Groups["Long"]); // blank
Console.WriteLine("Short: {0}", match.Groups["Short"]); // 9876543
</code></pre>
<p>Basically just modify your regex to include the names, and then regex.Groups[GroupName] will either have a value or wont. You could even just use the Success property of the group to know which matched (match.Groups["Long"].Success).</p>
<p><em>UPDATE:</em>
You can get the group name out of the match, with the following code:</p>
<pre><code>static void Main(string[] args)
{
var regex = new Regex(@"\=(?<Long>[0-9]+)\?|\+(?<Short>[0-9]+)\?");
string test1 = ";1234567890123456?+1234567890123456789012345123=9876543?";
string test2 = ";1234567890123456?+9876543?";
ShowGroupMatches(regex, test1);
ShowGroupMatches(regex, test2);
Console.ReadLine();
}
private static void ShowGroupMatches(Regex regex, string testCase)
{
int i = 0;
foreach (Group grp in regex.Match(testCase).Groups)
{
if (grp.Success && i != 0)
{
Console.WriteLine(regex.GroupNameFromNumber(i) + " : " + grp.Value);
}
i++;
}
}
</code></pre>
<p>I'm ignoring the 0th group, because that is always the entire match in .NET</p>
|
Custom .ttf fonts to use in C# windows.Form <p>How do I use a custom .tff font file I have with my current windows.forms application?
I read some where that I use it as an embedded resource, but how do I set it the System.Drawing.Font type?</p>
| <p>This article: <a href="http://www.bobpowell.net/embedfonts.htm" rel="nofollow">How to embed a true type font</a> shows how to do what you ask in .NET.</p>
<p><strong>How to embed a True Type font</strong></p>
<blockquote>
<p>Some applications, for reasons of esthetics or a required visual
style, will embed certain uncommon fonts so that they are always there
when needed regardless of whether the font is actually installed on
the destination system.</p>
<p>The secret to this is twofold. First the font needs to be placed in
the resources by adding it to the solution and marking it as an
embedded resource. Secondly, at runtime, the font is loaded via a
stream and stored in a PrivateFontCollection object for later use.</p>
<p>This example uses a font which is unlikely to be installed on your
system. Alpha Dance is a free True Type font that is available from
the Free Fonts Collection. This font was embedded into the application
by adding it to the solution and selecting the "embedded resource"
build action in the properties.</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/qSiPn.png" rel="nofollow"><img src="http://i.stack.imgur.com/qSiPn.png" alt="Figure 1. The Alpha Dance font file embedded in the solution."></a></p>
<blockquote>
<p>Once the file has been successfully included in the resources you need
to provide a PrivateFontCollection object in which to store it and a
method by which it's loaded into the collection. The best place to do
this is probably the form load override or event handler. The
following listing shows the process. Note how the AddMemoryFont method
is used. It requires a pointer to the memory in which the font is
saved as an array of bytes. In C# we can use the unsafe keyword for
convienience but VB must use the capabilities of the Marshal classes
unmanaged memory handling. The latter option is of course open to C#
programmers who just don't like the unsafe keyword.
PrivateFontCollection pfc = new PrivateFontCollection();</p>
</blockquote>
<pre><code>private void Form1_Load(object sender, System.EventArgs e)
{
Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("embedfont.Alphd___.ttf");
byte[] fontdata = new byte[fontStream.Length];
fontStream.Read(fontdata,0,(int)fontStream.Length);
fontStream.Close();
unsafe
{
fixed(byte * pFontData = fontdata)
{
pfc.AddMemoryFont((System.IntPtr)pFontData,fontdata.Length);
}
}
}
</code></pre>
<blockquote>
<p>Fonts may have only certain styles which are available and
unfortunately, selecting a font style that doesn't exist will throw an
exception. To overcome this the font can be interrogated to see which
styles are available and only those provided by the font can be used.
The following listing demonstrates how the Alpha Dance font is used by
checking the available font styles and showing all those that exist.
Note that the underline and strikethrough styles are pseudo styles
constructed by the font rendering engine and are not actually provided
in glyph form.</p>
</blockquote>
<pre><code>private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
bool bold=false;
bool regular=false;
bool italic=false;
e.Graphics.PageUnit=GraphicsUnit.Point;
SolidBrush b = new SolidBrush(Color.Black);
float y=5;
System.Drawing.Font fn;
foreach(FontFamily ff in pfc.Families)
{
if(ff.IsStyleAvailable(FontStyle.Regular))
{
regular=true;
fn=new Font(ff,18,FontStyle.Regular);
e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
fn.Dispose();
y+=20;
}
if(ff.IsStyleAvailable(FontStyle.Bold))
{
bold=true;
fn=new Font(ff,18,FontStyle.Bold);
e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
fn.Dispose();
y+=20;
}
if(ff.IsStyleAvailable(FontStyle.Italic))
{
italic=true;
fn=new Font(ff,18,FontStyle.Italic);
e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
fn.Dispose();
y+=20;
}
if(bold && italic)
{
fn=new Font(ff,18,FontStyle.Bold | FontStyle.Italic);
e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
fn.Dispose();
y+=20;
}
fn=new Font(ff,18,FontStyle.Underline);
e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
fn.Dispose();
y+=20;
fn=new Font(ff,18,FontStyle.Strikeout);
e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
fn.Dispose();
}
b.Dispose();
}
</code></pre>
<blockquote>
<p>Figure 2 shows the application in action.</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/J4iLq.png" rel="nofollow"><img src="http://i.stack.imgur.com/J4iLq.png" alt="Figure 2. The embedded Alpha Dance font."></a></p>
<p>See the Form1_Paint event handler, it shows specifically how to set the System.Drawing.Font type. It is based on using the System.Drawing.Text.PrivateFontCollection class.</p>
<p>Hope this helps.</p>
|
How do I test localization in a winforms application? <p>Is there a way to test different languages in a Windows application without changing the localization of the OS or adding code to the application to forcibly change the current culture?</p>
<p>Perhaps some type of a launcher that will launch the application with a specified culture?</p>
| <p>There is this <a href="http://www.microsoft.com/globaldev/tools/apploc.mspx" rel="nofollow">AppLocale</a> Utility for XP, which can also be installed on <a href="http://www.mydigitallife.info/2007/05/26/workaround-to-install-microsoft-applocale-utility-in-windows-vista/" rel="nofollow">vista</a>.</p>
<p>AppLocale automatically detects language for non-Unicode program and simulates a corresponding system locale for code-page to/from Unicode conversions.</p>
|
Flex with PHP <p>I'm new to Flex and done a few application with only client side programming. Now I'm trying to do the back-end stuff using PHP. Can some one explain where(which folder) to put the PHP file for the Flex file to communicate with PHP. I'm using Flexbuilder 3 IDE.</p>
<p>Thanks</p>
| <p>Flex will not access your PHP script via the filesystem, you have to invoke your PHP script via a web server. The easiest solution is to use XML as in your data transport language. But you can get fancy and use something like BlazeDS</p>
|
Making cut/replace methods with JTextArea <p>I am to make a cut and a replace method on JTextArea. I have the code for copy and paste, and I reckon I could just use that, in addition to just deleting the marked text in the JTA.</p>
<p>How would the code for a code for cut and replace methods look like?</p>
<p>The code for copy looks like this:</p>
<pre><code>public void copy(){
int start=ta.getSelectionStart();
int end=ta.getSelectionEnd();
String s=ta.getText();
aString=s.substring(start,end);
System.out.println(aString);
}
</code></pre>
<p>And the paste code looks like the following:</p>
<pre><code>public void paste(){
int start=ta.getSelectionStart();
String startText=ta.getText().substring(0, start);
String endText=ta.getText().substring(start);
String res=startText+clipBoard+endText;
ta.setText(res);
}
</code></pre>
<p>So basically: How do I delete marked text in a JTextArea? Or is there possibly a better way to do this?</p>
| <p>JTextArea supports cut/copy/paste by default using keyword combination (Ctrl+C etc). If you want to have custom invocations (like menu action), JTextComponent itself provides cut/copy/paste methods which you can re-use.</p>
|
How to select multiple records (row) from a column in mysql? <p>I want to display four (4) items'name from these id:
Can I do like this?</p>
<pre><code>SELECT item_name from items WHERE item_id IN ('001', '012', '103', '500')
</code></pre>
<p>or</p>
<pre><code>SELECT item_name from items WHERE item_id = '001' or item_id = '012' or item_id = '103' or item_id = '500'
</code></pre>
<p><strong>IN RESPONSE TO ALL ANSWERS</strong></p>
<p>Well, most of the answers said it works, but it does not really work. Here is my code:</p>
<pre><code>$query = "SELECT `item_name` from items WHERE item_id IN('s001','a012','t103','p500')";
$result = mysql_query($query, $conn) or die (mysql_error());
$fetch = mysql_fetch_assoc($result) or die (mysql_error());
$itemsCollected = $fetch['item_name'];
echo $itemsCollected;
</code></pre>
<p>The <code>item_id</code> is alphanumeric.</p>
| <p>You can do either one, but the IN query is much more efficient for this purpose for any large queries. I did some simple testing long ago that revealed it's about 10 times faster to use the IN construct for this. If you're asking if the syntax is correct then yes, it looks fine, other than missing semi-colons to complete the statement.</p>
<p><strong>EDIT</strong>: It looks like the actual question you were asking was "why do these queries only return one value". Well, looking at the sample code you posted, the problem is here: </p>
<pre><code>$fetch = mysql_fetch_assoc($result) or die (mysql_error());
$itemsCollected = $fetch['item_name'];
echo $itemsCollected;
</code></pre>
<p>You need to loop through and iterate until there are no more results to be fetched, as <a href="http://stackoverflow.com/questions/544750/how-to-select-multiple-records-row-from-a-column-in-mysql/544757#544757">Pax pointed out</a>. See the PHP manual page for <a href="http://us3.php.net/mysql_fetch_assoc"><strong>mysql_fetch_assoc</strong></a>:</p>
<pre><code>$sql = "SELECT item_name from items WHERE item_id IN('s001','a012')";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
</code></pre>
|
Need TwinView Help with NVidia <p>I am trying to set up dual monitors on ubuntu 8.10 and am having a lot of difficulty. I have tried going through many tutorials with no luck so I figure I will try here as well.</p>
<p>For some reason my computer does not detect my Dell S199WFP monitor. It only lets me run it at maximum 640x480 resolution. The optimum resolution for the monitor is 1440x900. This is weird because it detects my s2309w fine and this is the newer model. I have been fiddling around with my xorg.conf to try to get the settings right and I keep just messing everything up. I was wondering if anyone could give me a hand getting the proper resolution to work. </p>
<p>Here is my current xorg.conf.</p>
<pre><code>Section "ServerLayout"
Identifier "Layout0"
Screen 0 "Screen0" 0 0
InputDevice "Keyboard0" "CoreKeyboard"
InputDevice "Mouse0" "CorePointer"
EndSection
Section "Files"
EndSection
Section "Module"
Load "dbe"
Load "extmod"
Load "type1"
Load "freetype"
Load "glx"
EndSection
Section "ServerFlags"
Option "Xinerama" "0"
EndSection
Section "InputDevice"
# generated from default
Identifier "Mouse0"
Driver "mouse"
Option "Protocol" "auto"
Option "Device" "/dev/psaux"
Option "Emulate3Buttons" "no"
Option "ZAxisMapping" "4 5"
EndSection
Section "InputDevice"
# generated from default
Identifier "Keyboard0"
Driver "kbd"
EndSection
Section "Monitor"
Identifier "Monitor0"
VendorName "Unknown"
ModelName "CRT-0"
HorizSync 28.0 - 33.0
VertRefresh 43.0 - 72.0
Option "DPMS"
EndSection
Section "Device"
Identifier "Device0"
Driver "nvidia"
VendorName "NVIDIA Corporation"
BoardName "GeForce 6800"
EndSection
Section "Screen"
Identifier "Screen0"
Device "Device0"
Monitor "Monitor0"
DefaultDepth 24
Option "TwinView" "1"
Option "TwinViewXineramaInfoOrder" "CRT-1"
Option "metamodes" "CRT-0: nvidia-auto-select +0+0, CRT-1: 1920x1080 +640+0"
SubSection "Display"
Depth 24
EndSubSection
EndSection
</code></pre>
<p>Thanks so much in advance!</p>
| <p>I use an old CRT View Sonic monitor as Screen0 and a LCD Samsung 720p TV as Screen1.
It used to work "out of the box" with my "old" Nvidia drivers, but now the resolution in the Screen0 kept going automatically to 640x480, even tough my monitor supports 1024x768; Option "metamodes" was not solving the problem, and the command "xrandr" would throw me randomly 640x480 and 1024x768 as my maximum resolution.
Trial and error, I managed to solve the problem simply adding </p>
<p>Modes "1024x768"</p>
<p>to the <strong>SubSection of Screen0</strong>. In the end this is the result of my working xorg.conf:</p>
<pre><code># nvidia-settings: X configuration file generated by nvidia-settings
# nvidia-settings: version 1.0 (buildd@yellow) Fri Apr 9 11:51:21 UTC 2010
Section "ServerLayout"
Identifier "Layout0"
Screen 0 "Screen0" RightOf "Screen1"
Screen 1 "Screen1" 0 0
InputDevice "Keyboard0" "CoreKeyboard"
InputDevice "Mouse0" "CorePointer"
Option "Xinerama" "0"
EndSection
Section "Files"
EndSection
Section "InputDevice"
# generated from default
Identifier "Mouse0"
Driver "mouse"
Option "Protocol" "auto"
Option "Device" "/dev/psaux"
Option "Emulate3Buttons" "no"
Option "ZAxisMapping" "4 5"
EndSection
Section "InputDevice"
# generated from default
Identifier "Keyboard0"
Driver "kbd"
EndSection
Section "Monitor"
# HorizSync source: edid, VertRefresh source: edid
Identifier "Monitor0"
VendorName "Unknown"
ModelName "ViewSonic E40-3"
HorizSync 30.0 - 50.0
VertRefresh 50.0 - 90.0
Option "DPMS"
EndSection
Section "Monitor"
# HorizSync source: edid, VertRefresh source: edid
Identifier "Monitor1"
VendorName "Unknown"
ModelName "Samsung SyncMaster"
HorizSync 30.0 - 81.0
VertRefresh 56.0 - 75.0
Option "DPMS"
EndSection
Section "Device"
Identifier "Device0"
Driver "nvidia"
VendorName "NVIDIA Corporation"
BoardName "GeForce GT 220"
BusID "PCI:1:0:0"
Screen 0
EndSection
Section "Device"
Identifier "Device1"
Driver "nvidia"
VendorName "NVIDIA Corporation"
BoardName "GeForce GT 220"
BusID "PCI:1:0:0"
Screen 1
EndSection
Section "Screen"
Identifier "Screen0"
Device "Device0"
Monitor "Monitor0"
DefaultDepth 24
Option "TwinView" "0"
Option "TwinViewXineramaInfoOrder" "CRT-0"
Option "metamodes" "CRT: 1024x768 +0+0"
SubSection "Display"
Modes "1024x768"
Depth 24
EndSubSection
EndSection
Section "Screen"
Identifier "Screen1"
Device "Device1"
Monitor "Monitor1"
DefaultDepth 24
Option "TwinView" "0"
Option "metamodes" "DFP: nvidia-auto-select +0+0"
SubSection "Display"
Depth 24
EndSubSection
EndSection
</code></pre>
|
How to set Row Filter for Dataview to filter rows according to valu of column? <p>Hii,
I am using DataView control to bind a gridview. In dataview data is coming from a table 'cloneUserEntry'. cloneUserEntry table contains a column 'Visibility' whose value is true or false (boolean type). I want to display rows whose visibility is true.
So how to set row filter to filter rows whose column 'visiility' contains only true.
I am using code as following..</p>
<pre><code>Boolean var=true ;
gvUserDataReadOnly.DataSource = new DataView(cloneUserEntry, string.Format("Visibility = #{0}#", var), "FirstName ASC", DataViewRowState.CurrentRows);
</code></pre>
<p>but this is not working.
can anyone ell me how to do this task..?? Thanks in advance..</p>
| <p>Try removing the # characters from the filter statement, i.e., <code>"Visibility = true"</code> instead of <code>"Visibility = #true#"</code>. The # are used when filtering using DateTime objects.</p>
|
Is there any algorithm for search an element in sorted array with complexity less than log2(n) <p>i have coded an algorithm for search in sorted array with complexity log2(n)/5 .Is it useful?</p>
| <p>It is provable that you can't get lower than O(log(n)) for a search that assumes only compare operations. a complexity of log2(n)/5 is the same thing as O(log(n)).<br />
Usefulness depends on what you use it for.</p>
|
Programtically Reloading a C# Project <p>HI</p>
<p>Does anyone know if its is possible to programatically reload a C# project , in one of my previous <a href="http://stackoverflow.com/questions/510295/auto-include-files-in-a-c-project">questions</a> i needed to add all the CS files in a specific folder , now while this works i find that i have to reload the project every time to so that it can register the new files were added.</p>
<p>So now i need a way to automtically reload after the project had been generated.</p>
| <p>I assume, for the first time when you output all the DAL files, you are also creating a file with extension .csproj listing in it, all the files you just added in the folder.</p>
<p><strong><em>If my assumption above is right</em>:</strong>
When you want to add more files, you can programatically edit the same .csproj file from your c# code. Then, Visual studio will force the project reload saying it has changed outside the environment.</p>
<p><strong><em>If my assumption above is wrong:</em></strong>
You can create the .csproj file, It should be easy and straight forward.</p>
<p>I am not sure If I got your question right.</p>
|
Looking for commercial UI rich controls for ASP.NET MVC <p>I'm looking for a commercial suite of rich UI controls for ASP.NET MVC. (<em>commercial</em> suites, I know jQuery has a lot of free stuff) This means no postbacks. And preferably built with jQuery.</p>
<p>some webform examples:
<a href="http://www.infragistics.com" rel="nofollow">www.infragistics.com</a>
<a href="http://www.componentart.com/" rel="nofollow">http://www.componentart.com/</a></p>
| <p><a href="http://www.telerik.com/products/aspnet-ajax.aspx" rel="nofollow">Telerik RadControls</a> for ASP .NET <a href="http://blogs.telerik.com/AtanasKorchev/Posts/08-11-06/ASP_NET_Ajax_Controls_in_ASP_NET_MVC.aspx" rel="nofollow">has support for ASP .NET MVC</a>.</p>
|
Advice on moving to a multi tier Delphi architecture <p>We have a relatively large application that is strongly tied into Firebird (stored procedures, views etc). We are now getting a lot of requests to support additional databases and we would also like to move a lot of the functionality from the client to the server.</p>
<p>Now seems like a good time to move to a 3(4) tier architecture. We have already looked at DataSnap 2009 and RemObjects SDK/DataAbstract. Both seem like they would do the job, but are there any advantages/disadvantages we should look out for? Are there any other frameworks that you could recommend?</p>
<p>Cheers,
Paul</p>
| <p>I can recommend using the KBM Middleware components from Components4Developers. There is a bit of a learning curve but they are very flexible and hold up well under use in real world conditions.</p>
<p><A HRef="http://www.components4programmers.com/usercomments/commentfromapowerusertoaquestion.htm" rel="nofollow">Comment from a user (<a href="http://www.components4programmers.com/usercomments/commentfromapowerusertoaquestion.htm" rel="nofollow">http://www.components4programmers.com/usercomments/commentfromapowerusertoaquestion.htm</a>) </a></p>
|
Getting WM/Picture using C# and WM Encoder SDK <p>I was hoping someone could help point me in the right direction and/or provide a sample for me to look at. I need to get the WM/Picture field inside a WMA file that I decode using WM Encoder and C#. I have been able to get all the other tags fine, but media.getAttributeCountByType("WM/Picture", "") function always return 0. But Windows Media Player can display the picture correctly and I saw two hidden JPG files under the same music folder. MSDN don't provide much information about it. Thanks.</p>
| <p>program chat voice with c#</p>
|
How to set the UIImageView's position relative to sibling views <p>How to set the UIImageView's <s>layer</s> position relative to sibling views?</p>
<p>I mean like the swapDepths() / setChildIndex() in flash</p>
<p>many thanks for reading</p>
| <p>It would be useful to describe what you are attempting in absolute terms, not by referring to another framework people may not be familiar with (particularly since "Layer" has its own special meaning in Cocoa.</p>
<p>If by "layer" you mean its position relative to sibling views then you can use the following functions. </p>
<pre><code>bringSubviewToFront
sendSubviewToBack
exchangeSubviewAtIndex
</code></pre>
<p>Note that these are called on the PARENT of the UIView / UIImageView you wish to reposition. E.g. this would bring the imageview infront of its siblings;</p>
<pre><code>[imageView.superview bringSubviewToFront: imageView];
</code></pre>
|
C#: Anonymous types and property names <p>Is there any difference at all between this:</p>
<pre><code>dataContext.People.Select(ø => new
{
Name = ø.Name,
});
</code></pre>
<p>and this:</p>
<pre><code>dataContext.People.Select(ø => new
{
ø.Name,
});
</code></pre>
<p>?</p>
| <p>They are identical; if no name is specified (and the right-hand-side is a simple member-access) then the name of the existing member is assumed. The name is only necessary to:</p>
<ul>
<li>change the name to something <em>else</em> (for example <code>Name = grp.Key</code>)</li>
<li>to give a name to a non-member-access expression (for example <code>Count = grp.Count()</code>)</li>
</ul>
|
Does the ClientScriptmanager work when called in a partial postback? <p>I would like to close the browser window when an ASP.NET operation has succeeded. The code below is triggered by a button that resides in an Ajax UpdatePanel.</p>
<pre><code>Page.ClientScript.RegisterClientScriptBlock(typeof(LeaveApproval), "ShowSuccess", "<script language=javascript>window.opener=self; self.close();</script>");
</code></pre>
<p>However, this code does not seem to have any effect. The window is not closed. When I enter the javascript into the URL bar of my browser it works fine, so I'm guessing this has something to do with using the ClientScriptManager together with Ajax. </p>
<p>Any idea what I am doing wrong?</p>
| <p><a href="http://www.gotjeep.net/Blogs/CommentView,guid,4be2f278-12e4-40d5-b154-0e8ecaf18fac.aspx" rel="nofollow">This link</a> by Scott Klueppel helped me solve the problem... </p>
<p>Rather use...</p>
<pre><code>ScriptManager.RegisterStartupScript
</code></pre>
<p>instead of </p>
<pre><code>Page.ClientScript.RegisterClientScriptBlock.
</code></pre>
|
Weird Bug: "DoCmd.OutputTo acOutputQuery" is deleting the query <p>I'm encountering a problem where <code>DoCmd.OutputTo acOutputQuery</code> deletes the query itself the second time it is run.</p>
<p>Is there any workaround/patch for this bug (at least seems like a bug to me)?</p>
| <p>I think the behaviour you described "...deletes the query itself, the second time it is run" occurs when the query returns no records.</p>
|
How would you query an array of 1's and 0's chars from a database? <p>Say you had a long array of chars that are either 1 or 0, kind of like a bitvector, but on a database column. How would you query to know what values are set/no set? Say you need to know if the char 500 and char 1500 are "true" or not.</p>
| <pre><code>SELECT
Id
FROM
BitVectorTable
WHERE
SUBSTRING(BitVector, 500, 1) = '1'
AND SUBSTRING(BitVector, 1000, 1) = '1'
</code></pre>
<p>No index can be used for this kind of query, though. When you have many rows, this will get slow very quickly.</p>
<p>Edit: On SQL Server at least, all built-in string functions are <a href="http://msdn.microsoft.com/en-us/library/ms178091.aspx" rel="nofollow">deterministic</a>. That means you could look into the possibility to make computed columns based on the SUBSTRING() results for the whole combined value, <a href="http://msdn.microsoft.com/en-us/library/ms189292.aspx" rel="nofollow">putting an index on each of them</a>. Inserts will be slower, table size will increase, but searches will be really fast.</p>
<pre><code>SELECT
Id
FROM
BitVectorTable
WHERE
BitVector_0500 = '1'
AND BitVector_1000 = '1'
</code></pre>
<p>Edit #2: The <a href="http://msdn.microsoft.com/en-us/library/ms143432.aspx" rel="nofollow">limits for SQL Server</a> are:</p>
<ul>
<li>1,024 columns per normal table</li>
<li>30.000 columns per "wide" table</li>
</ul>
|
JavaScript drag and drop photo resizer cropper <p>I have an image of arbitrary size on the page. As an output I need an image of a fixed size, say <em>90x120px</em>. I would like the user to chose the area of the image by drag-and-dropping the big image behind the <em>90x120px</em> 'window'. The window would specify the resulting image. Something like this is implemented at <a href="http://www.facebook.com/editpicture.php" rel="nofollow">facebook image upload</a>.</p>
<p>I know how to deal with the image at backend as soon as I get the cropping coordinates, no problem with that. I guess I need to post the cropping coordinates in hidden form fields. User's drag-and-dropping action should make JavaScript populate the fields, right? I am new to JS, so a step-by-step guide would help a lot.</p>
| <p>For cropping, use <a href="http://jquery.com/">jQuery</a> and <a href="http://deepliquid.com/content/Jcrop.html">Jcrop</a>.</p>
|
How to force a Silverlight container to expand/contract to the size of its child controls? <p>I've got a root UserControl that is 300 high.</p>
<p>Inside that I have a Border that I want to expand to the size of its own controls, so if I stack in more controls, it will expand -- less controls, it will contract.</p>
<p>However when I set it to "Auto" it expands it out to the size of <em>its parent container</em> instead of the size of its <em>child controls</em>.</p>
<p>How can I get Border to expand and contract to the size of its child controls, something like the functionality of an HTML table?</p>
<pre><code><UserControl x:Class="Second105.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<Border
Background="Tan"
CornerRadius="10"
Padding="10"
Width="300"
Height="Auto">
<StackPanel>
<TextBlock HorizontalAlignment="Center" Margin="0 0 0 5">Please select a <Run FontStyle="Italic">week day</Run>:</TextBlock>
<basics:Calendar
Name="theCalendar"
SelectedDatesChanged="Calendar_SelectedDatesChanged"/>
<TextBlock
Name="theMessage"
Margin="0 10 0 0"
HorizontalAlignment="Center"
Text="..."/>
</StackPanel>
</Border>
</Grid>
</UserControl>
</code></pre>
| <p>Wrap it in a StackPanel should do it:</p>
<pre><code><UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400"
Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel>
<Border
Width="300"
Height="Auto"
Background="Tan"
CornerRadius="10"
Padding="10">
<StackPanel>
<TextBlock HorizontalAlignment="Center" Margin="0 0 0 5">Please select a
<Run FontStyle="Italic">week day
</Run>:
</TextBlock>
<TextBlock
Name="theMessage"
HorizontalAlignment="Center"
Margin="0 10 0 0"
Text="..."/>
</StackPanel>
</Border>
</StackPanel>
</Grid>
</UserControl>
</code></pre>
|
ADO.NET - What is best practice for getting datareader values? <p>Just wondering what is best practice for getting the values of a datareader. For example:</p>
<p>I have been doing this:</p>
<pre><code>MyValue = Dr("ColumnName")
</code></pre>
<p>But have noticed other people doing:</p>
<pre><code>MyValue = Dr.GetString("ColumnName")
</code></pre>
<p>I am intested to know the benifits of the 2nd method</p>
| <p>The DbDataReader.GetString(int) method can only be used if you know the index of the column. Using DbDataReader.GetString("ColumnName") is not possible as there is no such overload. I.e. you have the following two options:</p>
<pre><code> string myValue1 = (string) Dr["ColumnName"];
string myValue2 = Dr.GetString(columIndex);
</code></pre>
<p>The first line internally calls DbDataReader.GetOrdinal("ColumnName").</p>
|
Ajax onSuccess callback while not having any control over ajax calls <p>I have a simple JS function that needs to get called when AJAX call succeeds, however i don't have any control over the AJAX calls since the framework (DNN5) handles all that.</p>
<p>How do i call my function on AJAX success?</p>
<p>I use DNN5 and jQuery, if you're not familiar with DNN, just assume that all the controls on the page are wrapped in the asp:UpdatePanel.</p>
<p>Thank you.</p>
| <p>I'm not familiar with DNN5, but am with UpdatePanels. Can you hook into the Client events of an async postback in ASP.NET AJAX i.e. add an eventhandler to the PageRequestManager endRequest event.</p>
<p>As an example,</p>
<pre><code> var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequest);
// runs when async postback completes.
function EndRequest(sender, args)
{
if (sender._postBackSettings.sourceElement.id) // the id of the element that raised the postback that is completing
{
//Do what you need to do here
}
}
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Thinking about it, I'm not sure whether this will work for you. It'll depend on how DNN5 performs the AJAX calls within ASP.NET</p>
|
How to use Drupal 6 views and panels arguments together? <p>I need to acheive the following layout/setup for a section of my website:</p>
<p>Using the following panels layout:</p>
<p><strong>Top column spanning full width</strong> containing:<br />
- a view (prob themed using jquery cycle) of images relating to current node</p>
<p><strong>3 columns below</strong> containing: </p>
<ol>
<li><p>Left column: List of 4 single hierarchy taxonomy terms:</p>
<ul>
<li>Term 1 </li>
<li>Term 2 (selected) </li>
<li>Term 3 </li>
<li>Term 4</li>
</ul></li>
<li><p>Middle column: List view of node titles tagged with taxonomy term selected in left column </p>
<ul>
<li>Node1 title (tagged with term 2) (selected)</li>
<li>Node2 title (tagged with term 2)</li>
<li>etc.</li>
</ul></li>
<li><p>Right column: Contents of node selected in middle column</p>
<ul>
<li>Node 1</li>
</ul></li>
</ol>
<p>I'm a newbie. I think in theory I can do this with just views and panels, passing the term id and node id as arguments. But I need someone to point me in the right direction because I don't know how to make the views and panels arguments and contexts work together. Thanks.</p>
| <p>You're probably better off ditching panels and just making a block yourself to display the top panel. The <a href="http://drupal.org/project/acquia%5Fmarina" rel="nofollow">Acquia Marina theme</a> has a layout that lets you have this exact setup - a block above your content but below the header, with up to 3 columns underneath that. Just go ahead and copy their layout code from a finished page to get the effect you're looking for without having to use the panels module at all.</p>
|
Complex query in nHibernate using DetachedCriteria <p>I'm currently trying to move from hand-crafted hql to queries constructed via DetachedCriteria. I have and HQL:</p>
<pre><code>from GenericObject genericObject
left join fetch genericObject.Positions positions
where (positions.Key.TrackedSourceID, positions.Key.PositionTimestamp) in
(select gp.Key.TrackedSourceID, max(gp.Key.PositionTimestamp)
from GenericPosition gp
group by gp.Key.TrackedSourceID)
</code></pre>
<p>Now using DetachedCriteria:</p>
<pre><code>var subquery = DetachedCriteria
.For (typeof (GenericPosition), "gp")
.SetProjection (Projections.ProjectionList ()
.Add (Projections.Property ("gp.Key.TrackedSourceID"))
.Add (Projections.Max ("gp.Key.PositionTimestamp"))
.Add (Projections.GroupProperty ("gp.Key.TrackedSourceID"))
);
var criteriaQuery = DetachedCriteria
.For (typeof (GenericObject), "genericObject")
.CreateAlias ("genericObject.Positions", "positions")
.SetFetchMode ("genericObject.Positions", FetchMode.Eager)
.Add (Subqueries.In (??, subquery))
</code></pre>
<p>I don't know what to type instead of ?? to create expression like (positions.Key.TrackedSourceID, positions.Key.PositionTimestamp)</p>
| <p>I cannot see the advantage in moving from hql to DetachedCriteria, if the latter is more difficult to write. And read.</p>
<p>In my projects I use preferrably DetachedCriteria, unless the syntax gets too complicated. Then I use hql. Until it gets complicated again. Then I give it a try in sql, and go back to hql if it doesn't improve readability. </p>
<p>Keep in mind that you will have to maintain these queries in the future.</p>
|
Tool (or combination of tools) for reproducible environments in Python <p>I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team. </p>
<p>I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java.</p>
| <ol>
<li><p><a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> to create a contained virtual environment (prevent different versions of Python or Python packages from stomping on each other). There is increasing buzz from people moving to this tool. The author is the same as the older working-env.py mentioned by Aaron.</p></li>
<li><p><a href="http://pypi.python.org/pypi/pip">pip</a> to install packages inside a virtualenv. The traditional is easy_install as answered by S. Lott, but pip works better with virtualenv. easy_install still has features not found in pip though.</p></li>
<li><p><a href="http://www.scons.org/">scons</a> as a build tool, although you won't need this if you stay purely Python.</p></li>
<li><p><a href="http://pypi.python.org/pypi/Fabric/0.0.3">Fabric</a> paste, or <a href="http://www.blueskyonmars.com/projects/paver/">paver</a> for deployment.</p></li>
<li><p><a href="http://buildbot.net/trac">buildbot</a> for continuous integration.</p></li>
<li><p>Bazaar, mercurial, or git for version control.</p></li>
<li><p><a href="http://somethingaboutorange.com/mrl/projects/nose/">Nose</a> as an extension for unit testing.</p></li>
<li><p><a href="http://pypi.python.org/pypi/PyFIT/0.8a2">PyFit</a> for <a href="http://fit.c2.com">FIT</a> testing.</p></li>
</ol>
|
Which .config element affects exception handling with UnhandledExceptionMode set to UnhandledExceptionMode.Automatic? <p>I have a Windows Forms application that has this code in the program's start up:</p>
<pre><code>Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic);
</code></pre>
<p>In the MSDN Documentation for <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.unhandledexceptionmode(VS.85).aspx">UnhandledExceptionMode.Automatic</a> it states that:</p>
<blockquote>
<p><strong>Automatic</strong> - Route all exceptions to
the ThreadException handler, unless
the application's configuration file
specifies otherwise.</p>
</blockquote>
<p>Does anyone know exactly which element/attribute in the config file it is that affects this setting?</p>
| <p>You can add a JitDebugging section to your config file like this:</p>
<pre><code><configuration>
<system.windows.forms jitDebugging="true"/>
</configuration>
</code></pre>
<p>This is equivalent to setting the UnhandledExceptionMode to <code>UnhandledExceptionMode.ThrowException</code> (incidentally, if you run your application with a Debugger attached, this option is automatically enabled).</p>
<p>Note that <code>UnhandledExceptionMode.Automatic</code> is the default used by .Net unless you specify otherwise; as far as I can tell, the only reason to explicitly set the Unhandled Exception Mode to Automatic is if you want to undo a previous call that changed it to something else. Note that if you do set it to something other than Automatic, the configuration file setting will not be read.</p>
<p>Note that if you attach a ThreadException to the current AppDomain, the result is automatically as if you had set the UnhandledExceptionMode to <code>UnhandledExceptionMode.CatchException</code>.</p>
|
how to have make targets for separate debug and release build directories? <p>I am looking for suggestions to properly handle separate debug and release build subdirectories, in a recursive makefile system that uses the $(SUBDIRS) target as documented in the gnumake manual to apply make targets to (source code) subdirectories. </p>
<p>Specifically, I'm interested in possible strategies to implement targets like 'all', 'clean', 'realclean' etc. that either assume one of the trees or should work on both trees are causing a problem. </p>
<p>Our current makefiles use a COMPILETYPE variable that gets set to Debug (default) or Release (the 'release' target), which properly does the builds, but cleaning up and make all only work on the default Debug tree. Passing down the COMPILETYPE variable gets clumsy, because whether and how to do this depends on the value of the actual target.</p>
| <p>One option is to have specific targets in the subdirectories for each build type. So if you do a "make all" at the top level, it looks at COMPILETYPE and invokes "make all-debug" or "make all-release" as appropriate.</p>
<p>Alternatively, you could set a COMPILETYPE environment variable at the top level, and have each sub-Makefile deal with it.</p>
<p>The real solution is to not do a recursive make, but to include makefiles in subdirectories in the top level file. This will let you easily build in a different directory than the source lives in, so you can have <em>build_debug</em> and <em>build_release</em> directories. It also allows parallel make to work (make -j). See <a href="http://miller.emu.id.au/pmiller/books/rmch/" rel="nofollow">Recursive Make Considered Harmful</a> for a full explanation.</p>
|
How to call web service using vbscript (synchronous)? <p>Actually there many examples and I have used one of them. But it works asynchronous, I mean it is not waiting the function that I called to finish.</p>
<pre><code>function ProcessSend()
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.4.0")
Set oXMLDoc = CreateObject("MSXML2.DOMDocument")
oXMLHTTP.onreadystatechange = getRef("HandleStateChange")
strEnvelope = "callNo="&callNo&"&exp="&exp
call oXMLHTTP.open("POST","http://localhost:11883/ServiceCall.asmx/"&posFirm,true)
call oXMLHTTP.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
call oXMLHTTP.send(strEnvelope)
end function
Sub HandleStateChange
if(oXMLHTTP.readyState = 4) then
dim szResponse: szResponse = oXMLHTTP.responseText
call oXMLDoc.loadXML(szResponse)
if(oXMLDoc.parseError.errorCode <> 0) then
'call msgbox("ERROR")
response = oXMLHTTP.responseText&" "&oXMLDoc.parseError.reason
'call msgbox(oXMLDoc.parseError.reason)
else
response = oXMLDoc.getElementsByTagName("string")(0).childNodes(0).text
end if
end if
End Sub
</code></pre>
<p>I call ProcessSend function in a javascript function. It connects to webservice, and returns the "response" variable. But my javascript function do not wait ProcessSend function result.
How can I make it synchronous?</p>
| <p>If you're doing synchronous calls, you don't need the callback, and you can shrink the code into this:</p>
<pre><code>function ProcessSend()
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.4.0")
Set oXMLDoc = CreateObject("MSXML2.DOMDocument")
strEnvelope = "callNo=" & callNo & "&exp=" & exp
call oXMLHTTP.open("POST", "http://localhost:11883/ServiceCall.asmx/"&posFirm, false)
call oXMLHTTP.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
call oXMLHTTP.send(strEnvelope)
dim szResponse: szResponse = oXMLHTTP.responseText
call oXMLDoc.loadXML(szResponse)
if(oXMLDoc.parseError.errorCode <> 0) then
'call msgbox("ERROR")
response = oXMLHTTP.responseText&" "&oXMLDoc.parseError.reason
'call msgbox(oXMLDoc.parseError.reason)
else
response = oXMLDoc.getElementsByTagName("string")(0).childNodes(0).text
end if
End Sub
</code></pre>
|
Creating two pdf pages with Imagick <p>Currently i can create PDF files from images in Imagick with this function</p>
<pre><code>$im->setImageFormat("pdf");
$im->writeImage("file.pdf");
</code></pre>
<p>And it's possible to fetch multiple pages with imagick like this</p>
<pre><code>$im = new imagick("file.pdf[0]");
$im2 = new imagick("file.pdf[1]");
</code></pre>
<p>But is it possible to save two image objects to two pages?
(example of what i am thinking, its not possible like this)</p>
<pre><code>$im->setImageFormat("pdf");
$im->writeImage("file.pdf[0]");
$im2->setImageFormat("pdf");
$im2->writeImage("file.pdf[1]");
</code></pre>
| <p>I know this is long past due, but this result came up when I was trying to do the same thing. Here is how you create a multi-page PDF file in PHP and Imagick.</p>
<pre><code> $images = array(
'page_1.png',
'page_2.png'
);
$pdf = new Imagick($images);
$pdf->setImageFormat('pdf');
if (!$pdf->writeImages('combined.pdf', true)) {
die('Could not write!');
}
</code></pre>
|
Converting XML between schemas - XSLT or Objects? <p>Given:</p>
<ul>
<li>Two similar and complex Schemas, lets call them XmlA and XmlB.</li>
<li>We want to convert from XmlA to XmlB</li>
<li>Not all the information required to produce XmlB is contained withing XmlA (A database lookup will be required)</li>
</ul>
<p>Can I use XSLT for this given that I'll need to reference additional data in the database? If so what are the arguments in favour of using XSLT rather than plain old object mapping and conversion? I'm thinking that the following criteria might influence this decision:</p>
<ul>
<li>Performance/speed</li>
<li>Memory usage</li>
<li>Code reuse/comlpexity</li>
</ul>
<p>The project will be C# based.</p>
<p>Thanks.</p>
| <p>With C# you can always provide extension objects to XSLT transforms, so that's a non-issue.</p>
<p>It's hard to qualitatively say without having the schemas and XML to hand, but I imagine a compiled transform will be faster than object mapping since you'll have to do a fair amount of wheel reinventing.</p>
<p>Further, one of the huge benefits of XSLT is it's maintainability and portability. You'll be able to adapt the XSLT doc really quickly with schema changes, and on-the-fly without having to do any rebuilds and takedowns if you're monitoring the file.</p>
<p>Could go either way based on what you've given us though.</p>
|
Algorithm to compute a Voronoi diagram on a sphere? <p>I'm looking for a simple (if exists) algorithm to find the Voronoi diagram for a set of points on the surface of a sphere. Source code would be great. I'm a Delphi man (yes, I know...), but I eat C-code too.</p>
| <p>I don't have ACM document access but there's a paper on <a href="http://portal.acm.org/citation.cfm?id=636913">spherical Voronoi diagrams</a>.</p>
<p>Or if you grok Fortran (bleah!) there's <a href="http://people.sc.fsu.edu/~burkardt/f_src/sxyz_voronoi/sxyz_voronoi.html">this site</a>.</p>
|
Do you know of anyway to get a distinct result set without using the ResultTransformer when using SetFirstResult and SetMaxResults? <p>When i use SetFirstResult and SetMaxResult and if the query has joins the result have duplicate results instead of unique.</p>
<p>Then i use all type of Distinct helpers for criteria api. But it doesnt filter the whole result set it just filters the paged result.</p>
<p>How can i overcome this issue ?</p>
<p>Thanks</p>
| <p>I have found a <a href="http://opensource.atlassian.com/projects/hibernate/browse/HB-520" rel="nofollow">hacky thing to overcome</a> this issue.</p>
<blockquote>
<p>The only "workaround" for this that
I've been able to come up with is to
issue two queries from the criteria
same criteria object. The first one
gets the id's the second one is
contrained to the ids. </p>
<p>//set up crtieria as you wish,
including pagination myCriteria =
doStuffToSetupCriteria();
myCriteria.setFirstResult((page-1)*itemsPerPage);
myCriteria.setMaxResults(itemsPerPage);</p>
<p>//get the list if primary keys
myCriteria.setProjection(Projections.distinct(Projections.property("myAllias.id"));
List ids = gacc.list();</p>
<p>//now add the id's into the
restriction
myCriteria.add(Restrictions.in("myAlias.id,
ids));</p>
<p>//clean up from the last critiera run
gacc.setProjection(null);
gacc.setFirstResult(0);
gacc.setMaxResults(Integer.MAX_VALUE);</p>
<p>//your results List objects =
gacc.list()</p>
<p>A little hacky I agree, but the only
acceptable soltion I could find given
this limitiation.</p>
</blockquote>
|
Firefox Div Problem <p>I'm trying to make a little gallery of some school works I've done in my animation class. I want to put 3 images on each line and they are all in divs because I did onion skin wrapping for a dropshadow on them. Unfortunately this makes them all just stick together in two lines across the page. But I want them specifically formatted so I tried to wrap a div of 480px wide around each set of 3. In IE this works great and it looks perfect. However in firefox it does this</p>
<p><img src="http://i44.tinypic.com/1r5hdg.jpg" width="512" height="384"></p>
<p>I can't figure out why it is putting that one left aligned on the second line and therefore screwing up the order of the rest. Here's my code:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ryan Merl's Portfolio</title>
<style type='text/css'>
* {
padding: 0px;
margin: 0px;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size: 11px;
}
body {
background-color:#333333;
background-image: url('images/head.png');
background-repeat: repeat-x;
}
a {
color:#333333;
text-decoration: none;
}
a:hover {
color:#000000;
text-decoration:underline;
}
div.main {
width: 800px;
background-color:#FFFFFF;
margin-top: 10px;
color: #000000;
height: 1000px;
margin-bottom: 10px;
}
img.thumb {
}
.wrap1, .wrap2, .wrap3 {
display:inline-table;
/* \*/display:block;/**/
}
.wrap1 {
float:left;
background:url('images/shadow.gif') right bottom no-repeat;
}
.wrap2 {
background:url('images/corner_bl.gif') left bottom no-repeat;
}
.wrap3 {
padding:0 4px 4px 0;
background:url('images/corner_tr.gif' ) right top no-repeat;
}
</style>
<link rel="stylesheet" type="text/css" href="doc/css/style.css" />
<script type="text/javascript" src="src/adapter/shadowbox-base.js"></script>
<script type="text/javascript" src="src/shadowbox.js"></script>
<script type="text/javascript" src="glossy.js"></script>
<script type="text/javascript">
Shadowbox.loadSkin('classic', 'src/skin');
Shadowbox.loadLanguage('en', 'src/lang');
Shadowbox.loadPlayer(['flv', 'html','img', 'swf'], 'src/player');
window.onload = function(){
Shadowbox.init();
};
</script>
</head>
<body>
<center><div class='main'>
<img src='images/theantistudio.png' /><br /><br />
<img src='images/gallery.png' /><br />
<div style='text-align:center;width:480px;'>
<div class="wrap1">
<div class="wrap2">
<div class="wrap3">
<a href='video/rmerl_particle_fire.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_fire.png' /></a>
</div>
</div>
</div>
<div class="wrap1">
<div class="wrap2">
<div class="wrap3">
<a href='video/rmerl_firework.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_firework.png' /></a>
</div>
</div>
</div>
<div class="wrap1">
<div class="wrap2">
<div class="wrap3">
<a href='video/rmerl_fountain.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_fountain.png' /></a>
</div>
</div>
</div>
</div>
<br />
<div style='text-align:center;width:480px;'>
<div class="wrap1">
<div class="wrap2">
<div class="wrap3">
<a href='video/rmerl_logo.flv' rel='shadowbox'><img class='thumb' src= 'thumbs/thumb_logo.png' /></a>
</div>
</div>
</div>
<div class="wrap1">
<div class="wrap2">
<div class="wrap3">
<a href='video/rmerl_rocket_ship.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_rocket.png' /></a>
</div>
</div>
</div>
<div class="wrap1">
<div class="wrap2">
<div class="wrap3">
<a href='video/rmerl_solar_system.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_solar_system.png' /></a>
</div>
</div>
</div>
</div>
<br />
<div style='text-align:center;width:480px;'>
<div class="wrap1">
<div class="wrap2">
<div class="wrap3">
<a href='video/rmerl_space_ship.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_space_ship.png' /></a>
</div>
</div>
</div>
<div class="wrap1">
<div class="wrap2">
<div class="wrap3">
<a href='video/rmerl_still_life.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_still_life.png' /></a>
</div>
</div>
</div>
<div class="wrap1">
<div class="wrap2">
<div class="wrap3">
<a href='video/rmerl_walkthrough.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_walkthrough.png' /></a>
</div>
</div>
</div>
</div>
</div></center>
</body>
</html>
</code></pre>
| <p>It looks like your second image may be slightly taller than your third. So your floated second line is only floating back until it hits the second image. Either set your image or wrap1 heights, or add style="clear:both" to the break tags between lines.</p>
|
Calling MS .Net Webservices with Ruby <p>Has anyone done this / have some example code? </p>
| <pre><code>#use .wsdl file to initialize an RPC driver
driver = SOAP::WSDLDriverFactory.new('dotnetwebservice.wsdl').create_rpc_driver
#useful debugging call
driver.wiredump_dev = STDERR
#Set the enconding style to ASP.NET
driver.default_encodingstyle = SOAP::EncodingStyle::ASPDotNetHandler::Namespace
#call method defined in .wsdl
result = driver.serviceMethod()
</code></pre>
<p>For more info: <a href="http://dev.ctor.org/soap4r" rel="nofollow">http://dev.ctor.org/soap4r</a></p>
|
Float in Database to ? in .NET <p>If you have a float in MSSQLServer, to what do you map this in .NET?</p>
<p>Can you convert it to Double or will you lose numbers?</p>
| <p>SQLServer <code>float</code> and C#/VB <code>double</code> have the same representation. This is the correct mapping. What you don't want to do is map SQL Server <code>float</code> to C#/VB <code>float</code> as that may involve a loss of precision. SQL Server <code>real</code> maps onto C#/VB <code>float</code>.</p>
<p>T-SQL float and real type definitions can be found at <a href="http://msdn.microsoft.com/en-us/library/ms173773.aspx">MSDN</a>. C# double definition can be found at <a href="http://msdn.microsoft.com/en-us/library/678hzkk9.aspx">MSDN</a> as well, as can the float <a href="http://msdn.microsoft.com/en-us/library/b1e65aza.aspx">definition</a>.</p>
|
What is Erlang written in? <p>What is Ericsson's implementation of Erlang and Erlang/OTP written and compiled in? Is is assembly, C or Erlang itself?</p>
<p>Update 1: Thanks to DrJokepu. If I understand correctly, Erlang source-to-VM compiler is written in Erlang itself. But the VM is written in C.</p>
<p>Update 2: Hynek-Pichi-Vychodil pointed out a lot of details.</p>
<ul>
<li>VM and HW interacting drivers: in C.</li>
<li>Compiler (to VM) and libraries: in Erlang.</li>
<li>Extensions: Possible in any language by writing a port or an Erlang node in that language.</li>
</ul>
| <p>Erlang itself is written in Erlang. Sounds strange? Yes, because it is only partially true. OK look at it in more detail:</p>
<ol>
<li>Erlang preprocessor is written in Erlang.</li>
<li>Erlang parser is written in Erlang.</li>
<li>Erlang compiler to BEAM (byte-code VM) is written in Erlang.</li>
<li>Erlang compiler to HiPE (native VM extension) is written in Erlang.</li>
<li>Erlang VM BEAM and HiPE is written mostly in C.</li>
<li>Linked-in drivers are written mostly in C. (They are plugged to VM and serves communication with outside world.)</li>
<li>OTP is written in Erlang.</li>
<li>Another ports or nodes can be written in any language.</li>
</ol>
|
Is silverlight a good choice for web applications which display large amounts of data and focus on user productivity? <p>I've played some on-line demos of silverlight component packs, like Telerik, NetAdvantage and ComponentOne and although I was very impressed by what I saw, I had also the impression that the demo applications were heavy to load, even during the usage of some components.</p>
<p>I'm planning to try silverlight in a project that demands loading large amounts of data, using grids and charts.</p>
<p>What the guys who use silverlight can say about that?</p>
<p>Is silverlight a good choice for web applications which display large amounts of data and focus on user productivity?</p>
| <p>Silverlight isn't superspeedy at displaying large lists of rich data, but then well designed system would not attempt to display large lists of rich data only enough data that a user can make sense of at one time.</p>
<p>Hence silverlight makes an excellent platform for display and entry of data in an engaging manner but you need good design and backend code to really make that happen.</p>
|
How to match the first word after an expression with regex? <p>For example, in this text:</p>
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu tellus vel nunc pretium lacinia. Proin sed lorem. Cras sed ipsum. Nunc a libero quis risus sollicitudin imperdiet.</p>
</blockquote>
<p>I want to match the word after 'ipsum'.</p>
| <p>This sounds like a job for lookbehinds, though you should be aware that not all regex flavors support them. In your example:</p>
<pre><code>(?<=\bipsum\s)(\w+)
</code></pre>
<p>This will match any sequence of letter characters which follows "ipsum" as a whole word followed by a space. It does <strong>not</strong> match "ipsum" itself, you don't need to worry about reinserting it in the case of, e.g. replacements.</p>
<p>As I said, though, some flavors (JavaScript, for example) don't support lookbehind at all. Many others (most, in fact) only support "fixed width" lookbehinds â so you could use this example but not any of the repetition operators. (In other words, <code>(?<=\b\w+\s+)(\w+)</code> <em>wouldn't</em> work.)</p>
|
OpenID vs custom user login for a website used by non-tech people <p>Does anyone have experience with implementing OpenID on a non technical website? If you do, how were your non tech users reacting to the concept of OpenID and creation of the account on a different website? </p>
<p>I really like the idea of a single sign-on, but I am afraid that non-tech people who are used to create an account on every website would find it to complicated or even suspicious.</p>
<p>I know I could implement both (and that might be the route I will have to go) but I am trying to avoid implementing custom user login.</p>
<p>Also if you have links to some successful non-tech websites using OpenID only, it would be appreciated.</p>
| <p>Yahoo released their <a href="http://developer.yahoo.net/blog/archives/2008/10/open_id_research.html" rel="nofollow">OpenID usability research</a> results a while back. This will give you an insight on how OpenID is perceived by non-techies.</p>
|
How to UNPIVOT to split columns into rows? <p>I've got a sql query (using MS-SQL 2005) that generates data with these columns:</p>
<pre><code>TimeStamp | SpeedMax | SpeedMin | HeightMax | HeightMin
-------------------------------------------------------
10 | 50 | 10 | 300 | 70
</code></pre>
<p>The form I need it in though is this:</p>
<pre><code>TimeStamp | Speed | Height
---------------------------
10 | 50 | 300 <-- one row for the max values
10 | 10 | 70 <-- a second row for the min values
</code></pre>
<p>Given the first result set... what query would I need to get the data into the second format? I think it might involve an unpivot, but I'm new to that, and am having trouble working out what to write.</p>
<p>Thank you very much.</p>
| <pre><code>SELECT TimeStamp,
minmax,
CASE WHEN minmax = 0 THEN SpeedMax ELSE SpeedMin END AS Speed
CASE WHEN minmax = 0 THEN HeightMax ELSE HeightMin END AS Height
FROM Table,
(
SELECT 0 AS minmax
UNION ALL
SELECT 1
) mm
</code></pre>
<p>You may add</p>
<pre><code>OPTION (FORCE ORDER)
</code></pre>
<p>to avoid double scan on <code>Table</code></p>
|
Search, Filter AND Remove a List<List<T>> <p>I've a problem!</p>
<p>I've a </p>
<pre><code>List <List<Class>> L = new List<List<Class>>();
</code></pre>
<p>where Class contains</p>
<pre><code>IDLinea
Posizione
</code></pre>
<p>And so on...</p>
<p>I want to have a Distinct <code>List<List<Class>></code> Where there are no objects with same lines.</p>
<p>For example:</p>
<pre><code>List <List<Class>> L = new List<List<Class>>();
var A = new List<Class>();
Class C = new Class();
C.IDLinea = 1;
C.Posizione = 5;
A.Add(C);
C = new Class();
C.IDLinea = 2;
C.Posizione = 1;
A.Add(C);
L.Add(A);
var B = new List <Class>();
C = new Class();
C.IDLinea = 1;
C.Posizione = 3;
B.Add(C);
C = new Class();
C.IDLinea = 2;
C.Posizione = 1;
B.Add(C);
L.Add(B);
var D = new List <Class>();
C = new Class();
C.IDLinea = 4;
C.Posizione = 1;
D.Add(C);
C = new Class();
C.IDLinea = 2;
C.Posizione = 4;
D.Add(C);
L.Add(D);
</code></pre>
<p>So I want <strong>A and D</strong></p>
<p>I hope that what I need is clear.</p>
<p>Thanks.</p>
| <p>Edited based on your further explanation </p>
<pre><code>enum LineComparisonMode
{
///<summary>the order of the line numbers matters, default</summary>
Ordered = 0,
///<summary>the order of the line numbers doesn't matter
/// Has a higher cost to the default.
///</summary>
Unordered = 1,
}
class ListLineComparer : IEqualityComparer<List<Class>>
{
class LineComparer : IEqualityComparer<Class>
{
public bool Equals(Class x, Class y)
{
return x.IDLinea == y.IDLinea;
}
public int GetHashCode(Class x)
{
return x.IDLinea;
}
}
private readonly LineComparer lines;
private readonly LineComparisonMode mode;
public ListLineComparer() {}
public ListLineComparer(LineComparisonMode mode)
{
this.mode = mode;
}
public bool Equals(List<Class> x, List<Class> y)
{
if (mode == LineComparisonMode.Ordered)
return x.SequenceEqual(y, lines);
else
return x.OrderBy<Class, int>(Line).SequenceEqual(y.OrderBy<Class, int>(Line), lines);
}
private static int Line(Class c)
{
return c.IDLinea;
}
public int GetHashCode(List<Class> x)
{
//this is not a good hash (though correct)
// but not relevant to current question
return x.Sum(c => c.IDLinea);
}
}
// assume List <List<Class>> L = new List<List<Class>>(); from question
var result = L.Distinct(new ListLineComparer());
</code></pre>
<p>Result in form of IList of IList of Class rather than Lists hopefully that is acceptable. If not you will have the build the lists yourself rather than letting Linq deal with it.
If you want to have lines {1,2,3} be considered equal to {3,2,1} then you would need to set the Mode.</p>
<pre><code>var result = L.Distinct(new ListLineComparer(LineComparisonMode.Unordered));
</code></pre>
<p>This is all a little more verbose that I would have done it myself but makes it clear what is going on/what assumptions are being made so it is simple to change (if say the column position becomes involved later).</p>
|
Adding html in DataTextFormatString <p>I have a DropDownList populated from a LINQ query. As per the design requirements of this project, I need to append 4 " " to the DDL's ListItem.Text.</p>
<p>It works when I add the ListItems manually like so:</p>
<pre><code><asp:ListItem Value="NULL">&nsbp;&nsbp;&nsbp;&nsbp;Select One</asp:ListItem>
</code></pre>
<p>but not when I DataBind() and use:</p>
<pre><code>DataTextFormatString = "&nsbp;&nsbp;&nsbp;&nsbp;{0}";
</code></pre>
<p>Any help is appreciated.</p>
<p>AND: Before someone says something about the HTML code, I had to call it a "&nsbp;" since it wouldn't allow me to use Non-Breaking Space char code.</p>
<p>Thanks!</p>
| <pre><code>DropDownList ddl = new DropDownList();
ddl.Items.Add(new ListItem(Server.HtmlDecode("& n b s p;&n b s p ;& n b s p ;&n bs p;abc"), "abc"));
</code></pre>
<p>Hope this helps !</p>
<p><strong>Note :</strong> remove the spaces between characters..</p>
|
converting RELAX NG to XSD with trang while keeping external namespace elements (for use with JAXB) <p>I am using <a href="http://www.thaiopensource.com/relaxng/trang.html" rel="nofollow"><code>trang</code></a> to convert a RELAX NG .rng file to an XML Schema .xsd file for use with JAXB. Is there a way to put attributes/elements in the .rng file and have them show up in the .xsd file? I have an external .xjb file that I use for JAXB settings, but there are some JAXB settings that are very closely coupled to the schema itself and it seems like it makes more sense to (somehow) put them in the .rng file rather than the .xjb file.</p>
<p>Any advice?</p>
| <p>My opinion is that what you're doing now is the best way and you should keep your JAXB customizations separate from your RELAX NG schema. JAXB customizations in an XML Schema are ugly at best, distracting and confusing at worse. With RELAX NG, there's much less of a mapping and my guess is that you'll still need to put some of the customizations in a separate JAXB customization file, which means that your customizations will be in two different files. </p>
|
Passing arrays and matrices to functions as pointers and pointers to pointers in C <p>Given the following code:</p>
<pre><code>void
foo( int* array )
{
// ...
}
void
bar( int** matrix )
{
// ...
}
int
main( void ) {
int array[ 10 ];
int matrix[ 10 ][ 10 ];
foo( array );
bar( matrix );
return 0;
}
</code></pre>
<p>I don't understand why I get this warning:</p>
<blockquote>
<p>warning: passing argument 1 of âbarâ from incompatible pointer type</p>
</blockquote>
<p>Although 'foo' call seems to be ok.</p>
<p>Thanks :)</p>
| <p>Well, it's certainly not well understood by the C community as can be seen by glancing over SO. The magic is, <strong>all of the following are totally, 100%, equivalent</strong>:</p>
<pre><code>void foo(int (*array)[10]);
void foo(int array[][10]);
void foo(int array[10][10]);
void foo(int array[42][10]);
</code></pre>
<p>It is <em>very</em> important to draw the distinction of a pointer and an array. <em>An array is not a pointer</em>. An array can be converted to a pointer to its first element. If you have a pointer you have this:</p>
<pre><code>--------
| ptr | -------> data
--------
</code></pre>
<p>However, if you have an array, you have this:</p>
<pre><code>---------------------------
| c1 | c2 | c3 | ... | cn |
---------------------------
</code></pre>
<p>With the pointer, the data is at a whole other planet, but linked to by the pointer. An array has the data itself. Now, <strong>a multi-dimensional array is just an array of arrays.</strong> The arrays are nested into a parent array. So, the sizeof of your array is:</p>
<pre><code>(sizeof(int) * 10) * 10
</code></pre>
<p>That is because you have 10 arrays, all of which are arrays of 10 integers. Now, if you want to pass that array, it is converted. But to what? A pointer to its first element. The element type is <em>not</em> a pointer, but an array. As a consequence, you pass a pointer to an array of 10 int:</p>
<pre><code>int (*)[10] // a pointer to an int[10]
</code></pre>
<p>It is neither a array of <code>int*</code>, nor a <code>int**</code>. You may ask why the array is not passed as an <code>int**</code>. It's because the compiler has to know the row-length. If you do an <code>array[1][0]</code>, the compiler will address a place <code>sizeof(int) * 10</code> bytes apart from the begin of the 2 dimensional array. It decodes that information in the pointer-to-array type. </p>
<p>So, you have to chose among one of the above fully equivalent function prototypes. Naturally, the last one is just confusing. The compiler just silently ignores any number written in the most outer dimension if a parameter is declared to be an array. So i would also not use the second last version. Best is to use the first or second version. What is important to remember is that <strong>C has no (real) array parameters</strong>! The parameter will be a pointer in the end (pointer to array in this case).</p>
<p>Note how the multi-dimensional case of above is similar to the degenerate, one dimensional case below. All of the following 4 versions are fully equivalent:</p>
<pre><code>void foo(int *array);
void foo(int array[]);
void foo(int array[10]);
void foo(int array[42]);
</code></pre>
|
Why is a font in .NET of size 8 displayed as 8.25? <p>When you select, for example, a Size of 8 in a Font Dialog for Microsoft Sans Serif, it returns a font that .NET displays as having a size 8.25? </p>
<p>Why is this exactly?</p>
| <p>A point is 1/72 of an inch, so the font should be 8/72 (0.111111) inches high. Windows assumes a standard display is 96 DPI, unless you take pains to configure it otherwise. That means it tries to create a font that's 10.66667 pixels high; it rounds to 11 pixels. When you convert that back to points ((11 / 96) * 72), it becomes 8.25.</p>
|
Why can't you build a website in release mode? <p>In ASP.Net, if I set up a <strong>web application</strong> I can configure it to be in <strong>release mode</strong> but with a <strong>website</strong> I can only set the configuration to be in <strong>debug mode</strong>. Why is this?</p>
| <p>In web site projects each page is compiled dynamically upon first request. It will compile without debugging symbols unless you specify otherwise in the config file.</p>
|
Datasnap : Is there a way to detect connection loss globally? <p>I'm looking to detect local connection loss. Is there a mean to do that, as with the events on the Corelabs components ?</p>
<p>Thanks</p>
<p>EDIT:
Sorry, I'm going to try to be more specific:
I'm currently designing a prototype using datasnap 2009. So I've got a thin client, a stateless server app and a database server.</p>
<p>What I would be able to do is to detect and handle connection loss (internet connectivity) between the client and the server app to handle it appropriately, ie: Display an informative error message to the user or to detect a server shutdown to silently redirect on another app server.</p>
<p>In 2-tier I used to manage that with ODAC components, the TOraSession have some events to handle this issues.</p>
| <p>Normally there is no event fired when a connection is broken, unless a statement is fired against the database. This is because there is no way of knowing a connection loss unless there is some sort of is-alive pinging going on.</p>
<p>Many frameworks check if a connection is still valid by doing a very small query against the server. Could be getting the time from a server. Especially in a connection pooling environment.</p>
<p>You can implement a connection checking function in your application in some of the database events (beforeexecute?). Or make a timer that checks every 10 seconds.</p>
|
How to quickly organize functions in source code (c#) to order by alphabetical order? <p>I'm doing some class clean to organize the functions in cs file in alphabetical order. I'm using Visual Studio 2008.</p>
<p>When writing them, I just put them arbitrarily, but it now looks quite messy. </p>
<p>Is there some easy way to organize them automatically? </p>
<p>Better to have a tool because there're quite a lot files to clean up. </p>
| <p>Why bother organizing in alpha order?
The IDE provides a drop down list in order for you to use if you wish to access them in that manner.</p>
<p>Instead the source file should contain them in a meaningful order (what is meaningful is rather subjective) either by the specifics of their tasks or by some sensible convention if nothing else exists (such as by visibility, or placing properties together).</p>
<p>Auto layout rules are a nightmare for source repositories since they put in needless mass movements that frustrate your ability to identify real change, as such they should be avoided unless the rules comply with one of the following:</p>
<ul>
<li>They <strong>never</strong> change and you can apply it from the beginning of your project</li>
<li>They change very rarely and changing will affect at most a single line movement (like bracketing structure)</li>
<li>They change rarely and the effect is simply on white space within a line</li>
</ul>
<p>If the answer is at all beyond 'rarely' you don't want to use it full stop, efficient browsing of historical changes is more useful.</p>
|
Automatic feedback on JavaScript error <p>Is there a way to get an automatic feedback if an error (even syntax errors) occurs when running a JavaScript on the client side?</p>
<p>I was thinking of something like this:</p>
<pre><code><script src="debugger.js"></script>
<script>
// some script with an error in it
</script>
</code></pre>
<p>And every time the debugger notices an error it sends a feedback to the server.</p>
| <p>EDIT: I misunderstood your question initially, this should work:</p>
<p>Also note, this needs to go BEFORE any javascript that might cause errors.</p>
<pre><code>window.onerror = function(msg,u,l)
{
txt ="Error: " + msg + "\n";
txt+="URL: " + u + "\n";
txt+="Line: " + l + "\n\n";
//Insert AJAX call that passes data (txt) to server-side script
return true;
};
</code></pre>
<p>As for syntax errors, you're out of luck. Javascript simply dies when there's a syntax error. There's no way to handle it at all.</p>
|
Why would you choose a fixed-width design? <p><strong>Update:</strong>
I deleted my motivation because it seems to distract readers. This is not about "why don't you make your window smaller". See the screenshots and you will see obstructed text because of fixed width. See my reference to "em/ex" notation in CSS. I would like to have a real discussion here. Thank you.</p>
<p><hr /></p>
<p>Now I would like to ask real experts on this topic -- I'm not a web designer -- why fixed width layout are still that popular and if there are really <em>good</em> reasons for it. (you are welcome to point out reasons against it as well.)</p>
<ul>
<li><p><strong>Is it too hard</strong> to design your layout relatively (from start on)? It seems some people even <a href="http://stackoverflow.com/questions/90595/how-to-implement-a-web-page-that-scales-when-the-browser-window-is-resized">forgot how to do it</a>.</p></li>
<li><p><strong>Do you have real reasons</strong> like readability and just don't know how to deal with it correctly? Here I'm referring to pieces of wisdom, like it's harder to read longer lines (that's why newspapers use columns) -- but then, width should be given using <a href="http://htmlhelp.com/reference/css/units.html"><code>em</code> and <code>ex</code></a>.</p></li>
<li><p><strong>Are you forced</strong> by some <a href="http://stackoverflow.com/questions/456250/recommended-website-resolution-width-and-height">old guidelines</a>? In the dark old age of HTML, people did a <em>lot</em> of things wrong; now everybody finally uses CSS, but perhaps this one just sticked.</p></li>
<li><p>Or are you like me, wondering why everybody is doing it "wrong"?</p></li>
</ul>
<p>To illustrate the issue, I want to give screenshots of negative examples first:</p>
<ul>
<li><a href="http://fopref.meinungsverstaerker.de/div_priv/stackoverflow.png">StackOverflow</a> (here I can't even see what would make it <em>any</em> hard to fix it)</li>
<li><a href="http://fopref.meinungsverstaerker.de/div_priv/filmstarts.png">Filmstarts</a> (a german website which renders itself unreadable-if I don't take a reading-glass with me)</li>
</ul>
<p>And here is a positive example. It looks like a typical fixed with site (even with transparent borders), but it is not:</p>
<p><a href="http://fsi.informatik.uni-erlangen.de/dw/">Website on Wiki software</a> -- <a href="http://fsi.informatik.uni-erlangen.de/forum/">associated Forums</a></p>
<p>What do you think?</p>
<p><strong>Update:</strong> Related questions: <a href="http://stackoverflow.com/questions/27381/should-websites-expand-on-window-resize">this one</a> and <a href="http://stackoverflow.com/questions/329900/css-fixed-or-float-layout">that one</a>.</p>
| <p>And here, as expected, comes the usual canard: âlong lines are too hard to readâ.</p>
<p><strong>[Citation needed]</strong>, folks.</p>
<p>See <a href="http://webusability.com/article_line_length_12_2002.htm" rel="nofollow">http://webusability.com/article_line_length_12_2002.htm</a> for a summary of actual research in this area. A number of these, plus <a href="http://psychology.wichita.edu/surl/usabilitynews/72/LineLength.asp" rel="nofollow">http://psychology.wichita.edu/surl/usabilitynews/72/LineLength.asp</a>, find that although users express a preference for moderate line lengths, reading speeds do not sharply drop off with âlongâ lines; in fact many show increased speeds with the longer settings.</p>
<p>As long as it's not <em>ridiculously long</em>, and taking care to use a decent amount of leading, long lines are not generally a real issue at today's typical browser widths and default font sizes. (If you're one of those designers that loves to use teeny-tiny type for everything, it could be an issue, but then you're already making it impossible to read with the flyspeck text. Stop it!)</p>
<p>So as it's only an option of user preference that prefers medium-short lines, let us users decide how much screen space we want to give the web site to get our work done. We're the ones best-equipped to know. If you decide you know definitively best you're likely to waste space, or, if you guessed too long, make us scroll back and forth sideways to read the textâââand that really <em>is</em> a readability nightmare.</p>
<p>If you want to protect us from ourselves, you can compromise by specifying a min-width and max-width in âemâ units so that the page is responsive to liquid layout, but doesn't get stretched to extremes.</p>
<p>But otherwise, the best reason to design fixed-width is indeed that it is easier, especially for someone with a fixed-2D-grid view of the world and static visual-design tools like Photoshop.</p>
|
MS SQL2005 Query/Stored Proc Results To Text using SqlCommand or any other method <p>I have a simple question.</p>
<p>I need to return results as simple text, either as a string or similar. </p>
<p>i.e. I want the same behavior such as </p>
<p>Results to Text (Cntrl + T) </p>
<p>When you run a Query from SQL Server Management Studio. </p>
<p>How can this be done programmatically against calling a Stored Proc from C#?</p>
<p>i.e. similar to <code>ExecuteReader();</code> or <code>ExecuteXMLReader();</code> but returning a string instead. </p>
<p>Is there some <code>ToString()</code> available?</p>
<p>Thanks,
Kai.</p>
| <p>No, you will have to build the sting yourself by reading from dbreader.</p>
|
Searching numbers with Zend_Search_Lucene <p>So why does the first search example below return no results? And any ideas on how to modify the below code to make number searches possible would be much appreciated.</p>
<h1>Create the index</h1>
<pre><code>$index = new Zend_Search_Lucene('/myindex', true);
$doc->addField(Zend_Search_Lucene_Field::Text('ssn', '123-12-1234'));
$doc->addField(Zend_Search_Lucene_Field::Text('cats', 'Fluffy'));
$index->addDocument($doc);
$index->commit();
</code></pre>
<h1>Search - NO RESULTS</h1>
<pre><code>$index = new Zend_Search_Lucene('/myindex', true);
$results = $index->find('123-12-1234');
</code></pre>
<h1>Search - WITH RESULTS</h1>
<pre><code>$index = new Zend_Search_Lucene('/myindex', true);
$results = $index->find('Fluffy');
</code></pre>
| <p>First you need to change your text analizer to include numbers</p>
<p>Zend_Search_Lucene_Analysis_Analyzer::setDefault( new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum() );</p>
<p>Then for fields with numbers you want to use <strong>Zend_Search_Lucene_Field::Keyword</strong> instead of <strong>Zend_Search_Lucene_Field::Text</strong>
this will skip the the creation of tokens and saves the value 'as is' into the index. Then you can search by it. I don't know how it behaves with floats ( is probably not going to work for floats 3.0 is not going to match 3) but for natural numbers ( like ids ) works like a charm.</p>
|
Is the "empty base optimization" in GCC configurable? <p>Consider these types:</p>
<pre><code> struct A {};
struct B : A { int i; };
</code></pre>
<p><code>sizeof(A) > 0</code> as required by the standard.</p>
<p><code>sizeof(B)</code> should be 4 due to the empty base optimization. Yet on GCC 4.1.1 it's 5 (I'm using a pack of 1 in this area). And inconsistently - some of my files are getting it, some are not. Can't be sure what the differences are yet, we have a large prjoect.</p>
<p>On the other three compilers I'm using (by Microsoft and Freescale), I don't have this problem. The empty base optimization is optional apparently, according to <a href="http://www.cantrip.org/emptyopt.html">this article</a>.</p>
<p>Is there a compiler option or pragma to tune this in GCC 4.1.1? I can work around the issue but I would like to understand what's going on first. I Googled for a while and can't seem to find anything.</p>
| <p>This always happens. I post immediately before I figure it out. Maybe the act of posting gets me thinking in a different way..</p>
<p>So in my question the sample was a little bit over-simplified. It's actually more like this:</p>
<pre><code>struct Base {};
struct C1 : Base { int i; }
struct C2 : Base { C1 c; int i; }
</code></pre>
<p>sizeof(C1) is correctly 4 on all platforms, but sizeof(C2) is 9 instead of 8 on GCC. And... apparently GCC is the only thing that gets it right, according to the last bit of the article I linked to in the original question. I'll quote it (from Nathan Meyers) here:</p>
<blockquote>
<p>A whole family of related "empty subobject" optimizations are possible, subject to the ABI specifications a compiler must observe. (Jason Merrill pointed some of these out to me, years back.) For example, consider three struct members of (empty) types A, B, and C, and a fourth non-empty. They may, conformingly, all occupy the same address, as long as they don't have any bases in common with one another or with the containing class. <em>A common gotcha in practice is to have the first (or only) member of a class derived from the same empty base as the class. The compiler has to insert padding so that they two subobjects have different addresses.</em> This actually occurs in iterator adapters that have an interator member, both derived from std::iterator. An incautiously-implemented standard std::reverse_iterator might exhibit this problem.</p>
</blockquote>
<p>So, the inconsistency I was seeing was only in cases where I had the above pattern. Every other place I was deriving from an empty struct was ok.</p>
<p>Easy enough to work around. Thanks all for the comments and answers.</p>
|
Java library inspector? <p>I am currently working on a mantenance project that is written in Java. We are currently working to clean up the code some and try to provide a little more organization to the project overall.</p>
<p>The list of libraries that are included in the build have grown long, and honestly no one remains that knows/remembers what each library is used for or why? So I am looking for a tool that would be able to essentially find where the library is used in the code. Essentially like a find usage function in an IDE has for functions. </p>
<p>Does such a tool exist? I am curently using Netbeans and as mentioned our code is in java.</p>
<p>I know I could remove each library and compile the project for each library to find the usages, but it just seems there should be a better way. Any ideas?</p>
| <p>Since you're using NetBeans, I suggest the <a href="https://sqe.dev.java.net/" rel="nofollow">SQE</a> plugin, which includes <a href="http://depfind.sourceforge.net/" rel="nofollow">Dependency Finder</a>. (And if you weren't already using FindBugs, this is a good time to start.)</p>
|
C# string won't concatenate <pre><code>// Reads NetworkStream into a byte buffer.
NetworkStream ns;
System.Net.Sockets.TcpClient client = new TcpClient();
byte[] receiveBytes = new byte[client.ReceiveBufferSize];
ns.Read(receiveBytes, 0, (int)client.ReceiveBufferSize);
String returndata = Encoding.UTF8.GetString(receiveBytes);
</code></pre>
<p>I am successfully reading from a client and storing the result into a string called returndata. However, when I try to concatenate returndata with anything, no concatenation occurs. Ex: String.Concat(returndata, "test") returns returndata, as does returndata + "test".</p>
<p>Does anyone know why this is happening?</p>
<p>Edit: Steve W is correct; i found out later that returndata.Length was always returning 8192.</p>
| <p>Are you assigning it to a string or back to itself?</p>
<pre><code>returndata = string.Concat(returndata, "test");
returndata += "test";
</code></pre>
|
Send Info from Script to Module Python <p>Hi I wonder how you can send info over to a module </p>
<p>An Example
main.py Looks like this</p>
<pre><code>from module import *
print helloworld()
</code></pre>
<p>module.py looks like this</p>
<pre><code>def helloworld():
print "Hello world!"
</code></pre>
<p>Anyway i want to send over info from main.py to module.py is it possible?</p>
| <p>It is not clear what you mean by "send info", but if you but the typical way of passing a value would be with a function parameter.</p>
<p>main.py:</p>
<pre><code>helloworld("Hello world!")
</code></pre>
<p>module.py</p>
<pre><code>def helloworld(message):
print message
</code></pre>
<p>Is that what your looking for? Also the two uses of <code>print</code> in your example are redundant.</p>
<p>Addendum: It might be useful for you to read the <a href="http://docs.python.org/tutorial/controlflow.html#defining-functions" rel="nofollow">Python documentation regarding function declarations</a>, or, alternatively, most Python introductory tutorials would cover the same ground in fewer words. Anything you read there is going to apply equally regardless of whether the function is in the same module or another module.</p>
|
javascript in html spacing <pre><code><SCRIPT LANGUAGE="JavaScript">
DynamicImage1(xx) DynamicImage2(yy) DynamicImage3(zz)
</SCRIPT>
</code></pre>
<p>This snippet of JS is in my HTML sheet.
(Each function will display a different value based on the input parameter.)</p>
<p>How do I set the spacing between these images? I would like them all on the same row (as they are by default) but with the spacing between.</p>
<p>I am thinking about to put it in a table, but I am not sure if that is the best way</p>
| <p>The cleaner approach is going to be to separate them:</p>
<pre><code><div id="image1">
<SCRIPT LANGUAGE="JavaScript">
DynamicImage1(xx)
</SCRIPT>
</div>
<div id="image2">
<SCRIPT LANGUAGE="JavaScript">
DynamicImage2(xx)
</SCRIPT>
</div>
<div id="image3">
<SCRIPT LANGUAGE="JavaScript">
DynamicImage3(xx)
</SCRIPT>
</div>
</code></pre>
<p>Then style them using CSS; use <code>float:left</code> to put them in a row and add <code>padding:right</code> to space them out.</p>
<p>I said this was the clean way; the less-clean way is to keep what you have but add <code>document.write("&nbsp;")</code> in between each image.</p>
|
Long query prevents inserts <p>I have a query that runs each night on a table with a bunch of records (200,000+). This application simply iterates over the results (using a DbDataReader in a C# app if that's relevant) and processes each one. The processing is done outside of the database altogether. During the time that the application is iterating over the results I am unable to insert any records into the table that I am querying for. The insert statements just hang and eventually timeout. The inserts are done in completely separate applications.</p>
<p>Does SQL Server lock the table down while a query is being done? This seems like an overly aggressive locking policy. I could understand how there could be a conflict between the query and newly inserted records, but I would be perfectly ok if records inserted after the query started were simply not included in the results.</p>
<p>Any ways to avoid this?</p>
<p>Update:<br />
The WITH (NOLOCK) definitely did the trick. As some of you pointed out, this isn't the cleanest approach. I can't really query everything into memory given the amount of records and some of the columns in this table are binary (some records are actually about 1MB of total data).</p>
<p>The other suggestion, was to query for batches of records at a time. This isn't a bad idea either, but it does bring up a new issue: database independent queries. Right now the application can work with a variety of different databases (Oracle, MySQL, Access, etc). Each database has their own way of limiting the rows returned in a query. But maybe this is better saved for another question?</p>
<p>Back on topic, the "WITH (NOLOCK)" clause is certainly SQL Server specific, is there any way to keep this out of my query (and thus preventing it from working with other databases)? Maybe I could somehow specify a parameter on the DbCommand object? Or can I specify the locking policy at the database level? That is, change some properties in SQL Server itself that will prevent the table from locking like this by default?</p>
| <p>It depends what Isolation Level you are using. You might try doing your selects using the With (NoLock) hint, that will prevent the read locks, but will also mean the data being read might change before the selecting transaction completes. </p>
|
Why is Syntactic Sugar sometimes considered a bad thing? <p>Syntactic sugar, IMHO, generally makes programs much more readable and easier to understand than coding from a very minimalistic set of primitives. I don't really see a downside to good, well thought out syntactic sugar. Why do some people basically think that syntactic sugar is at best superfluous and at worst something to be avoided?</p>
<p>Edit: I didn't want to name names, but since people asked, it seems like most C++ and Java programmers, for example, frankly don't care about their language's utter lack of syntactic sugar. In a lot of cases, it's not necessarily that they just like other parts of the language enough to make the lack of sugar worth the tradeoff, it's that they really <strong>don't care</strong>. Also, Lisp programmers seem almost proud of their language's strange notation (I won't call it syntax because it technically isn't), though in this case, it's more understandable because it allows Lisp's metaprogramming facilities to be as powerful as they are.</p>
| <p><em>Syntactic sugar causes cancer of the semicolon.</em> Alan Perlis</p>
<p>It is difficult to reason about syntactic sugar if the reasoning takes place without reference to a context. There are lots of examples about why "syntactic sugar" is good or bad, and all of them are meaningless without context. </p>
<p>You mention that syntactic sugar is good when it makes programs readable and easier to understand... and I can counter that saying that sometimes, syntactic sugar can affect the formal structure of a language, especially when syntactic sugar is a late addendum during the design of a programming language. </p>
<p>Instead of thinking in terms of syntactic sugar, I like to think in terms of well-designed languages that foster readability and ease of understanding, and bad-designed languages.</p>
<p>Regards,</p>
|
SQL Data Services database design guidelines <p>I've been playing around lately with SQL Data Services. Although (or perhaps because) I can knock out a well-structured relational database in my sleep, I'm struggling to get my head round how to design a performant database in an environment that has (for example) no enforcement of referential integrity and no indexes on columns other than the primary key.</p>
<p>Does anyone know of any guidelines?</p>
<p>Maybe a place to start would be how to create a many-to-many join that can be traversed from either side in a performant manner, even with vast numbers of <strike>rows</strike> entities?</p>
| <p>It seems the phrases that are being used are:</p>
<ul>
<li><p>Spread your data out amongst many containers for best performance</p></li>
<li><p>Modeling your data via Entities </p></li>
<li><p>Process your queries in parallel for best performance</p></li>
<li><p>Caching data in the service hosted middle tier</p></li>
</ul>
<p>This would imply that we have to start thinking like OO modellers rather than in a relational mind-set. Performance seems to rely on the ability to massively parallelise an object query in a smiliar way to creating a LINQ query that can take advantage of parallelisation.</p>
|
Modern day, unicode-friendly ".ini file" to store config data in VB6 <p>I'd like to store the contents of a data structure, a few arrays, and a dozen or so variables in a file that can be saved and reloaded by my software as well as optionally edited in a text editor by a user reloaded. For the text editing, I need the data to be clearly labeled, like in a good ole .ini file:</p>
<p>AbsMaxVoltage = 17.5</p>
<p>There's a GUI, and one could argue that the user should just load and save and modify from the GUI, but the customer wants to be able to read and modify the data as text.</p>
<p>It's easy enough to write code to save it and reload it (assuming all the labels are in the same place and only the data has changed). With more work (or using some of the INI R/W code that's already out there I could pay attention to the label so if a line gets deleted or moved around the variables still get stuffed correctly, but both of these approaches seem pretty old-school. So I'm interested in how the brightest minds in programming would approach this today (using decade-old VB6 which I have to admit I still love).</p>
<p>Disclaimer: I'm an electrical engineer, not a programmer. This isn't my day job. Well maybe it's a few % of my day job.</p>
<p>Cheers!</p>
| <p>Consider using <a href="http://en.wikipedia.org/wiki/XML" rel="nofollow">XML</a>. It's completely standard, many text editors will highlight/manage it properly, every programming language and script language on Earth has good support for reading it, and it handles Unicode perfectly.</p>
<p>For simple name/value pairs as you suggest, it's quite readable. But you have the added advantage that if someday you need something more complex -- e.g. multi-lined values or a list of distinct values -- XML provides natural, easy ways of representing that.</p>
<p>P.S. <a href="http://www.nonhostile.com/howto-xml-vb6.asp" rel="nofollow">Here's how to read XML in VB6</a>.</p>
|
Adding a child node to XML in flex <p>In a Flex application, I'm have an xml object that I'm binding to a tree control. I'm able to add a child node to the xml but when I try to add a child to the child node it doesn't appear on the tree control</p>
<pre><code>tree = <node label="Root">
<node label="Category 1"/>
<node label="Category2"/>
<node label="Category3"/>
<node label="Category 4">
<node label="SubCategory4.1"/>
<node label="SubCategory4.2"/>
</node>
</node>;
var someNode:XMLNode = new XMLNode(9, 'Category5');
var aSubNode:XMLNode = new XMLNode(9, 'SubCategory5.1');
someNode.appendChild(aSubNode);
tree.appendChild(someNode);
</code></pre>
<p>So Category5 appears on the tree control but SubCategory5.1 does not. What am I missing?</p>
| <p>If you are using flex, use AS3. XMLNode is AS2. In short, try this:</p>
<pre><code>tree = <node label="Root">
<node label="Category 1"/>
<node label="Category2"/>
<node label="Category3"/>
<node label="Category 4">
<node label="SubCategory4.1"/>
<node label="SubCategory4.2"/>
</node>
</node>;
var someNode:XML = <node label="Category5"/>;
var aSubNode:XML = <node label="SubCategory5.1"/>;
someNode.appendChild(aSubNode);
tree.appendChild(someNode);
</code></pre>
|
Getting a SSL connection to work with STUNNEL/Win32 <p>The service I need to connect to has provided me three files and I'm trying to figure out what I need to create the Cert=xxx.PEM file that STUNNEL needs</p>
<p>I have a "keystore.jks" file. Dumping that with keytool says it's a "Private key entry"</p>
<p>I have a "truststore.jks" file. Dumping that says it's a "trusted certificate entry". The alias is "server"</p>
<p>I also have a "xyz.cer" file. That seems to be a X.509 certificate</p>
<p>I've got OPENSSL and a Java program called "KeytoolUI". </p>
<p>Bottom line is I have a bunch of files and tools and with not much knowledge of SSL I feel like I can't see the wood for the trees. Do I need all those files? The existing PEM files I have for other services just have a "Certificate" section and a "RSA Private key" section.</p>
<p>Any advice appreciated. Thanks!</p>
| <p>It sounds like your provider has provided your keypair (for client side authentication) as a java keystore, and (I'm guessing) the remote server's public certificate or CA certificate in PEM format. </p>
<p>That's some fairly heavy guesswork, but it's strange that they've sent you a private key if you aren't doing client side auth. (Let's hope they haven't sent you the private key for their server!).</p>
<p>As far as I'm aware, stunnel only uses PEM certificates, so you will need to convert your JKS files into two PEM files (one for the private key, one for the public certificate). One way to do this is to convert the JKS to a PKCS#12 (aka PFX) file using <code>keytool</code>, and then use OpenSSL to convert the PKCS#12 files into PEM private key/certificate files. </p>
<p>Once you have these two files, use them with the <code>key</code> and <code>cert</code> options in <code>stunnel.conf</code>.</p>
<p>For the final (mystery) PEM certificate that you have, I'm going to guess (again) that this is the remote CA, and therefore that you should configure this against the <code>CAfile</code> parameter in <code>stunnel.conf</code>. (If it's appropriate for you to post details here, edit to include output from <code>openssl x509 -in <filename> -text</code> to provide more clues).</p>
|
Rails nested resources <p>Here's the routes.rb: </p>
<pre><code>map.resources :assignments, :shallow => true do |assignment|
assignment.resources :problems
end
</code></pre>
<p>How do i get the url to edit a problem (/assignments/xyz/problems/abc/edit), in code? I have tried both<br />
edit_assignment_problem_path(assignment,problem)<br />
and edit_problem_path(problem).<br />
While the first one works on my local setup, on server it says that method edit_assignment_problem_path is not defined. Any ideas?</p>
| <p>Run this at your command line:</p>
<pre><code>rake routes
</code></pre>
<p>It will tell you all the routes that you have defined, and how they map. Very handy.</p>
|
Is there any value in creating a pool of Dom4J SaxReader objects? <p>I'm using Dom4J 1.4.2.</p>
<p>Right now my code creates a new SaxReader every time I want to parse a new XML document:</p>
<pre><code>SAXReader reader = new SAXReader( );
</code></pre>
<p><strong>Is there any value in creating a pool of SaxReader objects and just reusing them? How much overhead is involved in creating a new SaxReader on every call?</strong> </p>
<p>My code could get one from the pool, parse the document then return it to the pool for another thread to use. </p>
| <p>As with all so-called performance issues and urges to pool objects: are you experiencing an actual problem, or are you trying to prematurely optimize here? Rolling your own pooling in Java has been <a href="http://www.ibm.com/developerworks/java/library/j-jtp09275.html?ca=dgr-jw22JavaUrbanLegends" rel="nofollow">out of fashion</a> since at least 2005.</p>
<p>I peeked at the source code of <a href="http://www.dom4j.org/dom4j-1.4/apidocs/org/dom4j/io/SAXReader.html#SAXReader()" rel="nofollow">SAXReader</a>, and this is the constructor:</p>
<pre><code> 138 public SAXReader() {
139 }
</code></pre>
<p>There are no instance initializers, and the real work is done in the <code>read</code> method.</p>
|
Replacing escape characters in Powershell <p>I have a string that consists of </p>
<pre><code>"some text \\computername.example.com\admin$".
</code></pre>
<p>How would I do a replace so my final result would be just "computername"</p>
<p>My problems appears to not knowing how to escape two backslashes. To keep things simple I would prefer not to use regexp :)</p>
<p>EDIT: Actually looks like stackoverflow is having problems with the double backslash as well, it should be a double backslash, not the single shown</p>
| <p>I don't think you're going to get away from regular expressions in this case.</p>
<p>I would use this pattern:</p>
<pre><code>'Some text \\computername\admin$' -replace '\\\\(\w+)\\(\w+)\$', '$1'
</code></pre>
<p>which gives you </p>
<pre><code>PS C:\> 'Some text \\computername\admin$' -replace '\\\\(\w+)\\(\w+)\$', '$1'
Some text computername
</code></pre>
<p>or if you wanted only the computername from the line:</p>
<pre><code>'Some text \\computername\admin$' -replace '.*\\\\(\w+)\\(\w+)\$', '$1'
</code></pre>
<p>which returns</p>
<pre><code>PS C:\> 'Some text \\computername\admin$' -replace '.*\\\\(\w+)\\(\w+)\$', '$1'
computername
</code></pre>
|
Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL) <p>What are the real world pros and cons of executing a dynamic SQL command in a stored procedure in SQL Server using</p>
<pre><code>EXEC (@SQL)
</code></pre>
<p>versus</p>
<pre><code>EXEC SP_EXECUTESQL @SQL
</code></pre>
<p>?</p>
| <p><code>sp_executesql</code> is more likely to promote query plan reuse. When using <code>sp_executesql</code>, parameters are explicitly identified in the calling signature. This excellent article descibes this <a href="http://technet.microsoft.com/en-au/library/cc966425.aspx">process</a>.</p>
<p>The oft cited reference for many aspects of dynamic sql is Erland Sommarskog's must read: "<a href="http://www.sommarskog.se/dynamic_sql.html">The Curse and Blessings of Dynamic SQL</a>".</p>
|
Java : ignore single click on double click? <p>can anyone think of a good way to ignore the single click that comes with a double-click in Java ? </p>
<p>I'm looking to have different behaviors for each such that:</p>
<ul>
<li>single-click paints crosshairs on the click point</li>
<li>double-click selects an object on the screen, but should <strong>not</strong> paint crosshairs on the click point</li>
</ul>
<p>... can anyone think of a way to do this ? Some sort of timer set-up maybe ? An ideas appreciated :-)</p>
<p><disclaimer> ...and yes, I know I'm committing a most heinous usability / UI faux pas. </disclaimer></p>
<p><strong>EDIT #2:</strong> </p>
<p>Even though this works the delay due to the timer is maddening - I'm abandoning this solution, and using middle-click for selection instead of double-click...</p>
<p><strong>EDIT:</strong></p>
<p>Thanks <a href="http://stackoverflow.com/users/23325/cgull">cgull</a> - this is what I was able to come up with given your confirmation that there's no easy way to do this (note that if I set the timer < 200 odd racing is seen between the click & the timer, but as long as I set this to a value > 200 things work just peachy) :</p>
<pre><code>public void mouseClicked(MouseEvent e) {
System.out.println( "Click at (" + e.getX() + ":" + e.getY() + ")" );
if (e.getClickCount() == 2) {
System.out.println( " and it's a double click!");
wasDoubleClick = true;
}else{
Integer timerinterval = (Integer)
Toolkit.getDefaultToolkit().getDesktopProperty(
"awt.multiClickInterval");
timer = new Timer(timerinterval.intValue(), new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (wasDoubleClick) {
wasDoubleClick = false; // reset flag
} else {
System.out.println( " and it's a simple click!");
}
}
});
timer.setRepeats(false);
timer.start();
}
}
</code></pre>
| <p>Indeed you'll need to set up a Timer in your overridden mouseClicked() method of your MouseAdapter to detect the time interval between the two clicks. The default interval in ms can be found by querying
<code>Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval")</code>. If another mouse click is detected before the timer expires, then you have a double-click, else once the timer expires, you can process the single-click.</p>
|
Getting the font size of a Menu Item in the Win32 API? <p>Is it possible to retrieve the size of the font used in a menu via the Win32 API? I have found the <code>GetTextMetrics()</code> call, but cannot find a way to specify it getting the font used in a menu. Any suggestions?</p>
| <p>It looks like you can use this call</p>
<pre><code>SystemParametersInfo(SPI_GETNONCLIENTMETRICS)
</code></pre>
<p>to get various system parameters. The resulting structure contains a <a href="http://msdn.microsoft.com/en-us/library/ms901140.aspx" rel="nofollow">LOGFONT</a> item for the menu font and you should be able to determine the fontsize from that.</p>
|
How to break CAPTCHA? <p>What are the methods, algorithms used to break CAPTCHA ?</p>
| <p>The Security Now Podcast has an episode about this. Link to transcript follows.</p>
<p><a href="http://www.grc.com/sn/sn-101.txt" rel="nofollow">http://www.grc.com/sn/sn-101.txt</a></p>
<p>Update, better links:</p>
<p><a href="http://www.grc.com/sn/notes-101.htm" rel="nofollow">http://www.grc.com/sn/notes-101.htm</a>
<a href="http://www.grc.com/sn/sn-101.htm" rel="nofollow">http://www.grc.com/sn/sn-101.htm</a></p>
|
best way to generate mass insert statement in c#? <p>I am needing to insert a bunch of similar records into a table, and was wondering if there was a nice/easy way to do this. </p>
<p>I know it would be easy to just build a big string, but I was hoping I could find a more graceful way to do this.</p>
| <p>The <code>SqlBulkCopy</code> class has <code>WriteToServer</code> methods which write multiple records.</p>
<p>I created a class which implemented the <code>IDataReader</code> interface, which I can pass as a parameter to a <code>SqlBulkCopy.WriteToServer</code> method (see <a href="http://msdn.microsoft.com/en-us/magazine/cc301611.aspx" rel="nofollow">ADO.NET: Building a Custom Data Provider for Use with the .NET Data Access Framework</a> for an example of how to implement the <code>IDataReader</code> interface).</p>
<p>There might be a simpler way than implementing <code>IDataReader</code> (i.e. by using one of the other <code>SqlBulkCopy.WriteToServer</code> methods).</p>
|
How to generate Winamp-Style visualization effects with openGL? (Milkdrop, etc) <p>I'm trying to create an animated ambient abstract background for my game. I'm picturing something very similar to what Winamp has when you turn on it's visualization plug-in. Here's a link to some <a href="http://www.nullsoft.com/free/milkdrop/screenshots.html" rel="nofollow">screenshots</a>. </p>
<p>I can handle tweaking the idea once I get something up and running that is acting generally how I want it, but I just have no idea how to go about getting anything similar to these effects. </p>
<p>I'm working with OpenGL via LWJGL. </p>
<p>I've tried looking through the milkdrop source, but I can't seem to find the place where it does the magic. </p>
| <p>You might also want to check out <a href="http://projectm.sourceforge.net/" rel="nofollow">ProjectM</a>, it's an open source reimplementation of Milkdrop in OpenGL.</p>
|
TSQL to LINQ conversion reference? <p>I'm trying to find a good reference to help me convert this TSQL statement to Linq:</p>
<p>EXAMPLE:</p>
<pre><code>SELECT * FROM Categories WHERE ProductID IN (SELECT ProductID FROM ProductCategories WHERE CatID = 23)
</code></pre>
<p>I can't find anywhere that references how to do the WHERE "IN" part.</p>
| <p>While it's not <em>exactly</em> a TSQL to LINQ reference, I have found the <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx" rel="nofollow">101 LINQ Samples</a> page on MSDN helpful for this purpose.</p>
<p>See also <a href="http://stackoverflow.com/questions/51339/how-can-you-handle-an-in-sub-query-with-linq-to-sql">this related question</a></p>
|
How can I make changes to only the first line of a file? <p>I would like to know which pattern can I use in sed to make changes in the first line of huge files (~2 GB). The preference for sed is only because I assume it must be faster than a Python or Perl script.</p>
<p>The files have the following structure:</p>
<pre><code>field 1, field 2, ... field n
data
</code></pre>
<p>and, given the likelihood of having spaces in the identifier for every field, I need to replace every space by an underscore in this way:</p>
<pre><code>**BEFORE**
the first name,the second name,the first surname,a nickname, ...
data
**AFTER**
the_first_name,the_second_name,the_first_surname,a_nickname, ...
data
</code></pre>
<p>Any pointers to the right pattern to use, or another scripting solution would be great.</p>
| <p>To edit the first 10 lines</p>
<pre><code>sed -i -e '1,10s/ /_/g'
</code></pre>
<p>In Perl, you can use the flip-flop operator in scalar context:</p>
<pre><code>perl -i -pe 's/ /_/g if 1 .. 10'
</code></pre>
|
How can I configure Mercurial to use WinMerge for merges, under cygwin? <p>When Mercurial is running under cygwin, it's a bit tricky to figure out how to spawn <a href="http://winmerge.org/">WinMerge</a> to resolve merge conflicts. How can I do this?</p>
| <p>The trick is that cygwin paths are not the same as Windows paths, so you need a little script that converts the cygwin paths to Windows paths before passing them as arguments to WinMerge.</p>
<p>Here's how to do it:</p>
<p>(1) Create a shell script in <code>/usr/bin/winmerge</code> as follows:</p>
<pre><code>#!/bin/sh
"/cygdrive/c/Program Files/WinMerge/WinMergeU.EXE" /e /ub /dl other /dr local `cygpath -aw $1` `cygpath -aw $2` `cygpath -aw $3`
</code></pre>
<p>Note: <code>cygpath</code> converts path names. If WinMerge isn't in the default location, change the path here.</p>
<p>(2) Make that file executable</p>
<pre><code> chmod +x /usr/bin/winmerge
</code></pre>
<p>(3) Add the following to your <code>~/.hgrc</code> file:</p>
<pre><code>[ui]
merge = winmerge
[merge-tools]
winmergeu.executable=/usr/bin/winmerge
winmergeu.args=$other $local $output
winmergeu.fixeol=True
winmergeu.checkchanged=True
winmergeu.gui=False
</code></pre>
<p>Note! You probably already have a [ui] section with your name in it. Remember to merge my changes with yours, don't just add a new [ui] section. For example, my .hgrc looks like this:</p>
<pre><code>[ui]
username = Joel Spolsky <spolsky@example.com>
merge = winmergeu
[extensions]
fetch =
[merge-tools]
winmergeu.executable=/usr/bin/winmerge
winmergeu.args=$other $local $output
winmergeu.fixeol=True
winmergeu.checkchanged=True
winmergeu.gui=False
</code></pre>
|
jQuery and Auto-populat selects <p>I have a simple page where I can select a client, then once I chose that autopopulate to the projects that belong to the client. I am using PHP/MySQL to pull the results.</p>
<p>I took at a look at this: <a href="http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/" rel="nofollow">http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/</a> but I think that starts with both fields on the page. I tried to rework the code but didn't come out that well. </p>
<pre><code> var client_id = $('#c_id').val();
$.getJSON("../inc/get-projects.php", {id: client_id}, function(data){
projects = $('#p_id');
projects.empty();
$.each(data, function() {
var option = $('<option/>').attr('value', this.id).text(this.name);
projects.append(option);
});
});
</code></pre>
<p>PHP:</p>
<pre><code><?php
include "config.inc.php";
$sth = mysql_query(
sprintf(
"SELECT c_id,p_id,p_title FROM projects WHERE c_id = %s",
mysql_real_escape_string($_GET['id'])
)
);
$projects = array();
while($r = mysql_fetch_assoc($sth)) {
$projects[] = array('id' => $r['p_id'], 'name' => $r['p_title']);
}
print json_encode($projects);
exit;
?>
</code></pre>
| <p>If you have HTML like this:</p>
<pre><code><select id='clients'>...</select>
<select id='projects'>...</select>
</code></pre>
<p>You can have jQuery code like this:</p>
<pre><code>$(document).ready(function() {
var $clients = $('#clients');
$clients.change(function() {
var client_id = $clients.val();
$.getJSON("getProjects.php", {id: client_id}, function(projects) {
$projects = $('#projects');
$projects.empty();
$.each(projects, function() {
var option = $('<option/>').attr('value', this.id).text(this.name);
$projects.append(option);
});
});
});
});
</code></pre>
<p>And then have getProjects.php return something like:</p>
<pre><code>$sth = mysql_query(
sprintf(
"SELECT * FROM projects WHERE client_id = %s",
mysql_real_escape_string($_GET['id'])
)
);
$projects = array();
while($r = mysql_fetch_assoc($sth)) {
$projects[] = array('id' => $r['id'], 'name' => $r['name']);
}
print json_encode($projects);
exit;
</code></pre>
<p>I haven't tested all of this, but it is more or less what you want, I think.</p>
<p><strong>edit</strong> - Tested and works, obviously it might not be exactly what you need but it gives you an idea of how to go about it. Hope it helps.</p>
<p><strong>edit 2</strong> - The problem with your code is here:</p>
<pre><code>$.getJSON("../inc/get-projects.php", {id: client_id}, function(projects){
projects = $('#p_id');
projects.empty();
$.each(projects, function() {
var option = $('<option/>').attr('value', this.id).text(this.name);
projects.append(option);
});
});
</code></pre>
<p>You are overwriting the <code>projects</code> passed into the function with the <code>projects</code> in the 2nd line. I used a <code>$</code> in my code to differentiate the two, which was admittedly perhaps not the best of ways. To fix, change the code to this:</p>
<pre><code>$.getJSON("../inc/get-projects.php", {id: client_id}, function(data){
projects = $('#p_id');
projects.empty();
$.each(data, function() {
var option = $('<option/>').attr('value', this.id).text(this.name);
projects.append(option);
});
});
</code></pre>
|
How To Pass Soap Header When WSDL Doesn't Define It? <p>I have a web service that I am calling and their published WSDL doesn't actually define much of the service, 3/4 of it you have to manually build afterwards.</p>
<p>The problem I have is that they need a SoapHeader with some specific information in it, but I don't have any way of doing it. The only real things I have for the service is a proxy method that was created (MyMethod) that I can pass my message to. How can I set/send a soap header with it as well? </p>
<p>All of the services I've had, I have been able to use the automatically bound items from Visual Studio.</p>
| <p>I was able to get this done by modifying the auto-generated proxy code manually and simply injecting a class that inherited "SoapHeader" and added the attribute to the method!</p>
<p>I cannot re-generate or re-fresh the proxy, but it got the job done, and only took 15 minutes.</p>
|
UIApplication launching the phone app and returning user to the wrong screen <p>My iPhone app initiates a phone call with:</p>
<pre><code>NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", @"11111111"]];
[[UIApplication sharedApplication] openURL:phoneURL];
</code></pre>
<p>This is from a <code>UIView</code> inside a <code>UINavigationController</code>. It is not the root <code>UIView</code> however.</p>
<p>When the phone app is finished with the call and returns control to my app, the screen that the user is returned to is not the screen that the user left. It is the root screen of the <code>UINavigationController</code>.</p>
<p>How do I get <code>[UIApplication sharedApplication]</code> to return control at the screen that the user left?</p>
| <p>You don't.</p>
<p>If you insert appropriate debugging code, I think you'll find that your app actually closes when the call is placed and reopens when the call ends. This is by design; resources are limited in mid-call, and Apple doesn't want to have to decide between dropping the call and killing your app. So what you need to do is save the application's state before exiting (either as you go or in applicationWillTerminate:) and then restore it in applicationDidFinishLaunching:. Fortunately, you need to do this anyway--iPhone apps should <em>always</em> restore to their previous state when you relaunch them--so this isn't really extra work.</p>
|
Which free database with replication support? <p>I need to have 2 or 3 synchronized sql database instances at different locations. Which of FREE databases can do that?</p>
| <p>mysql can do it and also postgresql</p>
<ul>
<li><a href="http://www.mysql.com" rel="nofollow">www.mysql.com</a></li>
<li><a href="http://www.postgresql.org" rel="nofollow">www.postgresql.org</a></li>
</ul>
<p>I only have experience with mysql, for more info, just look into the documentation:</p>
<ul>
<li><a href="http://dev.mysql.com/doc/refman/5.0/en/replication.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.0/en/replication.html</a></li>
</ul>
<p>It can help you set up the base cluster and replication.</p>
|
Static Actionscript code analysis? <p>I want to see class, function and variable/property, dependencies visually, like <a href="http://www.ndepend.com/Screenshots.aspx">NDepend</a>, but for ActionScript 2 or AS3 code.</p>
<p>Any programs or ideas?</p>
<p>Use <a href="http://www.stack.nl/~dimitri/doxygen/">Doxygen</a> in some way?</p>
<p><a href="http://stackoverflow.com/questions/219549/automated-testing-non-ui-for-existing-flash-component">FlexUnit?</a></p>
| <p>Download <a href="http://www.headwaysoftware.com/downloads/structure101/g.php">Structure101g</a> and select the Actionscript flavor after installing the software. </p>
<p>I've confirmed that it is able to map out class level and even function call dependencies in Flex/AS3 projects, and generate a visual map of the same. </p>
<p>Take a look at the attached screenshot.</p>
<p><img src="http://i40.tinypic.com/e8qptu.png" alt="alt text"></p>
<p>Hope that helps.</p>
|
excel: charting with unknown number of data <p>Let's (for discussion purposes) say that I have x and y data in 2 columns. They're some measured data which, several times a day, a few of them are added (usually 4 times a day).
Now, I wish to plot y=f(x) (linear scale), but the problem is since data is constantly added to determine the number of points which will go in the plot. Always creating a new plot and then formatting it and all, is troublesome for ... reasons.</p>
<p>Is there a way to do this using excel's build in functions ? Should I use vba ? I tried googling, but I don't know what to search for. I'd appreciate any help on this, even if its just a point in the right direction.</p>
<p>Is there a way to tell excel, use all points in this column until you hit an empty cell ?</p>
| <p>You can do this without any VBA. Jon Peltier has an example by Debra Dalgleish on his website:</p>
<p><a href="http://peltiertech.com/Excel/Charts/DynamicColumnChart1.html" rel="nofollow">http://peltiertech.com/Excel/Charts/DynamicColumnChart1.html</a></p>
<p>It can be pretty frustrating to Google anything related to Excel because there is so much junk out there, but I've found that if there's something "obvious" that you know shouldn't be so hard, one of the various "MVP" sites will have covered it.</p>
|
Recommendations for AJAH Library <p>I have a classic ASP application</p>
<p>I would like to add some AJAX-style partial page updates to avoid server roundtrip. For example, list of rows displayed, option to add another in-situ, save it, and table redisplayed / add another.</p>
<p>I don't think I need all the other baggage of the well known AJAX libraries</p>
<p>I would appreciate suggestions for AJAH libraries, and also opinions on whether you think I am daft only adopting AJAH rather than full blown AJAX.</p>
<p>(My application has a template rendering function, so I can already convert database data into "rich HTML", so I perceive that my easiest route is to reuse this and send replacement HTML, using AJAH, to be injected into the page using innerHTML replace)</p>
<p>Thanks</p>
| <p>AJAH? There is to my knowledge no such thing as AJAH. Does the H stand for HTML instead of XML? If so, let me disabuse you of the notion that AJAX entails XML. That may have been its inception but that is not the case (now at least). In the moern vernacular Ajax has come to mean pages making Javascript calls back to the server without refreshing the page. Data can be sent to the server and the data returned can be JSON, XML, HTML or whatever you like really. JSON and HTML are probably the most common (with XML next).</p>
<p>As for what API to use. It sounds like you want to spruce up an existing application and (imho) there is no better library for this than jQuery. Its as lightweight as you want with plugins for almost everything and helps you a lot with cross-browser issues. You can easily do things like:</p>
<pre><code><input id="refresh" type="button" value="Refresh">
...
$("#refresh").click(function() {
$.ajax({
url: '/getusers',
type: "GET",
timeout: 5000,
dataType: "html",
failure: function() {
alert("An error occurred.");
},
success: function(data) {
$("#userlist").html(data);
}
});
});
</code></pre>
|
mysql keyword search <p>I have a table with names of movies, and I want to be able to search for a movie in that table. But I want to be able to search for part of the title, and still return a result. For example, if there is a record with the name "The quantum of solace", then I want to be able to do a search for "quantum solace", or even "007: quantum solace" and I want to find that record. Is there a way to do this?</p>
<p><strong>EDIT</strong>
And how do I sort according to the matches? That is, the row that matches the most, should be returned first.</p>
| <p>Use a <a href="http://dev.mysql.com/doc/refman/5.1/en/fulltext-boolean.html" rel="nofollow">MySQL Full Text Search</a> in boolean mode.
If you do this when you search for '007: quantum solace' as it contains at least one matching result in the column it will be displayed, you can then order by relevancy.</p>
<pre><code>SELECT *, MATCH(title) AGAINST ('quantum solace' IN BOOLEAN MODE) AS rank
FROM films
WHERE MATCH(title) AGAINST ('quantum solace' IN BOOLEAN MODE) ORDER BY rank DESC
</code></pre>
|
Visually edit C# imagemap control? <p>I just discovered the imagemap control in Visual Studio 2008.
I'm familiar with the imagemap concept from HTML, I'm just used to having editors that allow you to select areas visually, like drawing a hotspot on the image itself, and the software generates the HTML itself.
But I can't do that in Visual Studio, and I have about 20 different circular hotspots to create.. also I have no idea on how to easily detect coordinates (X & Y).
Any tips? Advice? Ideas?</p>
<p>Added in edit - Also, is there a way to add code to each hotspot in an imagemap?</p>
| <p>No, AFAIK there is no designer support for hotspots - I use a piece of paper.</p>
<p>Concerning the code, you'll have to set HotSpotMode="PostBack" PostBackValue="HS1" for each hotspot and use a switch statement in ImageMap1_Click to react to the different Postback values.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.