input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
A PHP API for retrieving Mail From Yahoo, GMail, Hotmail <p>There are a few APIs for grabbing the address book/contact list from the major providers of email.</p>
<p>I was wondering do APIs like this exist for grabbing emails/messages received?</p>
<p>Thanks all</p>
<h2>EDIT</h2>
<p>I am sure I can do this myself. However, I don't want to "re-invent" the wheel if someone has done it already. Probably better than I can since I am just a noob :P</p>
| <p>I think all of this services provide POP/IMAP protocol which you can acces with PHP's functions: <a href="http://php.net/book.imap" rel="nofollow">http://php.net/book.imap</a></p>
|
I need a fast key substitution algorithm for java <p>Given a string with replacement keys in it, how can I most efficiently replace these keys with runtime values, using <strong>Java</strong>? I need to do this often, fast, and on reasonably long strings (say, on average, 1-2kb). The form of the keys is my choice, since I'm providing the templates here too.</p>
<p>Here's an example (please don't get hung up on it being XML; I want to do this, if possible, cheaper than using XSL or DOM operations). I'd want to replace all <code>@[^@]*?@</code> patterns in this with property values from bean properties, true <code>Property</code> properties, and some other sources. The key here is <em>fast</em>. Any ideas?</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<envelope version="2.3">
<delivery_instructions>
<delivery_channel>
<channel_type>@CHANNEL_TYPE@</channel_type>
</delivery_channel>
<delivery_envelope>
<chan_delivery_envelope>
<queue_name>@ADDRESS@</queue_name>
</chan_delivery_envelope>
</delivery_envelope>
</delivery_instructions>
<composition_instructions>
<mime_part content_type="application/xml">
<content><external_uri>@URI@</external_uri></content>
</mime_part>
</composition_instructions>
</envelope>
</code></pre>
<p>The naive implementation is to use <code>String.replaceAll()</code> but I can't help but think that's less than ideal. If I can avoid adding new third-party dependencies, so much the better.</p>
| <p>The appendReplacement method in <a href="http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html" rel="nofollow">Matcher</a> looks like it might be useful, although I can't vouch for its speed.</p>
<p>Here's the sample code from the Javadoc:</p>
<pre><code>Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
</code></pre>
<p><strong>EDIT:</strong> If this is as complicated as it gets, you could probably implement your own state machine fairly easily. You'd pretty much be doing what appendReplacement is already doing, although a specialized implementation might be faster.</p>
|
How to eliminate post-render "flicker"? <p>I've tried my best to be a purist with my usage of Javascript/Ajax techniques, ensuring that all Ajax-y behavior is an enhancement of base functionality, while the site is also fully functional when Javascript is disabled. However, this causes some problems.</p>
<p>In some cases, a DOM node should only be visible when Javascript is enabled in the browser. In other cases, it should only be visible when disabled. Take for instance a submit button on a form that has a drop down with an onchange handler that auto-submits (using JQuery's form plugin):</p>
<pre><code><form method="post" action=".">
<label for="id_state">State:</label>
<select name="state" id="id_state" onchange="$(this.form).ajaxSubmit(ajax_submit_handler);">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
<input class="with_js_disabled" type="submit" value="OK" />
</form>
</code></pre>
<p>and the Javascript:</p>
<pre><code><script type="text/javascript">
$(document).ready(function()
{
$(".with_js_disabled").hide();
});
</script>
</code></pre>
<p>When Javascript is enabled, the submit button is not required (due to the onchange handler). However, JQuery's $(document).ready function (and the more direct document.onload) is only called after the page has been fully loaded and rendered - hence, the submit button is initially displayed and a "flash" occurs when the Javascript is executed and the node's display is set to "none".</p>
<p>I've accepted this as the cost of doing business, and haven't found a way around it. But is there a technique I'm not aware of that will minimize the effect, or even outright eliminate it?</p>
<p><strong>EDIT:</strong></p>
<p>The <code><noscript></code> solution mentioned by many people below seems promising, but isn't working for me on Safari. However Prestaul's 2nd suggestion works beautifully:</p>
<pre><code><body>
<script type="text/javascript">
document.body.className += ' has_js';
</script>
<!-- the rest of your page -->
</body>
</code></pre>
<p>This can then be styled using straight CSS:</p>
<pre><code>body .js_enabled_only { display: none; }
body .js_disabled_only { display: block; }
body.has_js .js_enabled_only { display: block; }
body.has_js .js_disabled_only { display: none; }
</code></pre>
<p>This second line is just for reference and can (and should) be removed to avoid circumstances where your element shouldn't be display:block. Likewise, you may need different variations on the third line for other display styles. But this solution is nice and clean, IMO, and in my tests entirely eliminates the flicker effect.</p>
| <p>How about combining some of these solutions:</p>
<pre><code><style type="text/javascript">
.only-without-script {
display: none;
}
</style>
<noscript>
<style type="text/javascript">
.only-with-script {
display: none;
}
.only-without-script {
display: block;
}
</style>
</noscript>
</code></pre>
<p>or I prefer adding a class to the body (place your <code><script></code> tag at the top of the body and don't use the .ready event):</p>
<pre><code><head>
<style type="text/javascript">
body.has-script .something-not-ajaxy {
display: none;
}
input.ajaxy-submit {
display: none;
}
body.has-script input.ajaxy-submit {
display: inline;
}
</style>
</head>
<body>
<script type="text/javascript">
document.body.className += ' has-script';
</script>
<!-- the rest of your page -->
</body>
</code></pre>
|
How do you manage your run once sql install scripts in subversion? <p>I'm working at a company that does several releases to production every year and during the build up to each release we gather up a collection of 1 time sql install scripts like table creation and dataports.</p>
<p>The way things currently work is that after the release to production, we branch, tag then we delete all 1 time scripts from subversion. </p>
<p>This seems to get the job done but to me it never seemed like the proper way to solve the problem. </p>
<p>Could you imagine deleting all your sourcecode every release and then writing patches for production? </p>
<p>The downsides that I see is if you want to reference and old script you have to checkout a tag or branch from subversion.</p>
<p>Our SVN Repo currently looks something like this</p>
<p>svnrepo/mywebsite/src
svnrepo/mywebsite/database/storedprocs
svnrepo/mywebsite/database/installscripts</p>
<p>I was thinking that a more accurate way to model what we want to do in SVN is the following.</p>
<p>Use an svn:externals attribute to point to the latest version. Then after every release just point it to the latest.</p>
<p>svnrepo/mywebsite/trunk/src/
svnrepo/mywebsite/trunk/src/database/installscripts/
-> svnrepo/mywebsite/trunk/database/Release_3</p>
<p>svnrepo/mywebsite/trunk/database/Release_1
svnrepo/mywebsite/trunk/database/Release_2
svnrepo/mywebsite/trunk/database/Release_3</p>
<p>Using this model we no longer svn delete any sql scripts and enable a database developer to check out svnrepo/mywebsite/trunk/database/ and easily view all the database development that has occurred.</p>
<p>Any comments on my ideas, the current structure, or the best way to manage this situation?</p>
<p>Thanks</p>
| <p>Synchronising database changes and code changes in subversion is hard</p>
<p>If you have the option of building the Database from scratch you can put the whole DDL into the repository along with the code, then you donât need to worry about which changes go with which release. </p>
<p>Looking at your situation I donât think you need to use externals (they can cause headaches). You also donât need to delete everything. It is not too difficult to check out a branch (or you could just use a repository browser).</p>
<p>You could even put the old db releases into a separate tag when you release so they are all in one place, which the database people can have checked out. If you are doing releases once a year this wonât be hard.</p>
<p><a href="http://stackoverflow.com/questions/173/how-do-i-version-my-ms-sql-database-in-svn">This question may also help</a></p>
|
jQuery $(document).ready() failing in IE6 <p>I have the following code:</p>
<pre><code>// Creates a timer to check for elements popping into the dom
timer = setInterval(function ()
{
for (p in pixelTypes)
{
checkElems(pixelTypes[p]);
}
}, 10);
// Add Document finished callback.
$(document).ready(function ()
{
// Document is loaded, so stop trying to find new pixels
clearInterval(timer);
});
</code></pre>
<p>In Firefox, it works great, but in IE6, I get a "Object Expected" error on the $(document).ready line.</p>
<p>I can't figure out what would cause IE6 to not recognize it, jquery is fully loaded by this point.</p>
<p>Is this a known issue?</p>
| <p>Just a few pointers for anyone that's interested:</p>
<p><code>$(document).ready(function() {...});</code> and <code>$(function() {...});</code> means exactly the same thing. The latter is a shorthand for the former.</p>
<p>If you develop for a large site, using multiple Javascript libraries, or you develop plugins meant to be compatible with other peoples work, you can not trust the dollar sign ($) to be associated with the jQuery object. Use the following notation to be on the safe side:</p>
<pre><code>(function($) { [your code here] })(jQuery);
</code></pre>
<p>This passes jQuery into a self-executing function, and associates $ with the jQuery object inside this function. Then it does not matter what the $ represents outside of your function.</p>
<p>To get back to your question, have you checked whether the timer variable is assigned when you get the error? I believe the browser will see the <code>$(document).ready(function() {...});</code> all as one line, so if you have some kind of debugger that tells you that's the offending line, it might be the timer variable...</p>
<p>Last thing: In Javascript, it is not correct to place open curly braces on a new line. This can cause really bad errors due to Javascripts semicolon-insertion. For further info, read Douglas Crockford's Javascript: The good parts:</p>
<p><a href="http://rads.stackoverflow.com/amzn/click/0596517742" rel="nofollow">http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ref=sr_1_1?ie=UTF8&s=books&qid=1267108736&sr=1-1</a></p>
<p>Anyway, really hope I didn't upset anyone. Hope you solve the problem!</p>
<p>EDIT: I'm not sure if this is what robertz meant by fully qualified, but as far as I know, when a URL is fully qualified it means no parts are missing, ie. it's an absolute URL starting with http:// or https:// (or some other protocol).
Please correct me if I'm wrong!</p>
|
High Level Graphics <p>I did a lot of VRML+Java work in college and loved it, but I feel like it's not really a marketable skill. Has anyone worked with a high level graphics API like open inventor, coin..etc that is actually in use to a degree that makes investing a lot of time in the API worthwhile for something more than a hobby?</p>
| <p>Here are some industries that need such graphics programming skills:</p>
<ul>
<li>Entertainment - Dreamworks, Pixar</li>
<li>Engineering - companies into Computation Fluid mechanics/ Dynamics (CFM, CDM)</li>
<li>Gaming - EA Games and so on</li>
</ul>
<p>Also check with companies into "photo realistic rendering". </p>
<p>So yes those skills will surely get you a nice job. If you take a look at the 'careers' or 'jobs' section of these companies you should get a pretty good idea of which particular api to develop on.</p>
|
When to exploit type inference in Haskell? <p>I'm curious as to how often experienced Haskell programmers really use type inference in practice. I often see it praised as an advantage over the always-explicit declarations needed in certain other languages, but for some reason (perhaps just because I'm new) it "feels" right to write a type signature just about all the time... and I'm sure in some cases it really is required.</p>
<p>Can some experienced Haskellers (Haskellites? Haskellizers?) provide some input?</p>
| <p>It's still an advantage, even if you write type signatures, because the compiler will catch type errors in your functions. I usually write type signatures too, but omit them in places like <code>where</code> or <code>let</code> clauses where you actually define new symbols but don't feel the need to specify a type signature.</p>
<p>Stupid example with a strange way to calculate squares of numbers:</p>
<pre><code>squares :: [Int]
squares = sums 0 odds
where
odds = filter odd [1..]
sums s (a:as) = s : sums (s+a) as
square :: Int -> Int
square n = squares !! n
</code></pre>
<p><code>odds</code> and <code>sums</code> are functions that would need a type signature if the compiler wouldn't infer them automatically.</p>
<p>Also if you use generic functions, like you usually do, type inference is what ensures that you really combine all those generic functions together in a valid way. If you, in the above example, say</p>
<pre><code>squares :: [a]
squares = ...
</code></pre>
<p>The compiler can deduce that this isn't valid this way, because one of the used functions (the <code>odd</code> function from the standard library), needs <code>a</code> to be in the type class <code>Integral</code>. In other languages you usually only recognize this at a later point.</p>
<p>If you write this as a template in C++, you get a compiler error when you use the function on a non-Integral type, but not when you define the template. This can be quite confusing, because it's not immediately clear where you've gone wrong and you might have to look through a long chain of error messages to find the real source of the problem. And in something like python you get the error at runtime at some unexpected point, because something didn't have the expected member functions. And in even more loosely typed languages you might not get any error, but just unexpected results.</p>
<p>In Haskell the compiler can ensure that the function can be called with all the types specified in it's signature, even if it's a generic function that is valid for all types that fulfill some constrains (aka type classes). This makes it easy to program in a generic way and use generic libraries, something much harder to get right in other languages. Even if you specify a generic type signature, there is still a lot of type inference going on in the compiler to find out what specific type is used in each call and if this type fulfills all the requirements of the function.</p>
|
String conversions <p>I have a method which takes String argument.In some cases i want to pass int value to that method.For invoking that method i want to convert int into String.For that i am doing the following</p>
<pre><code> aMethod(""+100);
</code></pre>
<p>One more option is </p>
<pre><code> aMethod(String.valueOf(100));
</code></pre>
<p>Both are correct.I don't know which is appropriate?Which gives better performance?</p>
<p>Mostly this is happen in GWT.In GWT for setting size of panels and widgets i want to do this.</p>
<p>Can anyone give suggestion?</p>
| <p>Good article by Jon Skeet about your question's topic: <a href="http://www.yoda.arachsys.com/java/stringconv.html" rel="nofollow">String conversions - the Good, the Okay-I-Suppose, and the Utterly Horrible</a></p>
|
Simple Dynamic Graph Display for C++ <p>I am looking for a simple graph layout library for C++. I want to embed the library into our visualizer based on wxWidgets. In summary, I am looking for something like <a href="http://www.graphviz.org/Gallery.php">graphviz</a>, except dynamic - that is when an event occurs, only the change in graph needs to be loaded, not the complete display. There is <a href="http://www.dynagraph.org/">dynagraph</a>, but it seems a dead project. I have previously been suggested to use VTK - but it is a heavyweight.</p>
<p>I am looking for open source, non-copyleft kind of library available for commercial use (GPL is out, LGPL should be ok). I am open to suggestions that google won't give. </p>
| <p>The layout that Graphviz generates is based on the global structure - any single addition can dramatically change the output (unless you're using fixed coordinates, in which case you probably wouldn't be asking this question). Basically, if you want automatic placement of elements, you need to accept one of these solutions:</p>
<ul>
<li>When a new element is placed, a physics simulation is run in realtime, causing nodes to bounce around wildly until they settle into their new locations. This will be slow, but it will show "pleasing" changes.</li>
<li>When a new element is placed, the entire graph is re-drawn (physics/whatever is hidden, but the entire thing gets modified). This will be faster due to not having to redraw, but the relative locations of nodes can be completely different.</li>
<li>When a new element is placed, the existing elements are not modified. After enough dynamic updates, your graph is going to look like crap, because automatic placement is a global optimization problem.</li>
</ul>
<p>Sorry I can't help with your question, but maybe this helps to explain why what you're looking for may simply not exist (or be any good).</p>
|
django application configuration <p>I'm dying to get started Django but I'm really struggling with the initial setup. I have Python/MySql/Apache2.2/mod_python installed. Now I'm trying to create a proper directory structure and then update Django and Apache settings.py/httpd docs respectively. Specifically the location tag in the latter. Django and Python are based on simplicity but this is one huge oversight from the Django folks to not provide more guidance in this area. I had a basic page running in the Django dev server but could not get the stylesheet to load. So i decided to install mod_python and try to use apache in my dev environment and I'm even more frustrated. I can't seem find a good example anywhere on the web or in books regarding how to create a realistic directory structure and then based on that strucure, how to configure neccessary settings. Everything in tutorials is as usual not realistic or very helpful. Too simple. If someone here could share how they have their Django directory and settings configured that would be FANTASTIC!</p>
| <p>Don't use Apache for development, that'll make you tear your hair out restarting Apache every fifteen seconds (<strong>EDIT</strong>: or you could just use PythonDebug On).</p>
<p><a href="http://docs.djangoproject.com/en/dev/howto/static-files/#limiting-use-to-debug-true" rel="nofollow">This technique</a> is how to get your media (stylesheets, etc) loading via the development server. If you used that exact snippet, you'd need to set MEDIA_URL to '/site_media/' and MEDIA_ROOT to '/path/to/media' (obviously this latter is likely to need changing to wherever your media files actually are).</p>
|
How are POST and GET variables handled in Python? <p>In PHP you can just use <code>$_POST</code> for POST and <code>$_GET</code> for GET (Query string) variables. What's the equivalent in Python?</p>
| <p>suppose you're posting a html form with this:</p>
<pre><code><input type="text" name="username">
</code></pre>
<p>If using <a href="http://docs.python.org/library/cgi.html">raw cgi</a>:</p>
<pre><code>import cgi
form = cgi.FieldStorage()
print form["username"]
</code></pre>
<p>If using <a href="http://docs.djangoproject.com/">Django</a>, <a href="http://pylonshq.com/">Pylons</a>, <a href="http://flask.pocoo.org/">Flask</a> or <a href="http://www.pylonsproject.org/projects/pyramid/about">Pyramid</a>: </p>
<pre><code>print request.GET['username'] # for GET form method
print request.POST['username'] # for POST form method
</code></pre>
<p>Using <a href="http://turbogears.org/">Turbogears</a>, <a href="http://www.cherrypy.org/">Cherrypy</a>:</p>
<pre><code>from cherrypy import request
print request.params['username']
</code></pre>
<p><a href="http://webpy.org">Web.py</a>:</p>
<pre><code>form = web.input()
print form.username
</code></pre>
<p><a href="http://werkzeug.pocoo.org/">Werkzeug</a>:</p>
<pre><code>print request.form['username']
</code></pre>
<p>If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:</p>
<pre><code>def index(self, username):
print username
</code></pre>
<p><a href="https://developers.google.com/appengine/docs/python/gettingstartedpython27/introduction">Google App Engine</a>:</p>
<pre><code>class SomeHandler(webapp2.RequestHandler):
def post(self):
name = self.request.get('username') # this will get the value from the field named username
self.response.write(name) # this will write on the document
</code></pre>
<p>So you really will have to choose one of those frameworks.</p>
|
Getting base station name using J2ME <p>How can get the base station name using J2ME?</p>
| <p>I'm not aware of any way generally for vanilla J2ME/MIDP. Specific platforms though may provide some way. For example, with BlackBerry you can use <code>net.rim.device.api.system.GPRSInfo</code> and related classes.</p>
|
CURL usages in PHP <p>I had a doubt in CURL (PHP) . I want to login directly into a site using CURL. Is it possible, if possible please guide me. </p>
<p>I tried with the following but its not working</p>
<pre><code>http://username:password@myurl
</code></pre>
| <p>This is probably what you're looking for:</p>
<pre><code>$ch = curl_init("http://myurl");
curl_setopt($ch, CURLOPT_USERPWD, "[username]:[password]");
$output = curl_exec($ch);
</code></pre>
<p>You can find more options for CURL <a href="http://us2.php.net/manual/en/function.curl-setopt.php" rel="nofollow">here</a>.</p>
|
Embedding Fonts in PDF from LaTeX Source with pdflatex <p>I need to embed the fonts that I'm using in my TeX document in my output PDF. I'm using pdflatex for TeX processing, and TextMate as my editor.</p>
<p>I can't find any reference on how to embed the fonts I need in the PDF document.</p>
| <p>From the pdfTex documentation,</p>
<blockquote>
<h1>5 Setting up fonts</h1>
<p>pdfTEX can work with Type 1 and TrueType fonts (and to some extent also
with OpenType fonts). Font les should be available and embedded for all
fonts used in the document. It is possible to use METAFONT-- generated
fonts in pdfTEX but it is strongly recommended not to use these fonts
if an equivalent is available in Type 1 or TrueType format, if only
because bitmap Type 3 fonts render very poorly in (older versions of)
Adobe Reader. Given the free availability of Type 1 versions of all the
Computer Modern fonts, and the ability to use standard PostScript fonts,
there is rarely a need to use bitmap fonts in pdfTEX.</p>
</blockquote>
<p>You probably need to either install the Type 1 Computer Modern fonts. Modern tex-live has them. If you have an older TeX distro, there is <code>lmodern</code>:</p>
<pre><code>\documentclass{article}
\usepackage{lmodern}
\begin{document}
Hello, world.
\end{document}
</code></pre>
<p>Now, if you check the fonts in the resulting document with, e.g., <code>pdffonts</code>:</p>
<pre><code>name type emb sub uni object ID
------------------------------------ ----------------- --- --- --- ---------
SZVHEC+LMRoman10-Regular Type 1 yes yes no 4 0
</code></pre>
<p>Bingo. Embedded type 1 font.</p>
|
ASP.NET MVC ViewData Null <p>I am currently creating an e-commerce site using C# ASP.NET MVC and have just come across a problem. On pages such as product pages and search results pages, I have to pass Lists of data from my controller to the ViewPage and that works just fine. However, a null reference exception occurs if the Viewdata equals null. It happens inside the viewpage when it loops through the ViewData and displays products or reviews.</p>
<p><strong>//ProductController.cs</strong></p>
<pre><code>public ActionResult Products_Sub(string category, int page)
{
ViewData["Products"] = database.GetByCategory(category, page);
return View();
}
</code></pre>
<p><strong>//ViewPage.cs -- product loop</strong></p>
<pre><code> <ul> foreach (E_Store.Models.Product product in ViewData["Products"] as
List<e_store.models.product>)
{%>
<li>
<img alt="<%= product.Title%>" src="<%= product.Thumbnail %>" />
<a href="/<%=product.Category %>/<%= product.SubCategory %>/<%= product.ASIN %>/1">
<%=product.Title%></a>
</li>
}%>
</ul>
</code></pre>
<p>The Null Reference Exception occurs when the following piece of code is reached:</p>
<pre><code> <ul> foreach (E_Store.Models.Product product in ViewData["Products"] as
</code></pre>
<p>What I would like to know is the best way to catch this type of error if it does happen, without resorting to <code>if</code> statements that check to see if it is null.</p>
<p>If anyone knows of a good way of doing this I would really love to know.</p>
| <p>In your case I would have your database.GetByCategory(category, page) method simply return an empty list rather than null, this way your foreach statement just won't have any data to loop through but you won't get a null exception.</p>
<p>In the case that you're not dealing with a list and the item is null, we use </p>
<pre><code>Html.Encode(ViewData.Eval("Field"))
</code></pre>
<p>To get the item's HTML value, it will return "" if the item is null.</p>
|
best deployment approach for VSeWSS 1.2 <p>Can anyone suggest the best deployment approach for VSeWSS 1.2 based development?</p>
<p>I have been working with this for more than 6 months now.. has anyone tried using WSPBuilder for this purpose?</p>
| <p>I Personally prefer using stsdev (<a href="http://www.codeplex.com/stsdev" rel="nofollow">http://www.codeplex.com/stsdev</a>). I've used both WSPbuilder and STSDEV. Stsdev offers some development project templates that you create using an stsdev gui, not like the standard project templates you create using new > project. </p>
<p>The stsdev projects has got a Rootfiles folder, which corresponds to the '12 hive' on the destination server. All the files you put into Rootfiles folder and subfolders, is automatically added to solutionpackage.ddf and manifest.xml, so you dont have to worry about editing these files and compiling them using makecab. </p>
<p>Another great thing that stsdev offers is build targets, like build, deploy, redeploy, Refresh Assembly in GAC, retract and upgrade. So stsdev projects automatically compiles the binaries, builds the .wsp package, and runs the stsadm commands according to the build type. You can customise the behavior of the build targets if you like, by editing the Microsoft.SharePoint.targets located in the DeploymentFiles folder of the project. As long as you are only working on the code, Refresh Assembly in GAC is a very fast build method, and you can see the changes in sharepoint immediately after. </p>
<p>An disadvantage of stsdev is if you use source control, the manifest.xml and SolutionPackage.ddf if not checked out, are read only, and will result in a compile error (i usually check out all the files in DeploymentFiles folder when working on a project). So you have to check out these files before building. Another thing is that it takes <strong>all</strong> the files under the Rootfiles, including the hidden vssver2.scc files if you are using source control. The project still builds and deploys without problems, but the files are in the wsp package, and copied to the '12 hive' on the destination server. </p>
<p>I think that compared to WSPbuilder, stsdev lets you customize just about anything of the development project, which i haven't been able to do in WSPbuilder. </p>
|
How to use #include directive correctly? <p>Is there any material about how to use <code>#include</code> correctly?
I didn't find any C/C++ text book that explains this usage in detail.
In formal project, I always get confused in dealing with it.</p>
| <p>The big one that always tripped me up was this:</p>
<p>This searches in the header path: </p>
<pre><code>#include <stdio.h>
</code></pre>
<p>This searches in your local directory:</p>
<pre><code>#include "myfile.h"
</code></pre>
<p>Second thing you should do with EVERY header is this:</p>
<p>myfilename.h:</p>
<pre><code>#ifndef MYFILENAME_H
#define MYFILENAME_H
//put code here
#endif
</code></pre>
<p>This pattern means that you cannot fall over on redefining the headers in your compilation (Cheers to orsogufo for pointing out to me this is called an "include guard"). Do some reading on how the C compiler actually compiles the files (before linking) because that will make the world of #define and #include make a whole lot of sense to you, the C compiler when it comes to parsing text isn't very intelligent. (The C compiler itself however is another matter)</p>
|
Login to windows xp programatically <p>Anyone heard that its possible to login to windows xp programatically,
I want to modify the way the Domain Controller authenticates the user and if the user authenticated in my special way it returns the user name and password to the service working on the client machine so it should login the user using its passed credentials from the DC without waiting for user to insert his original credentials.</p>
| <p>Have a look at this: <a href="http://msdn.microsoft.com/en-us/library/aa375457(VS.85).aspx">Gina.dll MSDN</a></p>
<p>Gina is the system that fingerprint readers etc. use to customise the login screen. You may be able to use this to achieve your purpose?</p>
<p>To future proof your app (Vista and Windows 7) you may wish to look into these: <a href="http://msdn.microsoft.com/en-us/magazine/cc163489.aspx">MSDN Mag Vista Credential Providers</a></p>
|
Can someone explain the difference between @Remote / @Local or only @Stateless in ejb? <p>I guess the topic says it.
I have tried googling this, but havent gotten the answer I am looking for.</p>
<p>I have many EJB's with only @Stateless.
And sometimes I put @Local on them withouth really knowing why, and the benefits/cons. I also know I can put @Remote, but really dont know the difference.</p>
<p>Hope someone can give a clear description, or point me somewhere that does.</p>
| <p>Annotations are part of EJB 3.0. For ex. @stateless means it is a stateless session bean. @local is used for local interface and @Remote for remote bean interface. A detailed description of the anotations is given <a href="http://edocs.bea.com/wls/docs100/ejb30/annotations.html#wp1416811">here</a>. To understand the meaning of these terms though, you should refer to a manual or book on EJBs. You can download a good EJB 3.0 book from <a href="http://www.theserverside.com/tt/books/wiley/masteringEJB3/index.tss">here</a>. Also checkout <a href="http://www.manning.com/panda/">EJB 3 in Action</a> from Manning Pub.</p>
|
Code golf: combining multiple sorted lists into a single sorted list <p>Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.</p>
<p>For example:</p>
<pre><code>input: ((1, 4, 7), (2, 5, 8), (3, 6, 9))
output: (1, 2, 3, 4, 5, 6, 7, 8, 9)
input: ((1, 10), (), (2, 5, 6, 7))
output: (1, 2, 5, 6, 7, 10)
</code></pre>
<p><strong>Note</strong>: solutions which concatenate the input lists then use a language-provided sort function are not in-keeping with the spirit of golf, and will not be accepted:</p>
<pre><code>sorted(sum(lists,[])) # cheating: out of bounds!
</code></pre>
<p>Apart from anything else, your algorithm <em>should</em> be (but doesn't have to be) a lot faster!</p>
<p>Clearly state the language, any foibles and the character count. Only include meaningful characters in the count, but feel free to add whitespace to the code for artistic / readability purposes.</p>
<p>To keep things tidy, suggest improvement in comments or by editing answers where appropriate, rather than creating a new answer for each "revision".</p>
<p><strong>EDIT</strong>: if I was submitting this question again, I would expand on the "no language provided sort" rule to be "don't concatenate all the lists then sort the result". Existing entries which do concatenate-then-sort are actually very interesting and compact, so I won't retro-actively introduce a rule they break, but feel free to work to the more restrictive spec in new submissions.</p>
<p><hr /></p>
<p>Inspired by <a href="http://stackoverflow.com/questions/464342/combining-two-sorted-lists-in-python">http://stackoverflow.com/questions/464342/combining-two-sorted-lists-in-python</a></p>
| <p>OCaml in 42 characters:</p>
<pre><code>let f=List.fold_left(List.merge compare)[]
</code></pre>
<p>I think I should get extra credit for 42 exactly?</p>
|
Parsing Functions <p>I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else block....</p>
<p><em>EDIT</em></p>
<p>This is for my own scripting language that i'm making. its nothing very complex, but i have a standard library of 8 functions or so that i need to be able to be run, how can i parse a line and run the function named in the line?</p>
| <p>Once you get the name of the function, use a dispatch dict to run the function:</p>
<pre><code>def mysum(...): ...
def myotherstuff(...): ...
# create dispatch dict:
myfunctions = {'sum': mysum, 'stuff': myotherstuff}
# run your parser:
function_name, parameters = parse_result(line)
# run the function:
myfunctions[function_name](parameters)
</code></pre>
<p>Alternatively create a class with the commands:</p>
<pre><code>class Commands(object):
def do_sum(self, ...): ...
def do_stuff(self, ...): ...
def run(self, funcname, params):
getattr(self, 'do_' + funcname)(params)
cmd = Commands()
function_name, parameters = parse_result(line)
cmd.run(function_name, parameters)
</code></pre>
<p>You could also look at the <a href="http://docs.python.org/library/cmd" rel="nofollow">cmd module</a> in the stdlib to do your class. It can provide you with a command-line interface for your language, with tab command completion, automatically.</p>
|
in ssis how do I include a reference to a global variable from a script component? <p>I have a script component which I need to reference a global variable? I guess I can dtsconfig file. How do I set this and read it back out from my script component?</p>
| <p>You can use </p>
<pre><code>Me.Variables.YourVariableName
</code></pre>
<p>this will work only in script component of Data Flow task. In script task you can use like this:</p>
<pre><code>Dts.Variables("YourVariableName").Value.ToString
</code></pre>
<p>All you need is to configure the package variable in the dts config file by specifying the value. </p>
|
SQL Server security via TSQL <p>I want to construct a transact sql script that will stop specified people from running certain commands against all databases: </p>
<pre><code>drop database, drop table or preferbly drop *
delete
update
</code></pre>
<p>Is this possible?
The user will already have access to the server.</p>
<p>Note : I am not trying to develop a security model for a server, or to prevent a malicious attack. This is an existing server where people may have a range of access rights through various Windows groups they belong to. I just want to know if there is a quick safeguard to prevent people from mistakenly running a command on the wrong server.</p>
| <p>(<strong>caveat</strong>, this is per-database; I don't know of anything server-wide, since the database is the main standalone unit)</p>
<p>Presumably your user isn't the owner of the schema (or dbo)? In which case, they already shouldn't have access to, well, anything unless you GRANT it. So don't <a href="http://msdn.microsoft.com/en-us/library/ms188371.aspx" rel="nofollow">GRANT</a> the access they don't need, <a href="http://msdn.microsoft.com/en-us/library/ms187719.aspx" rel="nofollow">REVOKE</a> any access you have granted incorrectly, and <a href="http://msdn.microsoft.com/en-us/library/ms173724.aspx" rel="nofollow">DENY</a> anything that you absolutely don't want them ever being able to do.</p>
<p>See also <a href="http://msdn.microsoft.com/en-us/library/aa215478(SQL.80).aspx" rel="nofollow">MSDN</a>.</p>
|
Complex ASP.NET web applications and nant <p>Working on an intranet where we have about 20 different web apps - some .net, some classic asp. </p>
<p>Currently each .net app is its own solution. There are advantages to this - we can build & deploy just one app, without affecting other apps, and all the apps share a session - but we can't use master pages, and there are real challenges using localization resources, shared css and js, etc. Build & deployment is done completely manually, which is a real problem.</p>
<p>I'm trying to set up a structure that will allow us to take advantage of VS2008 features, but still have the ability to update one app without affecting the others while still using features like master pages and localization resources, and sharing session between apps (so we can't set up virtual directories for each app).</p>
<p>If I set up single solution that looks like:</p>
<pre>
/Root
- App_GlobalResources/
- shared
-- masterpages/
-- css/
- App1/
- App2/
...
- AppN/
..
- ClassicASP1/
</pre>
<p>then the problem is that the build just produces a single DLL (Root.dll) - this will simply not scale to 20+ apps, all of which have different development cycles.</p>
<p>Is it possible (using nant, or some other build tool) to build multiple DLLs? In this case, I'd like to end up with Root.dll (contains the global resources at least) and App1.dll and App2.dll.</p>
<p>Any other suggestions or references I should look at?</p>
| <p>I'm not sure you can do what you want to do, sadly. VS tends to make one DLL per unique project (not solution), and it appears you have just one project, so hence, one DLL.</p>
<p>I'd suggest you keep one project (csproj) per application, but use NANT to build them all (ie, one at a time, together, in order), and package them all up for deployment. That way you can do a single point deployment, but still keep the apps seperate.</p>
<p>I'm surprised you can't use master pages in the sub-folders. You'd need to replicate them for each AppN folder, but again - NANT could be used to pull those in from a common place when you build your deployment package.</p>
<p>Writing a build and deployment script takes a while to get right, but I've found that once it's done, it pays for itself very quickly - even if the only payment is your sanity!</p>
|
What does the iPhone developer program give me over and above simple registration as an iPhone developer? <p>Simply put; what does my $99 get me, that I can't already get for free?</p>
<p>OK, OK, sounds like a dumb question, but the Apple site is not clear to me.</p>
<p>My hunch is that you get the ability to submit apps to the app store for your 99, but you could get everything else for free, but it's not clear to me hence the question.</p>
| <p>After paying the $99 the main benefits are shown below:</p>
<ul>
<li>Install your developed apps on your device without Jailbreaking</li>
<li>Submit and distribute paid and free apps to the Apple App Store</li>
<li>Access to coupon codes to distribute your paid app to reviewers (neat feature)</li>
<li>Distribute an internal app using ad-hoc distribution for up to 100 devices</li>
<li>Free additional marketing if your application is popular (generally not available to everyone)</li>
</ul>
<p>Those are the main benefits, I don't think I have forgotten any of the key benefits.</p>
|
Sharing C# code between Windows and Silverlight class libraries <p>We wrote a small Windows class library that implements extension methods for some standard types (strings initially). I placed this in a library so that any of our projects would be able to make use of it by simply referencing it and adding using XXX.Extensions.</p>
<p>A problem came up when we wanted to use some of these methods in Silverlight. Although all the code was compatible, a Windows library can't be referenced in Silverlight so we created a Silverlight library that had links to the same class files and put compiler directives into the classes to allow different using declarations and namespaces. This worked fine until today when I added a new class to the Windows extensions library and realised that I would have to remember to link the class into the Silverlight library too.</p>
<p>This isn't ideal and I wondered if anyone might have ideas for a better way of sharing extension methods and other helper code between Windows and Silverlight projects.</p>
| <p>You cannot set a reference from a Silverlight assembly to a regular .NET assembly but you can do so the other way round. </p>
<p>So create a shared Silverlight assembly and add your code to that assembly. Now you can set a reference fro both your regular .NET and you other Silverlight assembly to the shared Silverlight assembly.</p>
<p>The restriction is that you can only put code in there that would work on both the .NET and Silverlight CLR but that is no different from sharing code.</p>
|
Using Autoconf to find variably named libraries <p>I am writing my first project that will use autoconf and teaching it to myself as I go. For the most part, things are going extremely well. I have one last significant hurdle. I am having trouble locating library and header files that may be named differently from one system to the next.</p>
<p>For example, I need to compile with Mozilla's SpiderMonkey. When compiled from source, SpiderMonkey becomes libjs.so. On my Linux variant, however, SpiderMonkey is installed as libmozjs.so. It's the same library, just a different name, thus a different linker flag.</p>
<p>Is there a proper way to go about detecting the name of the library? Do I just default it to 'js' and give a configure option to override it?</p>
<p>I have the same situation with header files. The header files for SpiderMonkey are installed at /usr/include/mozjs/ on my operating system. I am sure that on other systems, it will be /usr/include/js/ or maybe even simply /usr/include/. How do I find the proper header file location? I was hesitant to do a vanilla "find" since it would be slow and I might find the wrong copy of the file (finding the file in a user's home directory instead of /usr/include/ for instance.)</p>
| <p>AC_TRY_LINK (with or without a loop) is unnecessarily redundant. Just take, for example, this recipe:</p>
<pre><code>LIBS=""
AC_SEARCH_LIBS([spidermonkey_init], [mozjs js], [sp_libs="$LIBS"; LIBS=""], [])
</code></pre>
|
How to assign values to the whole row of a dynamic two dimensional array? <p>I need to perform 9 different operations on a coordinate, depending on the position of the coordinate. I have a function that returns the coordinates of a position around the given coordinate (down, up, left, right or diagonals). The 9 different operations are the different possible 'types' of coordinate; if I'm dealing with coordinate (0, 0), the only valid operations are right, down-right and down.</p>
<p>I have a structure where I store the directions that are valid for each type of coordinate. 4 for the corner coordinates, 1 for all the inner coordinates, and 4 for the non-corner columns of the edge-rows.</p>
<p>The field in the structure where I store all the directions is a dynamic two-dimensional array called 'library'. Each row of library would correspond to a type of coordinate, containing all the valid directions for that type of coordinate. I haven't found a way to assign the values one row at a time though, and I can't assign them individually with a loop.</p>
<p>What I have tried is:</p>
<pre><code>searches->library[0][0] = {2, 3, 4, -1};
searches->library[1][0] = {4, 5, 6, -1};
searches->library[2][0] = {2, 3, 4, 5, 6, -1};
searches->library[3][0] = {0, 1, 2, 3, 4, 5, 6, 7, -1};
searches->library[4][0] = {0, 1, 2, -1};
searches->library[5][0] = {0, 6, 7, -1};
searches->library[6][0] = {0, 1, 2, 6, 7, -1};
searches->library[7][0] = {0, 1, 2, 3, 4, -1};
searches->library[8][0] = {0, 4, 5, 6, 7, -1};
</code></pre>
<p>But this gives me <code>p2AdjacencyMatrix.c:179: error: parse error before '{' token</code> for each line.</p>
<p>I have also tried:</p>
<pre><code>searches->library[][9] = {{2, 3, 4, -1},
{4, 5, 6, -1},
{2, 3, 4, 5, 6, -1},
{0, 1, 2, 3, 4, 5, 6, 7, -1},
{0, 1, 2, -1},
{0, 6, 7, -1},
{0, 1, 2, 6, 7, -1},
{0, 1, 2, 3, 4, -1},
{0, 4, 5, 6, 7, -1}};
</code></pre>
<p>And the result it <code>p2AdjacencyMatrix.c:189: error: parse error before ']' token</code></p>
<p>Here is the structure definition:</p>
<pre><code>typedef struct{
int active_length; // Size of active array of searches
int* active; // Active array of searches
int** library; // Library of array of searches
} SearchLibrary;
</code></pre>
<p>And the memory allocation for the dynamic array:</p>
<pre><code>SearchLibrary* searches;
searches = (SearchLibrary *) malloc(sizeof(SearchLibrary*));
int search_cases = 9, search_directions = 9;
searches->library = (int **) malloc(search_cases * sizeof(int *));
searches->active = (int *) malloc(search_directions * sizeof(int));
int i;
for(i = 0; i < search_cases; i++){
searches->library[i] = (int *) malloc(search_directions * sizeof(int));
}
</code></pre>
<p><strong>How can I add these values to each row of the array?</strong> I tried changing my structure definition to a static array, but that didn't work either. Is this happening because I'm using a pointer to a structure?</p>
| <p>Assuming C99, you can use a compound literal and <code>memcpy()</code> it over your row. For the <code>k</code>-th row, this could look like this:</p>
<pre><code>#define SEARCH_DIRECTIONS 9
memcpy(searches->library[k], ((int [SEARCH_DIRECTIONS]){ 1, 2, 3 }),
sizeof(int) * SEARCH_DIRECTIONS);
</code></pre>
|
Applying Styles to ASP.Net MVC ViewData objects <p>I have the following code in a MVC User Control (the field names have been changed to protect the innocent):</p>
<p><%=ViewData.Model.foo%></p>
<p><%=ViewData.Model.Bar%></p>
<p><%=ViewData.Model.Widget%></p>
<p><%=ViewData.Model.Thingy%></p>
<p><%=ViewData.Model.Address %></p>
<p><%=ViewData.Model.AlternateAddress %></p>
<p><%=ViewData.Model.CrossStreets %></p>
<p><%=ViewData.Model.SchoolName %></p>
<p>These are to be displayed in a list beneath a header on the page that calls this control.</p>
<p>Given that I blow at CSS, how do I apply tags to the header and these fields so that everything lines up properly?</p>
<p>Many thanks,</p>
<p>KevDog</p>
<p><b>Update:</b>
The goal is to have the fields in the user control underneath and aligned left beneath the labels in the header. My first problem is adding a class to the ViewData items above. Do they go inside of other tags or are the attributes applied inside the tag itself? I've tried the latter and it doesn't seem the correct approach. </p>
| <p>It appears, from your sample code, but you are just directly outputting string properties into the web page. In this case, you would need to surround the output string with a span or a div in order to assign it a class, like this:</p>
<pre><code><div class="foo"><%=ViewData.Model.foo %></div>
</code></pre>
<p>On the other hand, you might, elsewhere, use HTML helpers, and in this case, you can pass the class to the helper method:</p>
<pre><code><%= Html.TextBox("foo", ViewData.Model.Foo, new { @class="foo" })%>
</code></pre>
|
ASP.Net: Authentication via Browser's Login Window <p>I have what appears to be a fairly common scenario: I have a database that contains a list of users/passwords, and ideally, when someone visits the site, I'd like to use their windows name (internal), otherwise whatever name the user provided (external).</p>
<p>My main question is how do I send a response to the browser forcing it to prompt for their username/password for external users (like when you visit a page that uses windows authentication)? Has anyone done this before?</p>
<p>My main goal is to avoid creating a login screen, and just use what the browser has built in. Is there a way I can leverage the built in forms authentication to do this?</p>
<p>Thanks!</p>
<p>*Update: I found something similar to what I was looking for here: <a href="http://blog.codeville.net/2008/08/25/using-the-browsers-native-login-prompt/" rel="nofollow">http://blog.codeville.net/2008/08/25/using-the-browsers-native-login-prompt/</a></p>
| <p>You can use ASP.net Membership libraries with Windows authentication. Here is the <a href="http://weblogs.asp.net/scottgu/archive/2006/07/12/Recipe_3A00_-Enabling-Windows-Authentication-within-an-Intranet-ASP.NET-Web-application.aspx" rel="nofollow">ScottGu blog</a> talking about it</p>
|
HTML / CSS - DIV Element hidden when it shouldn't be? <p><a href="http://i41.tinypic.com/23rr095.jpg" rel="nofollow"><img src="http://i41.tinypic.com/23rr095.jpg" width="640"></a>
(clickable)</p>
<p>Mainad has a valid height and width, however it isn't shown like subad1/subad2. Which are in essence exactly the same! (just a different background image).</p>
<p>Firebug shows my div as greyed out for some weird reason. Replacing the contents of mainad with just some text doesn't solve the problem (problem isn't related to inner elements).. </p>
<p>What's going on?! :(</p>
| <p>Do you have AdBlock installed? That might be hiding that div.</p>
|
How to handle diacritics (accents) when rewriting 'pretty URLs' <p>I rewrite URLs to include the title of user generated travelblogs.</p>
<p>I do this for both readability of URLs and SEO purposes. </p>
<pre>
http://www.example.com/gallery/280-Gorges_du_Todra/
</pre>
<p>The first integer is the id, the rest is for us humans (but is irrelevant for requesting the resource).</p>
<p>Now people can write titles containing any UTF-8 character, but most are not allowed in the URL.
My audience is generally English speaking, but since they travel, they like to include names like </p>
<pre>
Aït Ben Haddou
</pre>
<p>What is the proper way to translate this for displaying in an URL using PHP on linux.</p>
<p>So far I've seen several solutions:</p>
<ol>
<li><p>just strip all non allowed characters, replace spaces
this has strange results:<br />
<code>'Aït Ben Haddou' â /gallery/280-At_Ben_Haddou/</code><br />
Not really helpfull.</p></li>
<li><p>just strip all non allowed characters, replace spaces, leave charcode (stackoverflow.com) most likely because of the 'regex-hammer' used<br />
this gives strange results:
<code>'tést tést' â /questions/0000/t233st-t233st</code></p></li>
<li><p>translate to 'nearest equivalent'<br />
<code>'Aït Ben Haddou' â /gallery/280-Ait_Ben_Haddou/</code><br />
But this goes wrong for german; for example 'ü' should be transliterated 'ue'.</p></li>
</ol>
<p>For me, as a Dutch person, the 3rd result 'looks' the best.<br />
I'm quite sure however that (1) many people will have a different opinion and (2) it is just plain wrong in the german example.</p>
<p>Another problem with the 3rd option is: how to find all possible characters that can be converted to a 7bit equivalent?</p>
<p>So the question is:</p>
<ol>
<li><p>what, in your opinion, is the most desirable result. (within tech-limits)</p></li>
<li><p>How to technically solve it. (reach the desired result) with PHP.</p></li>
</ol>
| <p>Ultimately, you're going to have to give up on the idea of "correct", for this problem. Translating the string, no matter how you do it, destroys accuracy in the name of compatibility and readability. All three options are equally compatible, but #1 and #2 suffer in terms of readability. So just run with it and go for whatever looks best â option #3.</p>
<p>Yes, the translations are wrong for German, but unless you start requiring your users to specify what language their titles are in (and restricting them to only one), you're not going to solve that problem without far more effort than it's worth. (For example, running each word in the title through dictionaries for each known language and translating that word's diacritics according to the rules of its language would <em>work</em>, but it's excessive.)</p>
<p>Alternatively, if German is a higher concern than other languages, make your translation <em>always</em> use the German version when one exists: <code>ä</code>â<code>ae</code>, <code>ë</code>â<code>e</code>, <code>ï</code>â<code>i</code>, <code>ö</code>â<code>oe</code>, <code>ü</code>â<code>ue</code>.</p>
<p><strong>Edit:</strong></p>
<p>Oh, and as for the actual method, I'd translate the special cases, if any, via <code>str_replace</code>, then use <code>iconv</code> for the rest:</p>
<pre><code>$text = str_replace(array("ä", "ö", "ü", "Ã"), array("ae", "oe", "ue", "ss"), $text);
$text = iconv('UTF-8', 'US-ASCII//TRANSLIT', $text);
</code></pre>
|
How to properly test this controller action with Shoulda? <p>I have the following controller action and test. I'm new to testing with Shoulda and I <em>know</em> there are areas of my controller that I can test further. For example, my flash messages as well as verifying the renders.</p>
<p>So my question is, how would I properly test this controller action in Shoulda?</p>
<p>My controller action (names have been changed to protect the innocent):</p>
<pre><code>def my_action
return redirect_to(root_url) if @site.nil?
@owner = current_site.owner
if request.post?
if params[:password].blank? || params[:email].blank?
flash[:error] = "You must fill in both the e-mail and password fields"
render :action => "my_action"
else
if @owner.authenticated?(params[:password])
@owner.login = params[:email]
@owner.save!
@owner.do_some_method
flash[:success] = "Success."
render :action => "my_action"
else
flash[:error] = "Incorrect password"
render :action => "my_action"
end
end
end
end
</code></pre>
<p>My test:</p>
<pre><code>context "on POST to :my_action" do
setup do
Owner.any_instance().expects(:do_some_method)
post :my_action, :email => 'foo@bar.com', :password => 'test'
end
should_assign_to :owner
should "Change name and verify password and resend activation key" do
assert_equal true, assigns(:owner).authenticated?('test')
assert_equal 'foo@bar.com', assigns(:owner).login
end
should_respond_with :success
end
</code></pre>
| <p>Right now, it appears that you're testing functionality specific to the model inside your controller, that should be in a unit test.</p>
<p>I would advise re-factoring your controller to include the required logic for updating the Owner's email inside the Owner model. By doing that, you should be able to simplify the controller down to a simple <code>if update; else; end</code> type statement and greatly simplify the controller test. Once you've moved the logic into the model, you can use built in Rails validations.</p>
<p>A couple of other things to consider:</p>
<ul>
<li>Redirecting after your POST action completes, prevents the user from double-posting by accident (most browsers will complain when the user attempts it).</li>
<li>Move the checking for @site and also the assignment to @owner to <code>before_filters</code> if this is done more than once inside the controller.</li>
<li>You can avoid having to check <code>if request.post?</code> with either <code>verify</code> or creating a route in `config/routes.rb'.</li>
</ul>
<p><strong>References</strong>:</p>
<ul>
<li><a href="http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model" rel="nofollow">Skinny Controller, Fat Model</a></li>
<li><a href="http://therailsway.com/2007/6/1/railsconf-recap-skinny-controllers" rel="nofollow">RailsConf Recap: Skinny Controllers</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html" rel="nofollow">ActionController::Filters::ClassMethods</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html" rel="nofollow">ActionController::Verification::ClassMethods</a></li>
</ul>
|
Can you search SQL Server 2005 Stored Procedure content? <p>SQL Server Server 2005. I'm staring at a database that has 500+ stored procedures, and trying to glean the intricacies of how they interact with the data - particularly in regards to how they insert/modify data. I was hoping to find a search" or "find" functionality that would look at the content of the actual procedure. That way, I could do a search for all procedures that do anything at all with some_table_name. The basic find functionality of SQL Management Studio looks in opened files, and Find in Files only appears to find the content if I already have the sproc opened, and even then only in the ...\Local Settings\Temp\~vs1011.sql temporary type files.</p>
<p>As of right now, the only way I know of getting to the underlying procedure is to right click and select "modify" (or Script Stored Procedure As => Create or Alter). Is there a faster/easier way to search/examine all the sprocs?</p>
| <p>Try using third party tools such as <a href="http://www.apexsql.com/sql_tools_search.aspx">ApexSQL Search</a> (free) or SSMS Toolpack (free) apart from those already mentioned here. </p>
<p>Iâve had a similar problem in the past when I inherited 500+ objects database. My experience is that queries are ok but what really helped was third party SSMS addins. </p>
|
php disk_total_space <p>i need help with disk_total_space function..</p>
<p>i have this on my code</p>
<pre><code><?php
$sql="select * from users order by id";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) {
?>
Name : <?php echo $row['name']; ?>
Email : <?php echo $row['email']; ?>
Diskspace Available : <?php
$dir = "C:/xampp/htdocs/freehosting/".$row['name'];
disk_total_space($dir);
} ?>
</code></pre>
<p>However this return me same disk space for every users .. </p>
<p>Anyone can shed me some light?</p>
<p>thanks :)</p>
| <p><a href="http://us2.php.net/disk_total_space" rel="nofollow">http://us2.php.net/disk_total_space</a> says,</p>
<blockquote>
<p>"Given a string containing a directory, this function will return the total number of bytes on the <strong>corresponding filesystem</strong> or <strong>disk partition</strong>."</p>
</blockquote>
<p>You're likely seeing the total_space of C:</p>
<p><a href="http://forums.devshed.com/showpost.php?p=1527717&postcount=4" rel="nofollow">Alternative solutions do exist for both Windows and Linux</a>.</p>
|
.NET ThreadPool clarification - Available vs idle threads <p>I'm a little confused about one aspect of the .NET ThreadPool: namely, how you can tell how many of its 'Available' threads are idle ones waiting to be reused, and how many haven't yet been created.</p>
<p>The summary for the <code>GetAvailableThreads()</code> method states that it:</p>
<blockquote>
<p>Retrieves the difference between the
maximum number of thread pool threads
returned by the GetMaxThreads method,
and the number currently active.</p>
</blockquote>
<p>Any thread that is 'active' is busy working and therefore not available for reuse, but how many are 'available' for reuse versus 'available' because they haven't been created?</p>
<p>I know that the <code>GetMinThreads()</code> method returns the absolute minimum number of threads the framework will maintain in the pool for reuse, but that doesn't necessarily equate to the current number of idle threads - does it? I'm under the impression that idle threads will hang around in the ThreadPool and only be pruned back to the minimum if they go unused for some time.</p>
<p>This is important because, according to the docs:</p>
<blockquote>
<p>When all thread pool threads have been assigned to tasks, the thread pool does not immediately begin creating new idle threads. To avoid unnecessarily allocating stack space for threads, it creates new idle threads at intervals. The interval is currently half a second, although it could change in future versions of the .NET Framework.</p>
</blockquote>
<p>I want to check if my application is having to create an excessive number of 'new' threads in the pool - slowing it down - but I'm not sure how to do that without being able to figure out how many idle, ready-to-reuse threads I have hanging around.</p>
<p>Any ideas welcome. Thanks!</p>
| <p>The ThreadPool does not have a way to determine how many threads are currently idle. That is, created but not actually doing anything.</p>
<p>My experience with the ThreadPool shows that it's pretty good about keeping threads around. I don't know if they've put logic in there to keep track of the average number of threads in use, but I've never noticed my programs waiting on thread creation. Except at startup, of course. One of my programs is often creating and running dozens of concurrent threads, and I don't see any delay in starting them up, even if the workload has been low for a period of time.</p>
<p>I would suggest that you instrument your application, keeping track of when you make the call to ThreadPool.QueueUserWorkItem, and when the work item actually starts. Something like this:</p>
<pre><code>DateTime queueTime = DateTime.Now;
ThreadPool.QueueUserWorkItem(WorkItemProc, queueTime);
void WorkItemProc(object state)
{
DateTime startTime = DateTime.Now;
DateTime queueTime = (DateTime)state;
TimeSpan elapsed = startTime - queueTime;
// At this point, elapsed.TotalMilliseconds will tell you how long it took
// between queuing the item and it actually being started.
...
}
</code></pre>
<p>If you find that it's taking too long to start your pool threads, then you should create your own managed thread, and use events or some other messaging mechanism to give it work.</p>
|
How do I prevent a swf from refreshing when an iframe is resized? <p>I am resizing an iframe, and when I do that in Firefox, the content gets refreshed.</p>
<p>I have a swf that extends, and in Firefox when the iframe extends to accommodate the swf, the swf appears in its normal position. </p>
<p>In IE this doesn't happen.</p>
<p>Anyone know how to prevent the refresh from happening in Firefox?</p>
<p>Thanks</p>
<p><hr /></p>
<p><strong>Edit:</strong></p>
<p>Ok I think the page is not being refreshed just the swf please check this out at:</p>
<p><a href="http://antoniocs.org/iframe/index_.html" rel="nofollow">http://antoniocs.org/iframe/index_.html</a></p>
<p>You can see that when the re-dimensioning takes place there is a quick "flash", in Firefox 3 and the swf returns to its initial state (not expanded), this does not happen in IE.</p>
<p>The code is all client side so you can view it all if you look at the source of the pages.</p>
| <p>Antonio, I'm afraid that the problem is in Firefox it self. When Gecko detects a change to the width of an iFrame, it repaints the page and causes that "refresh." There's no way that I know of to change this behavior, short of using a different technique.</p>
<p>I confirmed that the problem exists in other Gecko-based browsers as well (specifically Camino and Flock). I was not able to duplicate it in WebKit-based browsers (Chrome and Safari).</p>
|
Get bounds of filters applied to Flash Sprite within Sprite <p>I have a Flash library with Sprite symbols composed of other sprites with design-time applied filters. I'm embedding those symbols into a Flex application like so:</p>
<pre><code><mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
[Bindable]
[Embed(source="Resources.swf", symbol="SquareContainer")]
private var squareContainer_class:Class;
private function log(msg:String):void {
output.text = output.text + "\n" + msg;
}
]]>
</mx:Script>
<mx:VBox horizontalAlign="center" width="100%" height="100%" >
<mx:Image id="squareContainer" source="{squareContainer_class}"/>
<mx:Button click="log(squareContainer.width + ', ' + squareContainer.height);"/>
<mx:TextArea id="output" width="100%" height="100%" />
</mx:VBox>
</mx:Application>
</code></pre>
<p>In this example, the SquareContainer symbol is 100px wide by 100px height; however it contains a child sprite with a glow and blur filter, that cause the sprite to appear to be significantly larger than 100x100. Since I cannot know for certain the composition of the container, I cannot use BitmapData.generateFilterRect() to get at the filters applied to nested sprites. </p>
<p>How can I get the size of the sprite plus its filters?</p>
| <p>Oh sweet success! (and thanks for the tips) A friend helped solve the problem with a nice recursive function to handle the filters which may exist on nested sprites:</p>
<pre><code>private function getDisplayObjectRectangle(container:DisplayObjectContainer, processFilters:Boolean):Rectangle {
var final_rectangle:Rectangle = processDisplayObjectContainer(container, processFilters);
// translate to local
var local_point:Point = container.globalToLocal(new Point(final_rectangle.x, final_rectangle.y));
final_rectangle = new Rectangle(local_point.x, local_point.y, final_rectangle.width, final_rectangle.height);
return final_rectangle;
}
private function processDisplayObjectContainer(container:DisplayObjectContainer, processFilters:Boolean):Rectangle {
var result_rectangle:Rectangle = null;
// Process if container exists
if (container != null) {
var index:int = 0;
var displayObject:DisplayObject;
// Process each child DisplayObject
for(var childIndex:int = 0; childIndex < container.numChildren; childIndex++){
displayObject = container.getChildAt(childIndex);
//If we are recursing all children, we also get the rectangle of children within these children.
if (displayObject is DisplayObjectContainer) {
// Let's drill into the structure till we find the deepest DisplayObject
var displayObject_rectangle:Rectangle = processDisplayObjectContainer(displayObject as DisplayObjectContainer, processFilters);
// Now, stepping out, uniting the result creates a rectangle that surrounds siblings
if (result_rectangle == null) {
result_rectangle = displayObject_rectangle.clone();
} else {
result_rectangle = result_rectangle.union(displayObject_rectangle);
}
}
}
// Get bounds of current container, at this point we're stepping out of the nested DisplayObjects
var container_rectangle:Rectangle = container.getBounds(container.stage);
if (result_rectangle == null) {
result_rectangle = container_rectangle.clone();
} else {
result_rectangle = result_rectangle.union(container_rectangle);
}
// Include all filters if requested and they exist
if ((processFilters == true) && (container.filters.length > 0)) {
var filterGenerater_rectangle:Rectangle = new Rectangle(0,0,result_rectangle.width, result_rectangle.height);
var bmd:BitmapData = new BitmapData(result_rectangle.width, result_rectangle.height, true, 0x00000000);
var filter_minimumX:Number = 0;
var filter_minimumY:Number = 0;
var filtersLength:int = container.filters.length;
for (var filtersIndex:int = 0; filtersIndex < filtersLength; filtersIndex++) {
var filter:BitmapFilter = container.filters[filtersIndex];
var filter_rectangle:Rectangle = bmd.generateFilterRect(filterGenerater_rectangle, filter);
filter_minimumX = filter_minimumX + filter_rectangle.x;
filter_minimumY = filter_minimumY + filter_rectangle.y;
filterGenerater_rectangle = filter_rectangle.clone();
filterGenerater_rectangle.x = 0;
filterGenerater_rectangle.y = 0;
bmd = new BitmapData(filterGenerater_rectangle.width, filterGenerater_rectangle.height, true, 0x00000000);
}
// Reposition filter_rectangle back to global coordinates
filter_rectangle.x = result_rectangle.x + filter_minimumX;
filter_rectangle.y = result_rectangle.y + filter_minimumY;
result_rectangle = filter_rectangle.clone();
}
} else {
throw new Error("No displayobject was passed as an argument");
}
return result_rectangle;
}
</code></pre>
|
VB.NET Queue constructor Error: Queue grow factor must be between 1 and 10 <p>First some background:
VB.NET 2005 Application that accesses a MS-SQL back-end, using multiple Web Services for data gathering/publishing.</p>
<p>On to the error:
Our application mysteriously crashes on one of our clients computers, it works fine on the other computers in their office, but not on the big whigs' computer, which now makes it my problem. It appears to be a software conflict of some sort as they have replaced the computer (with the same software configuration I assume) but the error still persists. I'm currently waiting to hear back from their IT staff on whether there are any known differences between this user's setup and the others in that office.</p>
<p>What's even more annoying is the app just disappears. We can't easily debug it as no error messages are shown, even though we have specific code in there to catch unhandled exceptions and display a message, it just closes. </p>
<p>However, our exception handling code <em>is</em> being called (at least partially) because it successfully logs this following error (just does not show it to the user like other normal errors):</p>
<pre><code>Error Message: Queue grow factor must be between 1 and 10.
Stack Trace: at
System.Collections.Queue..ctor(Int32 capacity, Single growFactor) at
System.Collections.Queue..ctor() at
System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous) at
System.Windows.Forms.Control.BeginInvoke(Delegate method, Object[] args) at
System.Windows.Forms.Form.OnLoad(EventArgs e) at
System.Windows.Forms.Form.OnCreateControl() at
System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible) at
System.Windows.Forms.Control.CreateControl() at
System.Windows.Forms.Control.WmShowWindow(Message& m) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ScrollableControl.WndProc(Message& m) at
System.Windows.Forms.ContainerControl.WndProc(Message& m) at
System.Windows.Forms.Form.WmShowWindow(Message& m) at
System.Windows.Forms.Form.WndProc(Message& m) at
System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at
System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at
System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code></pre>
<p>Now the really curious part is that we're not using Queues at all in the code that should be running at this point. (User opens app, tries to login, bam, error happens) The only Queues referenced anywhere in code is in a very specific function that is only ever run in a testing mode in-house. And it has no problems there whatsoever.</p>
<p>I'm kind of at a loss as to where to proceed with this problem, so any input would be appreciated.</p>
<p>Edit: Ok I've finally been in contact with their IT department, he was running .NET 2.0 as I suspected. I had the IT guy repair the .NET install from Add/Remove Programs and after that the problem no longer existed. So it was in fact a .NET issue</p>
| <p>Is it possible that this user doesn't have the appropriate .net framework? I'm guessing your application requires 2.0, but maybe he/she has 3.5? Is he running a different version of windows than the other users?</p>
<p>The problem is not happening with your code but the lower level .net BCL.</p>
|
What is Your Tool-of-Choice for Creating Stubs? <p>Following on from my last question "<a href="http://stackoverflow.com/questions/463278/what-is-a-stub">What is a "Stub"</a>, I would really like to sit down tonight and play more with creating stub objects.</p>
<p><strong>What is your tool of choice for creating Stub objects?</strong> </p>
<p>And for bonus points :)</p>
<p>Can you also link to any good tutorials for getting started with them?</p>
<p>Thanks a lot guys and girls, appreciated :)</p>
<p><strong>FYI - I am using .NET (2.0 @ Work, 3.5 @ Home)</strong></p>
| <p>Simply, Rhino.Mocks. Yes, "Mocks Aren't Stubs", but Rhino.Mocks does both. Before wrapping my brain around Rhino.Mocks I hand-coded my own stubs. Never again.</p>
<p>Sorry, I don't get the bonus points. Ayende.com, the place to get Rhino.Mocks, has decent online documentation, and a forum full of questions. The author is actually very good at responding and answering too. I don't feel like there's a good "shortcut" to learning how to use it; for this I think it's through practice and/or trial-and-error that it's best learned.</p>
<p>(In rereading the above, I don't mean it to sound like RTFM even though it may come across that way.)</p>
|
What is Rhino Mocks Repeat? <p>What is Rhino Mocks Repeat ?</p>
<pre><code>Repeat.Any();
Repeat.Once();
</code></pre>
<p>What does it mean and how it works ?</p>
| <p>It's used with the <code>Expect</code> construct as part of a fluent declaration. As for what it means, it means that the previous even is expected to occur that many times.</p>
<p>For instance, <code>Expect.Call(someMethod()).Repeat.Twice()</code> says that <code>someMethod()</code> will be called exactly two times.</p>
|
treeview checkbox: how to check on select and vice versa <p>I'm working on a treeview with its CheckBoxes property set to true. I want the same functionality as in a CheckListBox in that if I check the box of a treenode, that node will be selected; and if I select a node, that node's checkbox will be checked. I'm not sure what event I need to hookup to do this. Please help. Thanks.</p>
| <p>Try the following:</p>
<pre><code> private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
treeView1.SelectedNode.Checked = true;
}
</code></pre>
<p>This event is tied to the treeviews AfterSelect event</p>
|
Getting row index from an ImageButton click in a GridView <p>I have a Gridview with ImageButtons added to a column via a templatefield. I've attached a function to the "OnClick" event.</p>
<p>Once in this function, how can I get the index of the row that has the button that has been clicked. It appears that all I have is the mouse coordinates on the page.</p>
| <p>Cast the sender to an ImageButton then cast the image button's NamingContainer to a row:</p>
<p>VB:</p>
<pre><code>Dim btn as ImageButton = CType(sender, ImageButton)
Dim row as GridViewRow = CType(btn.NamingContainer, GridViewRow)
</code></pre>
<p>C#: </p>
<pre><code>ImageButton btn = (ImageButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
</code></pre>
|
Can anybody give me an example of overused design patterns? <p>I've been hearing and reading about cases when people had come across cases of overused design patterns. Ok, missused design patterns are understandable phenomenon. What does it actually mean overused design patterns?</p>
<p>Do you have any examples and why do you think there are too many patterns?</p>
| <p>The <a href="http://en.wikipedia.org/wiki/Singleton_pattern">singleton</a> is probably the most <a href="http://www.ibm.com/developerworks/webservices/library/co-single.html">overused design pattern</a>. I often see it used in many cases when it's out of scope and much more appropriate to directly instantiate objects.</p>
<p>After that, I believe the <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">factory pattern</a> is way overused as a shortcut of instantiating objects, many times without a real need.</p>
|
Flex Datagrid to Array? <p>I need to convert a datagrid table in Adobe Flex to an ArrayCollection. I was expecting to be able to loop through each row of a datagrid and write that to the Array collection, but the only method for accessing data in the datagrid that I can find is SelectedItem, which doesn't help me.</p>
<p>Obviously one could just copy the dataProvider for the datagrid, but my datagrid is editable and I need to store the state of the datagrid at any one time into a database. Can anyone recommend a method of doing this?</p>
<h2>Much Appreciated</h2>
<p>-Matt</p>
| <p>If your DataGrid is:</p>
<pre><code><mx:DataGrid id="someDG" dataProvider="{this.provider}" />
</code></pre>
<p>Then check if this.provider is Array or ArrayCollection. If it is ArrayCollection then access it simply by:</p>
<pre><code>var gotIt:ArrayCollection = this.someDG.dataProvider as ArrayCollection;
</code></pre>
<p>if it is an Array, then:</p>
<pre><code>var gotIt:ArrayCollection = new ArrayCollection(this.someDG.dataProvider as Array);
</code></pre>
<p>Hope this helps.</p>
|
Class Access question <p>I know this should be simple and I should know it but it's eluding me for the time being.</p>
<p>I am using a singleton pattern to help with logging stuff. However, logging only happens in one class, and the singleton is basically a watcher for a boolean that opens and closes the log file. Because I don't want the file to be opened more than once, or closed more than once, I'm using the singleton pattern. However, I don't want it to be a global value, and I sure as hell don't want other classes, even inside the package accessing it. How can I make it so only this one class use it?</p>
| <p>Make it a private class inside the class in which you want to use it. Also, consider making it a static class.</p>
|
Add Multiple User Control of the Same Type to a Page <p>Similar questions to this one have been asked but none seem to address my exact situation here's what I am trying to do.</p>
<p>I have a user control that manages student info. i.e. FirstName, LastName, Address etc.</p>
<p>I have a webpage/form that has a button on it. "Add Student". What I want to accomplish is for a new StudentInfo control to be added to the webform after each click.</p>
<p>My current code looks something like this</p>
<pre><code>Private Sub btnAddStudent_Click(sender as object, ByVal e As System.EventArgs)
Dim lStudentInfo as Control
LoadControl("~/StudentInfo.ascx")
Me.placeholder1.controls.add(lStudentInfo)
End Sub
</code></pre>
<p>With this code only one StudentInfo control is added and upon pressing the "Add" button again a new StudentInfo control isnt added below the first one and the text/data entered within the first control is cleared.</p>
<p>Thanks in advance for any assistance.</p>
| <p>What is happening is that every time you do a postback your previous control was lost. Remember, every postback uses a brand new instance of your page class. The instance you added the control to last time was <em>destroyed</em> as soon as the http request finished — possibly before the browser even finished loading it's DOM. </p>
<p>If you want a control to exist for every postback you have to add it <em>on every postback</em>. </p>
<p>Additionally, if you want ViewState to work for the control you need to add it <em>before the Load event for the page</em>. This means either on Init or PreInit.</p>
<pre><code>Private Sub btnAddStudent_Click(sender as object, ByVal e As System.EventArgs)
Me.placeholder1.controls.add(LoadControl("~/StudentInfo.ascx"))
Session("NewStudentControls") += 1
End Sub
Protected Sub Page_Init(sender as object, e as system.eventargs)
For i As Integer = 1 To Session("NewStudentControls")
Me.placeholder1.controls.add(LoadControl("~/StudentInfo.ascx"))
Next
End Sub
</code></pre>
|
Windows Mobile Emulator networking to host machine <p>I'm trying to do some Windows Mobile dev in VS2008. The WM app is making a WCF call (or trying to). The emulator and my WCF server are running on the same desktop PC. I found some details about how to configure the network card on the WM5 emulator in conjunction with Virtual PC2007. This does allow me to now surf the net view the emulator, which puts me a lot closer than I was. However, I can't get it to recognise the desktop machine itself, e.g. <a href="http://mycomputername/" rel="nofollow">http://mycomputername/</a> and <a href="http://10.1.1.2/" rel="nofollow">http://10.1.1.2/</a> Obviously, this makes it a bit hard to test the WCF side of things. Have I missed something obvious?</p>
<p>Thanks</p>
| <p>In visual studio that you are doing win mobile development from, go to tools menu then select device emulator manager. If your device emulator is running you will see it with a small arrow in the list. Right click this emulator and select "cradle". This should open activesync for XP or windows mobile device center for Vista or higher. Once you have cradled the emulator you should be able to access your local PC by IP or name. Good luck, i've spent way too much time messing with trying to get this to connect so I hope this gets you there a little faster.</p>
|
Assembly code vs Machine code vs Object code? <p>What is the difference between object code, machine code and assembly code?</p>
<p>Can you give a visual example of their difference?</p>
| <p>Machine code is binary (1's and 0's) code that can be executed directly by the cpu. If you were to open a "machine code" file in a text editor you would see garbage, including unprintable characters (no, not <em>those</em> unprintable characters ;).</p>
<p>Object code is a portion of machine code that hasn't yet been linked into a complete program. It's the machine code for one particular library or module that will make up the completed product. It may also contain placeholders or offsets not found in the machine code of a completed program that the linker will use to connect everything together.</p>
<p>Assembly code is plain-text and (somewhat) human read-able source code that has a mostly direct 1:1 analog with machine instructions. This is accomplished using mnemonics for the actual instructions/registers/other resources. Examples include things like <code>JMP</code> or <code>MULT</code> for the jump and multiplication instructions. Unlike Machine Code, the CPU does not understand Assembly Code.</p>
|
Math Resources for C/C++ Programmers <p>My degree is in Electrical and Computer Engineering but i'm currently employed as a Software Engineer. I took all of the algebra, geometry and calculus classes that one would expect from someone with my degree however I must admit, I think I learned just enough to pass the test but never really saw a use for it and therefore never really retained much of the material.</p>
<p>Now that i've matured some, I see the use for it all of the time. I KNOW that there are lots of places that math knowledge would improve my coding so i'm ready to relearn the old stuff and learn some new stuff.</p>
<p>What are your favorite resources out there? (Resources that can tie math into programming are even better if you have any!) Books? Websites? Blogs?</p>
| <p>I found this blog on the subject intresting:</p>
<p><a href="http://steve-yegge.blogspot.com/2006/03/math-for-programmers.html" rel="nofollow">http://steve-yegge.blogspot.com/2006/03/math-for-programmers.html</a></p>
<p>also has some recommendations for books.</p>
|
Camera output, while performing functions, SLOW converting from linux to windows (C++) <p>I know this is probably general, please bear with me!</p>
<p>We've got a program that uses a web camera and, based on what the camera is seeing, runs certain functions. The program runs excellently on MacOS and Linux, and it compiles and it <em>does run</em> on Windows, but a couple of the functions, (including one that iterates pixel by pixel, 640x480) drop the FPS to 1 or less. Occasionally dropping it to freeze for a nunber of seconds. </p>
<p>Like I said, I know this is very general... I was just (desperately) hoping for anybody else's input on possible explanations? These same functions work fine on other platforms. I'm curious if possibly the camera's running in it's own thread, which gets bogged down? Maybe we just aren't looking in the right places to optimize? And is there possibly a resource on what to optimze when porting code to windows? </p>
<p>Thanks so much, and any input is <strong>very much</strong> appreciated!</p>
<p><<< EDIT >>></p>
<p>As for the video source code, I'm using ewclib and </p>
<pre><code>const char * m_buffer;
EWC_Open(MEDIASUBTYPE_RGB24, 640, 480, FPS, true);
m_buffer = new unsigned char[EWC_GetBufferSize(0)];
EWC_GetImage(0, m_buffer);
</code></pre>
| <p>What do you use to compile the program on Windows? Visual Studio? Cygwin? Are you sure you are not compiling a debug version? Have you turned on compiler optimization? You may also want to check your data types. You may be assuming int to be 64 bits, while you may be using 32-bit Windows, where it is 32 bits.</p>
|
Is R a compiled language? <p>I can't find it anywhere on the web (and I don't want to install it). Is the <a href="http://en.wikipedia.org/wiki/R_(programming_language)" rel="nofollow">R language</a> a compiled language? How fast does it run a pre-written script? Does it do any kind of compilation, or just execute instructions line by line?</p>
| <p>In most cases R is an interpreted language that runs in a read-evaluate-print loop. There are numerous extensions to R that are written in other languages like C and Fortran where speed or interfacing with native libraries is helpful. </p>
|
What are some good C++ resources for effectively using Apache XML Security? <p>I'm looking for some resources that allow me to understand how to use this library, particularly for signing XML. Most of what I found out there is Java related, and I would prefer to get documentation/FAQs/tutorials on the C++ library.</p>
| <p>I had the same problem. The best information I could find was on the Apache website itself ( <a href="http://santuario.apache.org/c/programming.html" rel="nofollow">http://santuario.apache.org/c/programming.html</a> ), the API docs and by looking at the code of the examples and tools (like templatesign) they provide.</p>
<p>This information combined with some experimenting was enough for me to sign and verify XML documents. Basically I just used templatesign and checksig as starting point.</p>
<p>The most problems I had was with C14N, so if there is something not working try dumping the raw data streams which Apache is using internally and check if it really signs/verifies what you expect. </p>
|
How does one parse an XML document after first validating against a DTD in VB6 <p>I am attempting to write a XML parser in VB6.<br />
The standards that the XML is based off of comes with a DTD to verify the XML before you begin parsing. I have also written a sample XML file so that I have something with which to test.</p>
<p>I am able to load the XML via the vb6 code </p>
<pre><code>Dim objXMLDoc As MSXML.DOMDocument
Set objXMLDoc = New MSXML.DOMDocument
If Not objXMLDoc.Load("sample.xml") Then
----Goto ErrorHandler
End If
</code></pre>
<p>Working XML </p>
<pre><code><?xml version = "1.0"?>
<Root>
...
</Root>
</code></pre>
<p>Trying to validate with my DTD</p>
<pre><code><?xml version = "1.0"?>
<!DOCTYPE sample SYSTEM "sample.dtd">
<Root>
...
</Root>
</code></pre>
<p>The research I did lead me to believe that the Load would validate the XML if the XML pointed to the DTD via the doc type.<br />
I've done a lot of research and cant figure out where I'm going wrong. It could be as simple as the DTD provided isn't syntactically correct, which I'm looking over now. The resources I've found are mostly on MSDN and here <a href="http://www.jalix.org/ressources/internet/dom/~vrac/articles/XML%20DOM.html" rel="nofollow">http://www.jalix.org/ressources/internet/dom/~vrac/articles/XML%20DOM.html</a>.<br />
Both the xml and dtd are located in the same directory, and I have it parsing the XML with out the doctype tag.</p>
<p>The error I get is:<br />
Error #: -2146697211: The system cannot locate the resouce specified.
error processing resource 'sample.dtd'</p>
<p>Any additional resources, or suggestions would be greatly appreciated.</p>
| <p>I can't reproduce your error. It works just fine with both files in the same folder for me.</p>
<p>It's not a problem of the DTD not being well-formed either; that throws another error. I get the same error as you if it can't find the DTD, while I get error <code>-1072896757</code> ("Invalid character found in DTD.") if it does find my (totally bogus) DTD.</p>
<p>Have you tried using a different <em>Microsoft XML</em> version, or are you tied to the old <strong>version 2.0</strong>? Try <strong>v6.0</strong> if possible.</p>
|
SQL Server won't perform regular expression validation on XML column <p>I have an XML column in my table which contains this xsd snippet:</p>
<pre><code><xsd:element name="Postcode" minOccurs="0">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:pattern value="^[0-9]{4}$" />
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
</code></pre>
<p>The regular expression should require a string containing 4 numerical digits. It validates perfectly in Visual Studio and is a correct regular expression.</p>
<p>SQL Server, on the other hand, won't accept it. The error message I receive is: </p>
<pre><code>XML Validation: Invalid simple type value: '1234'. Location: / * : Donor[1]/*:Postcode[1].
</code></pre>
<p>I have an email address regex working fine, but can't get this simple numerical regex to work.</p>
| <p>Does your source XML look like this:</p>
<pre><code><Postcode>1234</Postcode>
</code></pre>
<p>or like this:</p>
<pre><code><Postcode>
1234
</Postcode>
</code></pre>
<p>Since you are trimming the string (with <code>^</code> and <code>$</code>) make sure that your XML looks like the former and not the latter.</p>
|
dojo.require issues <p>I'm having trouble configuring my initial installation of dojo to include the widget framework correctly. </p>
<p>Following most of the code I see, including dijit should look like this:</p>
<pre><code>dojo.require("dijit");
</code></pre>
<p>and that's that. Unfortunately, that doesn't seem to work. </p>
<p>Using this initializes the widgets correctly, but there's some weird behavior from the standard dijit methods that makes me think that I'm doing it wrong:</p>
<pre><code>dojo.require("dijit.dijit");
</code></pre>
<p>Is there an element of configuring dojo that I'm missing? The files are all placed as they are in the 1.2.3 distribution, underneath another javascript folder.</p>
| <p>You don't actually <em>have to</em> include dijit, just point directly to widgets you want to use: <code>dojo.require("dijit.Dialog");</code>. Weird widget behavior could be explained also by:</p>
<ul>
<li>missing theme css files: check with FireBug that everything gets loaded</li>
<li>missing theme class attribute: add <code>class="tundra"</code> to the <code>body</code> element</li>
<li>missing <code>djConfig="parseOnLoad: true"</code></li>
</ul>
|
Use data with variable structure <p>Imagine a system that works with data, which structure changes over time. Say, for example, today your User object contains Name : String and Email : String, but tomorrow you need to add Age : Integer and Address which consists of Country, Zip code, etc. Then you may want to create new field User.Contacts and move Email and Address to that field, like refactoring.
And it should be done in runtime, without coding and redeployment, because it will be done by customers or administrators, not developers.</p>
<p>What approaches and tools would you consider for storing such data? Will it be separate table for each class of objects and altering table each time structure is changed, or 1-to-many relationship between object and it's property values (like table StringProperties with fields ObjectID, PropertyID, StringValue); or one big table for all objects (with generic fields StringField1, NumericField2, etc)</p>
<p>How would you make indexing work?</p>
<p>Would you consider using less mainstream tools like CouchDB? Are there any other tools I should know about?</p>
<p>Are there any existing examples of application with similar idea - allowing users to define and augment their own data structures?</p>
<p>EDIT: I do not expect anyone to solve my entire design problem. Rough ideas or links to tools like CouchDB or Prevayler are more than welcome. Any article links are welcome too.</p>
| <p>I think this would largely depend on the longevity of the data and the language you're in.</p>
<p>For a short lived structure, in a dynamic language, then I would be tempted to go low-brow and use a Hash of Lists.</p>
<p>On the other end of the scale - something you need to persist and you really want a relational database, then I would probably move over to a more modular architecture, whereby the client code takes care of the whole lifecycle of the data - up to and including the <code>create table</code> statements, the marshalling and unmarshalling, and querying of the data. </p>
<p>For the marshalling/unmarshalling/query problem, there's another fork in the road which may be using a ORM tool, or using a more low-tech/raw SQL approach. Either way, you would need some kind of staged approach which is part of the modular design.</p>
<p>Of course, how you arrange your data structure when it's in memory could be a straight forward Map of Lists, or more type safe approach, such as found with Eclipse's <code>IAdaptable</code> "pattern". </p>
<p>Otherwise, you're in the territory of tools like Prevayler which are more advanced serialized to disk tools than RDBMS.</p>
<p>On a side note, you could do a lot worse than CouchDB.</p>
|
Hibernate session handling in spring web services <p>I am using spring-ws with Jaxb2Marshaller, PayloadRootAnnotationMethodEndpointMapping and GenericMarshallingMethodEndpointAdapter to configure my web services via the @Endpoint and @PayloadRoot annotations.</p>
<p>When I try to use the DAO's of my project I am able to load objects from the database but as soon as I try to access properties inside my service that should be lazily loaded I get a org.hibernate.LazyInitializationException - could not initialize proxy - no Session.</p>
<p>In my spring-mvc web application the OpenSessionInViewInterceptor handles the sessions. How do I configure my web service project to automatically create a Hibernate session for every web service call? </p>
| <p>Wrap a org.springframework.aop.framework.ProxyFactoryBean around the object in the spring context that needs the hibernate session to be present.</p>
<p>This article <a href="http://springtips.blogspot.com/2007/06/spring-and-hibernate.html" rel="nofollow">http://springtips.blogspot.com/2007/06/spring-and-hibernate.html</a> shows how to do it.</p>
<p>If you experience problems because of lazy-loaded collections when using sessions this way there are at least 2 possible fixes:</p>
<ul>
<li>Add a Hibernate.initialize() call to the collection in code that is executed with the Hibernate session available - <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Hibernate.html#initialize" rel="nofollow">http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Hibernate.html#initialize</a>(java.lang.Object)</li>
<li>Use a non-lazy collection by adding lazy="false" to the mapping - watch out when using this option, you can easily force hibernate to load your whole database with a couple of badly placed lazy="false" options. </li>
</ul>
|
How to use msxml with Visual Studio 2008 Express (no ATL classes) without becoming crazy? <p>It is not really a question because I have already found a solution. It took me a lot of time, that's why I want to explain it here.</p>
<p>Msxml is based on COM so it is not really easy to use in C++ even when you have helpful classes to deal with memory allocation issues. But writing a new XML parser would be much more difficult so I wanted to use msxml.</p>
<p><strong>The problem:</strong></p>
<p>I was able to find enough examples on the internet to use msxml with the help of <code>CComPtr</code> (smart pointer to avoid having to call Release() for each IXMLDOMNode manually), <code>CComBSTR</code> (to convert C++ strings to the COM format for strings) and <code>CComVariant</code>. This 3 helpful classes are ATL classes and need an <code>#include <atlbase.h></code>.</p>
<p>Problem: Visual Studio 2008 Express (the free version) doesn't include ATL.</p>
<p><strong>Solution:</strong></p>
<p>Use <code>comutil.h</code> and <code>comdef.h</code>, which include some simple helper classes:</p>
<ul>
<li><code>_bstr_t</code> replaces more or less <code>CComBSTR</code></li>
<li><code>_variant_t</code> replaces more or less <code>CComVariant</code></li>
<li><code>_com_ptr_t</code> replaces indirectly <code>CComPtr</code> through the use of <code>_COM_SMARTPTR_TYPEDEF</code></li>
</ul>
<p><strong>Small example:</strong></p>
<pre><code>#include <msxml.h>
#include <comdef.h>
#include <comutil.h>
// Define some smart pointers for MSXML
_COM_SMARTPTR_TYPEDEF(IXMLDOMDocument, __uuidof(IXMLDOMDocument)); // IXMLDOMDocumentPtr
_COM_SMARTPTR_TYPEDEF(IXMLDOMElement, __uuidof(IXMLDOMElement)); // IXMLDOMElementPtr
_COM_SMARTPTR_TYPEDEF(IXMLDOMNodeList, __uuidof(IXMLDOMNodeList)); // IXMLDOMNodeListPtr
_COM_SMARTPTR_TYPEDEF(IXMLDOMNamedNodeMap, __uuidof(IXMLDOMNamedNodeMap)); // IXMLDOMNamedNodeMapPtr
_COM_SMARTPTR_TYPEDEF(IXMLDOMNode, __uuidof(IXMLDOMNode)); // IXMLDOMNodePtr
void test_msxml()
{
// This program will use COM
CoInitializeEx(NULL, COINIT_MULTITHREADED);
{
// Create parser
IXMLDOMDocumentPtr pXMLDoc;
HRESULT hr = CoCreateInstance(__uuidof (DOMDocument), NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)&pXMLDoc);
pXMLDoc->put_validateOnParse(VARIANT_FALSE);
pXMLDoc->put_resolveExternals(VARIANT_FALSE);
pXMLDoc->put_preserveWhiteSpace(VARIANT_FALSE);
// Open file
VARIANT_BOOL bLoadOk;
std::wstring sfilename = L"testfile.xml";
hr = pXMLDoc->load(_variant_t(sfilename.c_str()), &bLoadOk);
// Search for node <testtag>
IXMLDOMNodePtr pNode;
hr = pXMLDoc->selectSingleNode(_bstr_t(L"testtag"), &pNode);
// Read something
_bstr_t bstrText;
hr = pNode->get_text(bstrText.GetAddress());
std::string sSomething = bstrText;
}
// I'm finished with COM
// (Don't call before all IXMLDOMNodePtr are out of scope)
CoUninitialize();
}
</code></pre>
| <p>Maybe try using the <code>#import</code> statement. </p>
<p>I've used it in a VS6 project I have hanging around, you do something like this (for illustrative purposes only; this worked for me but I don't claim to be error proof):</p>
<pre><code>#import "msxml6.dll"
...
MSXML2::IXMLDOMDocument2Ptr pdoc;
HRESULT hr = pdoc.CreateInstance(__uuidof(MSXML2::DOMDocument60));
if (!SUCCEEDED(hr)) return hr;
MSXML2::IXMLDOMDocument2Ptr pschema;
HRESULT hr = pschema.CreateInstance(__uuidof(MSXML2::DOMDocument60));
if (!SUCCEEDED(hr)) return hr;
pschema->async=VARIANT_FALSE;
VARIANT_BOOL b;
b = pschema->loadXML(_bstr_t( /* your schema XML here */ ));
MSXML2::IXMLDOMSchemaCollection2Ptr pSchemaCache;
hr = pSchemaCache.CreateInstance(__uuidof(MSXML2::XMLSchemaCache60));
if (!SUCCEEDED(hr)) return hr;
_variant_t vp=pschema.GetInterfacePtr();
pSchemaCache->add(_bstr_t( /* your namespace here */ ),vp);
pdoc->async=VARIANT_FALSE;
pdoc->schemas = pSchemaCache.GetInterfacePtr();
pdoc->validateOnParse=VARIANT_TRUE;
if (how == e_filename)
b = pdoc->load(v);
else
b = pdoc->loadXML(bxmldoc);
pXMLError = pdoc->parseError;
if (pXMLError->errorCode != 0)
return E_FAIL; // an unhelpful return code, sigh....
</code></pre>
|
WCF Fails Under Load - MessageSecurityException <p>I am load testing my website. The site calls to a WCF service running on the same box using clientCredentialType="Windows". Everything works until I reach a certain load (which is not even very high), then I get the following error:</p>
<blockquote>
<p>System.ServiceModel.Security.MessageSecurityException:
The HTTP request was forbidden with
client authentication scheme
'Anonymous'. ---->
System.Net.WebException: The remote
server returned an error: (403)
Forbidden.</p>
</blockquote>
<p>Upon each call I create a channel:</p>
<pre><code>var proxy = (IClientChannel)channelFactory.CreateChannel();
</code></pre>
<p>On success, I close:</p>
<pre><code>proxy.Close();
</code></pre>
<p>On error, I abort:</p>
<pre><code>proxy.Abort();
</code></pre>
<p>Any ideas what's going on? What I can do to handle loads better? What to look for?</p>
| <p>Is your Service a Sessionful Service or do you not worry about keeping state between calls? If you don't have state, you may want to mark your service as a PerCall service. This will make sure that the service instance only exists when a client call is in progress.</p>
<p>Chapter 4 of Juval Lowy's excellent book "Programming WCF Services" 2nd Edition covers this topic.</p>
<p>The default is PerSession which may not be what you want.</p>
<p>Also, see this on MSDN: How To: <a href="http://msdn.microsoft.com/en-us/library/ms734715.aspx" rel="nofollow">Control Service Instancing</a> </p>
|
What is the best approach for decoupled database design in terms of data sharing? <p>I have a series of Oracle databases that need to access each other's data. The most efficient way to do this is to use database links - setting up a few database links I can get data from A to B with the minimum of fuss. The problem for me is that you end up with a tightly-coupled design and if one database goes down it can bring the coupled databases with it (or perhaps part of an application on those databases).</p>
<p>What alternative approaches have you tried for sharing data between Oracle databases?</p>
<p><strong>Update after a couple of responses...</strong></p>
<p>I wasn't thinking so much a replication, more on accessing "master data". For example, if I have a central database with currency conversion rates and I want to pull a rate into a separate database (application). For such a small dataset igor-db's suggestion of materialized views over DB links would work beautifully. However, when you are dynamically sampling from a very large dataset then the option of locally caching starts to become trickier. What options would you go for in these circumstances. I wondered about an XML service but tuinstoel (in a comment to le dorfier's reply) rightly questioned the overhead involved.</p>
<p><strong>Summary of responses...</strong></p>
<p>On the whole I think igor-db is closest, which is why I've accepted that answer, but I thought I'd add a little to bring out some of the other answers.</p>
<p>For my purposes, where I'm looking at data replication only, it looks like Oracle BASIC replication (as opposed to ADVANCED) replication is the one for me. Using materialized view logs on the master site and materialized views on the snapshot site looks like an excellent way forward.</p>
<p>Where this isn't an option, perhaps where the data volumes make full table replication an issue, then a messaging solution seems the most appropriate Oracle solution. Oracle Advanced Queueing seems the quickest and easiest way to set up a messaging solution.</p>
<p>The least preferable approach seems to be roll-your-own XML web services but only where the relative ease of Advanced Queueing isn't an option.</p>
| <p>Streams is the Oracle replication technology.
You can use MVs over database links (so database 'A' has a materialized view of the data from database 'B'. If 'B' goes down, the MV can't be refreshed but the data is still in 'A').</p>
<p>Mileage may depend on DB volumes, change volumes...</p>
|
How can I read system information in Python on OS X? <p>Following from this <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python">OS-agnostic question</a>, specifically <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291">this response</a>, similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from OS X using Python (including, but not limited to memory usage).</p>
| <p>You can get a large amount of system information from the command line utilities <a href="http://developer.apple.com/DOCUMENTATION/Darwin/Reference/ManPages/man8/sysctl.8.html" rel="nofollow"><code>sysctl</code></a> and <a href="http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/ManPages/man1/vm_stat.1.html" rel="nofollow"><code>vm_stat</code></a> (as well as <code>ps</code>, as in <a href="http://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python">this question</a>.) </p>
<p>If you don't find a better way, you could always call these using <a href="http://docs.python.org/library/subprocess.html" rel="nofollow"><code>subprocess</code></a>.</p>
|
How can I deploy a django appserver as an egg, running behind fastcgi? <p>I want to run a django appserver behind apache/fastcgi. That's no problem, django does that out of the box.</p>
<p>I want this appserver to be deployable via setuptools. That is, I will make it as an egg and install it with easy_install. And that part I can also handle, even though setuptools is not a standard complement to a django appserver.</p>
<p>But what I can't figure out is how the dispatch.fcgi would actually call into this my_app.egg to "start" the server process. Has anyone ever run in this config before?</p>
| <p>What you probably want to do instead is use something like <a href="http://pythonpaste.org/" rel="nofollow">Paste</a> to delegate to your egg (see example Paste deployment config file <a href="http://pythonpaste.org/deploy/#the-config-file" rel="nofollow">here</a>); this means doing the <code>flup</code> stuff (which translates FastCGI to WSGI) manually since you'll be pointing <code>flup</code> at Paste instead of at Django, but you can look at the Django management script to find out how it works.</p>
|
Compiler Error when adding dll reference to managed c++ project <p>I am using VS 2008 and get compiler errors sporadically when adding a dll reference to a managed c++ file in my C++ project. I am trying to add a reference to the dll so as to be able to use smart pointers.
<strong>ex: #import items.tlb</strong></p>
<p>The problem is that the compiler crashes at sporadic places inside of <strong>items.tlh</strong> almost as though chunks of bytes where erased of missings , but when i open the file i can't find any reference to the aforementioned errors. </p>
<p>I tried to rebuild the whole project several times, tried on different machine, but although the compiler errors are not consistents and disappear alltogether sometimes , a fresh rebuild sometimes brings back the problem. I was told that the size of the generated <strong>.tlh</strong> file may be a reason but it doesn't really solve my problem or point me in the right direction.</p>
<p>Did anybody experienced the same symptoms?
Thank you</p>
| <p>Whenever I've had this problem, it was caused by linking a Debug build to a Release DLL or a Release build to a Debug DLL.</p>
|
Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)? <p>In Python compiled regex patterns <a href="http://docs.python.org/library/re.html#re.findall">have a <code>findall</code> method</a> that does the following:</p>
<blockquote>
<p>Return all non-overlapping matches of
pattern in string, as a list of
strings. The string is scanned
left-to-right, and matches are
returned in the order found. If one or
more groups are present in the
pattern, return a list of groups; this
will be a list of tuples if the
pattern has more than one group. Empty
matches are included in the result
unless they touch the beginning of
another match.</p>
</blockquote>
<p>What's the canonical way of doing this in Perl? A naive algorithm I can think of is along the lines of "while a search and replace with the empty string is successful, do [suite]". I'm hoping there's a nicer way. :-)</p>
<p>Thanks in advance!</p>
| <p>Use the <code>/g</code> modifier in your match. From the <code>perlop</code> manual:</p>
<blockquote>
<p>The "<code>/g</code>" modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern.</p>
<p>In scalar context, each execution of "<code>m//g</code>" finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using the <code>pos()</code> function; see "<code>pos</code>" in <code>perlfunc</code>. A failed match normally resets the search position to the beginning of the string, but you can avoid that by adding the "<code>/c</code>" modifier (e.g. "<code>m//gc</code>"). Modifying the target string also resets the search position.</p>
</blockquote>
|
In what situation should the built-in 'operator' module be used in python? <p>I'm speaking of this module:
<a href="http://docs.python.org/library/operator.html">http://docs.python.org/library/operator.html</a></p>
<p>From the article:</p>
<blockquote>
<p>The operator module exports a set of
functions implemented in C
corresponding to the intrinsic
operators of Python. For example,
operator.add(x, y) is equivalent to
the expression x+y. The function names
are those used for special class
methods; variants without leading and
trailing __ are also provided for
convenience.</p>
</blockquote>
<p>I'm not sure I understand the benefit or purpose of this module.</p>
| <p>Possibly the most popular usage is operator.itemgetter. Given a list <code>lst</code> of tuples, you can sort by the ith element by: <code>lst.sort(key=operator.itemgetter(i))</code></p>
<p>Certainly, you could do the same thing without operator by defining your own key function, but the operator module makes it slightly neater.</p>
<p>As to the rest, python allows a functional style of programming, and so it can come up -- for instance, Greg's reduce example.</p>
<p>You might argue: "Why do I need <code>operator.add</code> when I can just do: <code>add = lambda x, y: x+y</code>?" The answers are:</p>
<ol>
<li><code>operator.add</code> is (I think) slightly faster.</li>
<li>It makes the code easier to understand for you, or another person later, looking at it. They don't need to look for the definition of add, because they know what the operator module does.</li>
</ol>
|
How to restructure this code hierarchy (relating to the Law of Demeter) <p>I've got a game engine where I'm splitting off the physics simulation from the game object functionality. So I've got a pure virtual class for a physical body</p>
<pre><code>class Body
</code></pre>
<p>from which I'll be deriving various implementations of a physics simulation. My game object class then looks like</p>
<pre><code>class GameObject {
public:
// ...
private:
Body *m_pBody;
};
</code></pre>
<p>and I can plug in whatever implementation I need for that particular game. But I may need access to all of the <code>Body</code> functions when I've only got a <code>GameObject</code>. So I've found myself writing tons of things like</p>
<pre><code>Vector GameObject::GetPosition() const { return m_pBody->GetPosition(); }
</code></pre>
<p>I'm tempted to scratch all of them and just do stuff like</p>
<pre><code>pObject->GetBody()->GetPosition();
</code></pre>
<p>but this seems wrong (i.e. violates the Law of Demeter). Plus, it simply pushes the verbosity from the implementation to the usage. So I'm looking for a different way of doing this.</p>
| <p>One approach you could take is to split the <code>Body</code> interface into multiple interfaces, each with a different purpose and give <code>GameObject</code> ownership of only the interfaces that it would have to expose.</p>
<pre><code>class Positionable;
class Movable;
class Collidable;
//etc.
</code></pre>
<p>The concrete <code>Body</code> implementations would probably implement all interfaces but a <code>GameObject</code> that only needs to expose its position would only reference (through dependency injection) a <code>Positionable</code> interface:</p>
<pre><code>class BodyA : public Positionable, Movable, Collidable {
// ...
};
class GameObjectA {
private:
Positionable *m_p;
public:
GameObjectA(Positionable *p) { m_p = p; }
Positionable *getPosition() { return m_p; }
};
BodyA bodyA;
GameObjectA objA(&bodyA);
objA->getPosition()->getX();
</code></pre>
|
Specifying connection string in config file for a class library and re-use/modify in ASP.NET Web Application <p>How can one specify the connection string in a config file of a class library and later modify this when used in a ASP.NET Web Application?</p>
<p>The Class library is a data access layer that has a Dataset connecting to a database based on a connection string specified in a config file (Settings.settings/app.config).</p>
<p>This class library is used in a web application where user inputs data and is written to the database using the DAL classes & methods exposed in the class library.</p>
<p>Now, I want to migrate this application from development environment to testing environment and later to production. The problem I'm facing is that after migrating to testing, the app in testing still connects to development database. I've changed the connection string mentioned in <strong><class library>.dll.config</strong> file but this seems to have no impact. </p>
<p>Can someone explain the right way to achieve this? Thanks in advance for any help. Cheers.</p>
| <p>With the .config files the name has to match the main executing assembly. For example I had a situation like yours, I needed a class library to have its settings in a .dll.config file. While it was able to reference it the actual application would not be able to read the config file because it was expecting .exe.config. Renaming the .dll.config to .exe.config fixed the problem.</p>
<p>In your case migrating your connection strings from .dll.config to web.config should fix your problem!</p>
<p>Good luck!</p>
|
Is it possible to display a panel or div in between gridview rows on RowCommand event <p>Currentaly I am using a gridView and on RowCommand event of gridview the details of selected row are displayed below the Gridview. But now I have to display the details just below the row clicked. Means it will be displayed in between the selected row and next row of it. The gridview code is as </p>
<pre><code> <asp:GridView ID ="gvUserDataReadOnly" AutoGenerateColumns ="false" runat ="server" OnRowCommand ="gvUserDataReadOnly_RowCommand" DataKeyNames ="Guid">
<Columns >
<asp:ButtonField ItemStyle-Width ="100px" DataTextField ="FirstName" HeaderText ="<%$ Resources:StringsRes,pge_ContactManager_FirstName %>" SortExpression ="FiratName" CommandName ="show_Details" ButtonType ="link" />
<asp:ButtonField ItemStyle-Width ="100px" DataTextField ="LastName" HeaderText ="<%$ Resources:StringsRes,pge_ContactManager_LastName %>" SortExpression ="LastName" CommandName ="show_Details" ButtonType ="link" />
<asp:BoundField ItemStyle-Width ="100px" DataField ="TypeName" HeaderText ="<%$ Resources:StringsRes,pge_ContactManager_TypeName %>" SortExpression ="TypeId" />
</Columns>
<RowStyle Height="25px" />
<HeaderStyle Height="30px"/>
</asp:GridView>
</code></pre>
<p>and div tag which i want to display in betwwen rows is</p>
<pre><code><div id ="dvUserDatails" runat ="server" visible ="false" class ="eventcontent">
<h2><asp:Literal ID ="ltUserName" runat ="server" ></asp:Literal></h2>
<asp:Label Text ="Type : " runat ="server" ID ="Type"></asp:Label><asp:Literal ID ="ltType" runat ="server" ></asp:Literal><br />
<asp:Label Text ="Address : " runat ="server" ID ="Address"></asp:Label><asp:Literal ID ="ltAddress" runat ="server" ></asp:Literal><br />
<asp:Label Text ="Phone No : " runat ="server" ID ="PhoneNo"></asp:Label><asp:Literal ID ="ltPhoneNo" runat ="server" ></asp:Literal><br />
<asp:Label Text ="Mobile No : " runat ="server" ID ="MobNo"></asp:Label><asp:Literal ID ="ltMobNo" runat ="server" ></asp:Literal><br />
<asp:Label Text ="Email Id : " runat ="server" ID ="emailId"></asp:Label><asp:Literal ID ="ltemail" runat ="server" ></asp:Literal><br />
</div>
</code></pre>
<p>I can't use EditItem Template as I am not using Edit button of gridview. Can anyone tell me how to do this task? Any other way to do this? Thanks in advance.</p>
| <p>You probably want to use a Repeater and build the table yourself. I don't think that you'll be able to get a GridView to work as you can only control what goes in each row and what you want to do is alternate rows between general and detailed information. More information on how to connect it to your data source and handle the button clicks can be found at <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx" rel="nofollow">MSDN</a>.</p>
<pre><code><asp:Repeater ID="gvUserDataReadOnly" runat="server" DataKeyNames="Guid">
<HeaderTemplate>
<table>
<tr>
<th>Header 1</th>
...
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
... first name button ...
</td>
...
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr runat="server" visible="false">
<td colspan="3">
... details (minus div) here ...
</td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</code></pre>
|
How do you run Android instrumentation tests from Eclipse? <p>Currently I'm running instrumentations tests from the command line this way:</p>
<pre><code>adb shell am instrument -w com.blah.blah/android.test.InstrumentationTestRunner
</code></pre>
<p>Is there a way to run them from Eclipse (with automatic installation of the application)?</p>
| <p>I was not able to determine automatic deployment to the emulator. However, you can take that same "adb shell" command and create an external launch configuration. I blogged on this same topic <a href="http://stuffikeepforgettinghowtodo.blogspot.com/2009/01/unit-testing-android-applications.html" rel="nofollow">here</a>. Launching this way is a bit more intuitive when you're also using the "-e debug true" argument.</p>
<p>However, I think I've gotten more mileage out of the bash shell script (if you're using a <em>good</em> development platform) :</p>
<pre><code>function adbtest() {
adb shell am instrument -w -e class blah.package.$1 blah.package.test/android.test.InstrumentationTestRunner;
}
</code></pre>
<p>That way when I want to test blah.package.FooTest I only need to remember to type:</p>
<pre><code>james@trex:~$ adbtest FooTest
</code></pre>
|
A Regex to match a SHA1 <p>I'm trying to match SHA1's in generic text with a regular expression.</p>
<p>Ideally I want to avoid matching words. </p>
<p>It's safe to say that full SHA1's have a distinctive pattern (they're long and a consistent length) - so I can match these reliably - but what about abbreviated SHA1's?</p>
<p>Can I rely on the presence of numbers?</p>
<p>Looking at the SHA1's in my commit log - numbers always appear in the first 3 characters. But is this too short? How many characters of SHA1 do I need to consider before I can assume a number would have appeared? </p>
<p>This does not have to be 100% accurate - I just need to match an abbreviated SHA1 99% of the time.</p>
| <p>You can consider the SHA1 hashes to be completely random, so this reduces to a matter of probabilities. The probability that a given digit is not a number is 6/16, or 0.375. The probability that three SHA1 digits are all not numbers is 0.375 ** 3, or 0.0527 (5% ish). At six digits, this reduces again to 0.00278 (0.2%). At five digits, the probability of all letters drops below 1% (you said you wanted to match 99% of the time).</p>
<p>It's easy to craft a regular expression that always matches SHA1 values:</p>
<pre><code>\b[0-9a-f]{5,40}\b
</code></pre>
<p>However, this may also match perfectly good five letter words, like "added" or "faded". In my <code>/usr/share/dict/words</code> file, there are several six letter words that would match: "accede", "beaded", "bedded", "decade", "deface", "efface", and "facade" are the most likely. At seven letters, there is only "deedeed" which is unlikely to appear in prose. It all depends on how many false positives you can tolerate, and what the likely words you will encounter actually are.</p>
|
Any reason to use DataSets with Local Databases with SQL Server CE? <p>Does it make sense to use .NET DataSets even in applications that use a local in-process database for application data persistence?</p>
<p>If DataSets are mainly meant for in-memory caching of database results, it sounds like they're not so beneficial when using something like SQL Server Compact local database that runs in the same process as the application.</p>
<p>Are there any other reasons to use typed DataSets? Say, do they ease WPF data binding?</p>
| <p>Let me try to answer my own question.</p>
<p>It seems to me that DataSets were designed for use-cases such as this:</p>
<ol>
<li>Data is loaded from a remote DB to an in-memory cache (the DataSet).</li>
<li>The cached copy is operated on in non-trivial ways (multiple tables, delete, add, update) without an active connection to the database.
<ul>
<li>DB relations need to be modeled into the local cache to enable these operations. </li>
<li>Data binding to the UI (e.g., WPF) is trivial because we're working on in-memory copy of the data.</li>
</ul></li>
<li>The cached copy is sometimes updated to the remote DB for true persistence.<br />
<ul>
<li>This may happen for example when the client returns to online state or the user presses "Apply" to truly commit his data.</li>
</ul></li>
</ol>
<p>With local in-process databases, there's no need for the ability to work completely offline -- the local DB connection is always available. This would suggest that modeling (potentially) complex DB relations into the local cache to enable add, delete and update is unnecessary. Rather, one would directly modify data in the database and only maintain a custom local cache for viewing the data. The local cache could be decoupled from the DB layer and put into its own ViewModel layer (MVVM).</p>
|
Is there a way to automatically sort the using directives alphabetically in Visual Studio 2005? <p>There is <a href="http://msdn.microsoft.com/en-us/library/bb514113.aspx" rel="nofollow">this option</a> available in Visual Studio 2008.</p>
<p>Is there a similar option in Visual Studio 2005? Or something else that would accomplish such a task? An add-in, maybe?</p>
| <p>If you've got Visual Assist, that's got a 'Sort Selected Lines' command that will do what you need.</p>
|
How should I refer to Team Foundation Server builds? <p>I am building a release of my project using tfs build which generates a unique identity for the build in tfs build explorer such as "MyProject_20090122.1" indicating that this is the first build on 2009-01-22. However this is my release 1.0.0 of MyProject. Is there a way to connect the two identifiers or do I have to maintain the mapping externally and elsewhere?</p>
<p>Should I make my version identifier confirm to the way the tfs build names so that my version number for the above should be 1.0.20090122.1?</p>
<p>Is there a way to add comments to a tfsbuild?</p>
<p>How do you do it?</p>
<p>Edit:</p>
<p>As some have suggested the version number can be updated via msbuild and automatically incremented. The question however is how do I determine which version a specific team build is as the version number is not embedded in the build name? Can I control the identifiers for the tfs build name?</p>
| <p>You can override the versioning target to supply your own version number. That way you can conform to x.x.x or whatever style you want. Ideally, x.y.x would mean x is major version, y is minor (point release) and z is a unique build number that increments each build. You might also want to check in again the assemblyinfo.cs with the new updated build number (1.0.1423 for example).</p>
<p>There is a lot of info about this via google. In particular:
<a href="http://geekswithblogs.net/etiennetremblay/archive/2008/10/03/matching-tfs-build-labels-with-custom-build-number.aspx" rel="nofollow">http://geekswithblogs.net/etiennetremblay/archive/2008/10/03/matching-tfs-build-labels-with-custom-build-number.aspx</a></p>
|
ob_get_contents equivalent in asp <p>Working on an old site in asp classic.
I want to write a function that returns some html.
Right now I'm reduced to writing everything in a string.</p>
<p>The downsides are: </p>
<ul>
<li>I have to escape quotes</li>
<li>There is no code completion on the tags nor attributes</li>
</ul>
<p>In php I know how to get the contents of the output buffer with ob_get_contents. Is there an equivalent function in asp classic?</p>
| <p>There is no way to access the Response buffer contents in ASP.</p>
<p>When code generating a HTML content string gets ugly I tend to resort to using an MSXML dom document as a place to create the content. Then return the .XML property of the DOM, not effecient but when done properly much more readable.</p>
<p>Alternatively if you know that the only thing that will be done with the string once returned is to write it to the response then you can just do that directly in the function (or a Sub if you are using VBScript).</p>
<p>Its worth noting that you do this sort of thing in a Sub procedure in ASP:-</p>
<pre><code>Sub WriteRow(first, second)
%>
<tr>
<td><%=Server.HTMLEncode(first)%></td>
<td><%=Server.HTMLEncode(second)%></td>
</tr>
<%
End Sub
</code></pre>
<p>Now you can call WriteRow in a loop. If you have a lot of boilerplate HTML with just a little dynamic content then this may be an option.</p>
|
Should i use @property for Controller Classes variables? <p>Question is should i use properties for my view controllers?</p>
<p>Consider the following case:</p>
<ol>
<li><p>I have a view controller object in my parent class: MyViewController *myVC;</p></li>
<li><p>I don't release this view controller in parent class's <em>dealloc</em> method.</p></li>
<li><p>I use view controller like this:</p>
<pre><code>// Allocate and Initialize view controller
myVC = [[MyViewController alloc] initWithNibName:@"newView" bundle:nil];
// Push View Controller
[self.navigationController pushViewController:myVC animated:YES];
// Release memory
[myVC release];
myVC = nil;
</code></pre></li>
</ol>
<p>Is there any problem with this approach? </p>
| <p>What Brad Larson said. myVC will leak unless you release it in the owning class' dealloc method. Making it a property will not affect this behavior (and where does the itemEditVC var come from?) The only reason to expose it as a property would be if external classes need access to this variable and you want to ensure proper release/retain semantics when this property is modified.</p>
|
Free code coverage tools in .NET for personal project <p>I need a free code coverage tools in .NET for personal project. NCover is bit expensive for person use.</p>
| <p>Discontinued versions of NCover are still free (and still work quite well, in my opinion). Get them <a href="http://www.ncover.com/download/discontinued" rel="nofollow">here</a>.</p>
<p>UPDATE (20th Nov, 2012): I believe <a href="https://github.com/sawilde/opencover" rel="nofollow">OpenCover</a> is now the best option. I've used it with great success on my current .NET 4 project.</p>
|
How to get the data in a System.Object <p>I'm using a COM object that has a function called GetImage.</p>
<p><a href="http://www.pdf-tools.com/asp/products.asp?name=P2IA" rel="nofollow">http://www.pdf-tools.com/asp/products.asp?name=P2IA</a></p>
<p>When I use it in Visual Studio 2008 it returns byte[], but when I use it in RAD Studio 2007 it returns System.Object. How can I get the data from the System.Object into a byte[]?</p>
| <p>There is no data in an instance of Object itself. However since objects inherit from Object they may be referenced by an Object reference. To get data from the instance (assuming there is any) you have to cast the reference to the appropriate type. </p>
|
ASP.NET: How to hide ListBox control vertical scrollbar? <p>I have tried CSS: overflow: auto. It doesn't work. Any way to achieve it?</p>
<p>Do I need to create my custom control as I have seen it on ASP.NET forum?</p>
| <p>I would go with creating a custom control like you mentioned.</p>
<p>What is your desired goal? Creating your own scrollbar to put in the listbox?</p>
|
How can I combine multiple rows into a comma-delimited list in Oracle? <p>I have a simple query:</p>
<pre><code>select * from countries
</code></pre>
<p>with the following results:</p>
<pre><code>country_name
------------
Albania
Andorra
Antigua
.....
</code></pre>
<p>I would like to return the results in one row, so like this:</p>
<pre><code>Albania, Andorra, Antigua, ...
</code></pre>
<p>Of course, I can write a PL/SQL function to do the job (I already did in Oracle 10g), but is there a nicer, preferably non-Oracle-specific solution (or may be a built-in function) for this task?</p>
<p>I would generally use it to avoid multiple rows in a sub-query, so if a person has more then one citizenship, I do not want her/him to be a duplicate in the list.</p>
<p>My question is based on the similar question on <a href="http://stackoverflow.com/questions/180032/how-can-i-combine-multiple-rows-into-a-comma-delimited-list-in-sql-server-2005">SQL server 2005</a>.</p>
<p><strong>UPDATE</strong>:
My function looks like this:</p>
<pre><code>CREATE OR REPLACE FUNCTION APPEND_FIELD (sqlstr in varchar2, sep in varchar2 ) return varchar2 is
ret varchar2(4000) := '';
TYPE cur_typ IS REF CURSOR;
rec cur_typ;
field varchar2(4000);
begin
OPEN rec FOR sqlstr;
LOOP
FETCH rec INTO field;
EXIT WHEN rec%NOTFOUND;
ret := ret || field || sep;
END LOOP;
if length(ret) = 0 then
RETURN '';
else
RETURN substr(ret,1,length(ret)-length(sep));
end if;
end;
</code></pre>
| <p>The <code>WM_CONCAT</code> function (if included in your database, pre Oracle 11.2) or <code>LISTAGG</code> (starting Oracle 11.2) should do the trick nicely. For example, this gets a comma-delimited list of the table names in your schema:</p>
<pre><code>select listagg(table_name, ', ') within group (order by table_name)
from user_tables;
</code></pre>
<p>or</p>
<pre><code>select wm_concat(table_name)
from user_tables;
</code></pre>
<p><a href="http://www.oracle-base.com/articles/misc/StringAggregationTechniques.php">More details/options</a></p>
<p><a href="http://docs.oracle.com/cd/E11882_01/server.112/e10592/functions089.htm">Link to documentation</a> </p>
|
Is it safe to use incremental rebuild for generating release build in visual C++? <p>I sometimes have issues with the incremental rebuild on visual C++ (2003 currently ). Some dependencies does not seem correctly checked and some files aren't build when they should. I suppose thoses issues come from the timestamp approach to incremental rebuild.</p>
<p>I don't consider it a huge issue when building debug build on my desk, however for distribuable build this is a issue.</p>
<p>Is it safe to use incremental build for a build server or is a full build a requirement ?</p>
| <p>You need a build you distrubute to be recreatable again should users experience problems that need investigating.</p>
<p>I would not rely on an incremental build. Also, I would always delete all source from the build machine, and fetch it from scratch from the source control system before building a release. This way, you know you can repeat the build process again by fetching the same source code.</p>
<p>If you use an incremental build, the build will build differently each time because only a subset of the system will need to be built. I think its just good to eliminate as many possible differences between release builds as possible. So, for this reason incremental builds are out.</p>
<p>It's a good idea to label or somehow mark the versions of each source file in the source control system with the version number of the build. This enables you to keep track of the exact source that went into building the release. With a decent source code control system the labels can be used to track down all the changes that were made to the code between one release and the next. This can be a real help when trying to track down a bug that you know was introduced between the two releases.</p>
<p>Incremental builds can still be useful on a development machine when you're not distributing the build, just for saving time during the code/debug/test/repeat development cycle.</p>
|
How to make it so if one copy of a program is running another won't be able to open? <p>How to make it so if one copy of a program is running another won't be able to open?</p>
<p>Or better yet, how to make it so that if one copy is already running, then trying to run another copy will just act as if you maximized the original process?</p>
| <p>Scott Hanselman wrote <a href="http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx" rel="nofollow">a post on doing this sort of thing</a></p>
|
In Django how do i return the total number of items that are related to a model? <p>In Django how can i return the total number of items (count) that are related to another model, e.g the way stackoverflow does a list of questions then on the side it shows the count on the answers related to that question.</p>
<p>This is easy if i get the questionid, i can return all answers related to that question but when am displaying the entire list of question it becomes a bit tricky to display on the side the count showing the total count.</p>
<p>I don't know if am clear but just think how stackoverflow displays its questions with answer,views count next to each question! </p>
| <p><a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#count">QuerySet.count()</a></p>
<p>See also an <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward">example</a> how to build QuerySets of related models.</p>
|
Any Python OLAP/MDX ORM engines? <p>I'm new to the MDX/OLAP and I'm wondering if there is any ORM similar like Django ORM for Python that would support OLAP.</p>
<p>I'm a Python/Django developer and if there would be something that would have some level of integration with Django I would be much interested in learning more about it.</p>
| <p>Django has some OLAP features that are nearing release.</p>
<p>Read <a href="http://www.eflorenzano.com/blog/post/secrets-django-orm/" rel="nofollow">http://www.eflorenzano.com/blog/post/secrets-django-orm/</a></p>
<p><a href="http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html" rel="nofollow">http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html</a>, also</p>
<p>If you have a proper star schema design in the first place, then one-dimensional results can have the following form.</p>
<pre><code>from myapp.models import SomeFact
from collections import defaultdict
facts = SomeFact.objects.filter( dimension1__attribute=this, dimension2__attribute=that )
myAggregates = defaultdict( int )
for row in facts:
myAggregates[row.dimension3__attribute] += row.someMeasure
</code></pre>
<p>If you want to create a two-dimensional summary, you have to do something like the following.</p>
<pre><code>facts = SomeFact.objects.filter( dimension1__attribute=this, dimension2__attribute=that )
myAggregates = defaultdict( int )
for row in facts:
key = ( row.dimension3__attribute, row.dimension4__attribute )
myAggregates[key] += row.someMeasure
</code></pre>
<p>To compute multiple SUM's and COUNT's and what-not, you have to do something like this.</p>
<pre><code>class MyAgg( object ):
def __init__( self ):
self.count = 0
self.thisSum= 0
self.thatSum= 0
myAggregates= defaultdict( MyAgg )
for row in facts:
myAggregates[row.dimension3__attr].count += 1
myAggregates[row.dimension3__attr].thisSum += row.this
myAggregates[row.dimension3__attr].thatSum += row.that
</code></pre>
<p>This -- at first blush -- seems inefficient. You're trolling through the fact table returning lots of rows which you are then aggregating in your application.</p>
<p>In some cases, this may be <em>faster</em> than the RDBMS's native sum/group_by. Why? You're using a simple mapping, not the more complex sort-based grouping operation that the RDBMS often has to use for this. Yes, you're getting a lot of rows; but you're doing less to get them.</p>
<p>This has the disadvantage that it's not so declarative as we'd like. It has the advantage that it's pure Django ORM.</p>
|
Installation file names in Windows Vista <p>I read in this article:</p>
<p><a href="http://technet.microsoft.com/en-us/library/cc709628.aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/cc709628.aspx</a></p>
<p>That Windows detects Installers through file names, following this tip, Is it better to include setup in the file name for the installer</p>
<p>I mean ProductSetup.msi is better than Product.msi???</p>
<p>It's hard to think that Windows does this kind of detection :-)</p>
| <p>This only applies to EXE files. If you've got an MSI file, it's up to the MSI file to specify which parts of the MSI require elevation or not.</p>
|
How to resolve "Only one project can be specified" error from <msbuild> task in CruiseControl.NET <p>I'm trying to use the task in CruiseControl.NET version 1.3.0.2918 with a rather straight forward :</p>
<pre><code> <project name="AppBuilder 1.0 (Debug)">
<workingDirectory>c:\depot\AppBuilder\1.0\</workingDirectory>
<triggers/>
<tasks>
<msbuild/>
</tasks>
</project>
</code></pre>
<p>However, when the project is run it fails with this information in the build log:</p>
<blockquote>
<p>MSBUILD : error MSB1008: Only one
project can be specified. Switch: 1.0</p>
<p>For switch syntax, type "MSBuild
/help"</p>
</blockquote>
<p>When I look at the ccnet.log file I find this:</p>
<blockquote>
<p>Starting process [C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MSBuild.exe] in working
directory [c:\depot\AppBuilder\1.0] with arguments [/nologo "/p:CCNetArtifactDirectory=C:\Program Files\CruiseControl.NET\server\AppBuilder 1.0 (Debug)\Artifacts;CCNetBuildCondition=ForceBuild;CCNetBuildDate=2009-01-22;CCNetBuildTime=09:25:55;CCNetIntegrationStatus=Unknown;CCNetLabel=3;
CCNetLastIntegrationStatus=Failure;CCNetNumericLabel=3;CCNetProject=AppBuilder 1.0 (Debug);CCNetProjectUrl=<a href="http://CISERVER01/ccnet;CCNetRequestSource=jstong">http://CISERVER01/ccnet;CCNetRequestSource=jstong</a>;
CCNetWorkingDirectory=c:\depot\AppBuilder\1.0\" "/l:ThoughtWorks.CruiseControl.MsBuild.XmlLogger,ThoughtWorks.CruiseControl.MsBuild.dll;C:\Program Files\CruiseControl.NET\server\AppBuilder 1.0 (Debug)\Artifacts\msbuild-results.xml"]</p>
</blockquote>
<p>from which I infer that msbuild was run in the correct working directory and that the command line passed to it was: </p>
<blockquote>
<p>/nologo "/p:CCNetArtifactDirectory=C:\Program Files\CruiseControl.NET\server\AppBuilder 1.0 (Debug)\Artifacts;CCNetBuildCondition=ForceBuild;CCNetBuildDate=2009-01-22;CCNetBuildTime=09:25:55;CCNetIntegrationStatus=Unknown;CCNetLabel=3;
CCNetLastIntegrationStatus=Failure;CCNetNumericLabel=3;CCNetProject=AppBuilder 1.0 (Debug);CCNetProjectUrl=<a href="http://CISERVER01/ccnet;CCNetRequestSource=jstong">http://CISERVER01/ccnet;CCNetRequestSource=jstong</a>;
CCNetWorkingDirectory=c:\depot\AppBuilder\1.0\" "/l:ThoughtWorks.CruiseControl.MsBuild.XmlLogger,ThoughtWorks.CruiseControl.MsBuild.dll;C:\Program Files\CruiseControl.NET\server\AppBuilder 1.0 (Debug)\Artifacts\msbuild-results.xml"</p>
</blockquote>
<p>If I run this manually at the command line I get a similiar error.</p>
<p>It appears to me that the isn't passing the correct command line to the MSBuild executable.</p>
<p>Can you spot my error? Or is this version of CruiseControl.NET (1.3.0.2918) broken with respect to the task? </p>
| <p>I think maybe it is your space in the artifact directory path. MSBuild really does not like spaces as it considers it a break between arguments. Can you try an remove the space from that path and see what happens?</p>
|
VerQueryValue Fileversion doesn't match Windows Shell <p>I'm using the <a href="http://www.google.co.uk/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2Fms647464(VS.85).aspx&ei=V4N4SbfNGNzFjAfoq4mzAQ&usg=AFQjCNGKeUAmRnuBiua6Y8uBzbkBFRGQxg&sig2=yInI3Sqsq-PRMuIMPmfGSA" rel="nofollow">VerQueryValue</a> to retrieve strings from a DLL's VersionInfo.</p>
<p>All works fine, except that the FileVersion displayed by Explorer (right-click on file, Properties, Details, "File Version") doesn't match the string I get from the VerQueryValue.</p>
<p>All my other calls to VerQueryValue are working fine, but FileVersion seems to retrieve the same data as ProductVersion. I've tried two different "version info" components written in different languages ( C++ and Delphi), and both exhibit this behaviour, so I don't think it's a bug in my (or their) code.</p>
<p>Two possibilities I can think of: </p>
<ul>
<li>A bug in VerQueryValue</li>
<li>or, the Windows shell actually displays something other than the FileVersion string.</li>
</ul>
<p>Anybody know which it's likely to be?</p>
| <p>Is the lpSubBlock parameter (the 2nd parameter) of VerQueryValue set to the correct value for the locale you're in? For <em>English - United Kingdom</em> this would be:</p>
<pre><code>StringFileInfo\080904E4\FileVersion
</code></pre>
<p><a href="http://techsupt.winbatch.com/TS/T000001050F49.html" rel="nofollow">This page</a> has some more language/character-set identifiers.</p>
|
How do I move service references to their own assembly? <p>A little background:</p>
<p>I'm creating a set of adapters to allow communication with mobile devices over different cellular networks. This will be achieved using a class factory pattern. At least one of the networks requires a service reference to communicate with their devices through a web service.</p>
<p>So far I've got 3 assemblies so far which represent:</p>
<ul>
<li>An assembly which contains the main adapter library: this contains
<ul>
<li>The interface definition for each of the adapters</li>
<li>Base classes </li>
<li>The class factory to instantiate the specified adapter at runtime.</li>
</ul></li>
<li>An assembly for each network adapter implementation.</li>
<li>An assembly that contains my main application.</li>
</ul>
<p>Given that I don't want to be adding service references and their configuration to the main application assembly [as that's not relevant to the main application], how do I force each assembly's service reference to get its configuration from its own app.config?</p>
<p>If I have the service reference configuration in the main app.config, everything works just fine, but if I move the configuration to the adapter's app.config everything stops working throwing the following exception at the point where I new up the Soap1Client.</p>
<blockquote>
<p>"Could not find default endpoint element that references contract 'MobileService.Service1Soap' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element."</p>
</blockquote>
| <p>In the end, I just removed the service reference and added a web reference [i.e. did it the 2.0 way]. For some reason the web reference will access its own app.config instead of the main application's app.config.</p>
<p>Far easier than the alternative...</p>
|
jquery append to front/top of list <p>I have this unordered list</p>
<pre><code><ul>
<li>two</li>
<li>three</li>
</ul>
</code></pre>
<p>Is there a way I can prepend to the unordered list so that it ends up like this?</p>
<pre><code><ul>
<li>ONE</li>
<li>two</li>
<li>three</li>
</ul>
</code></pre>
<p>Notice the "ONE" is added to the FRONT/TOP of the list.</p>
| <pre><code>$("ul").prepend("<li>ONE</li>");
</code></pre>
|
"Property 'Path' does not have a value" <p>I'm using the following xaml to fill the dataContext:</p>
<pre><code>DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}"
</code></pre>
<p>The application works fine, but Cider complains that I must set the Path property.
I'm interested in the entire object, and not a specific property though.</p>
<p>I hope there's a way to get the designer support back!!</p>
| <p>Have a look at section 2.3.8.7 here (you'll need to scroll down a bit):</p>
<p><a href="http://download.microsoft.com/download/A/2/8/A2807F78-C861-4B66-9B31-9205C3F22252/VS2008SP1Readme.htm#Windows%20Presentation%20Foundation%20(WPF)%20Designer%20for%20Visual%20Studio" rel="nofollow">Visual Studio 2008 Service Pack 1 (SP1) Readme</a></p>
<p>Try changing your tag to</p>
<pre><code>DataContext="{Binding RelativeSource={RelativeSource TemplatedParent},Path=.}"
</code></pre>
|
Detect closed pipe in redirected console output in .NET applications <p>The .NET <code>Console</code> class and its default <code>TextWriter</code> implementation (available as <code>Console.Out</code> and implicitly in e.g. <code>Console.WriteLine()</code>) does not signal any error when the application is having its output piped to another program, and the other program terminates or closes the pipe before the application has finished. This means that the application may run for longer than necessary, writing output into a black hole.</p>
<p><strong>How can I detect the closing of the other end of the redirection pipe?</strong></p>
<p>A more detailed explanation follows:</p>
<p>Here are a pair of example programs that demonstrate the problem. <code>Produce</code> prints lots of integers fairly slowly, to simulate the effect of computation:</p>
<pre><code>using System;
class Produce
{
static void Main()
{
for (int i = 0; i < 10000; ++i)
{
System.Threading.Thread.Sleep(100); // added for effect
Console.WriteLine(i);
}
}
}
</code></pre>
<p><code>Consume</code> only reads the first 10 lines of input and then exits:</p>
<pre><code>using System;
class Consume
{
static void Main()
{
for (int i = 0; i < 10; ++i)
Console.ReadLine();
}
}
</code></pre>
<p>If these two programs are compiled, and the output of the first piped to the second, like so:</p>
<pre><code>Produce | Consume
</code></pre>
<p>... it can be observed that <code>Produce</code> keeps on running long after <code>Consume</code> has terminated.</p>
<p>In reality, my <code>Consume</code> program is Unix-style <code>head</code>, and my <code>Produce</code> program prints data which is costly to calculate. I'd like to terminate output when the other end of the pipe has closed the connection.</p>
<p>How can I do this in .NET?</p>
<p>(I know that an obvious alternative is to pass a command-line argument to limit output, and indeed that's what I'm currently doing, but I'd still like to know how to do this since I want to be able to make more configurable judgements about when to terminate reading; e.g. piping through <code>grep</code> before <code>head</code>.)</p>
<p><strong>UPDATE:</strong> It looks horribly like the <code>System.IO.__ConsoleStream</code> implementation in .NET is hard-coded to ignore errors 0x6D (<code>ERROR_BROKEN_PIPE</code>) and 0xE8 (<code>ERROR_NO_DATA</code>). That probably means I need to reimplement the console stream. Sigh...)</p>
| <p>To solve this one, I had to write my own basic stream implementation over Win32 file handles. This wasn't terribly difficult, as I didn't need to implement asynchronous support, buffering or seeking.</p>
<p>Unfortunately, unsafe code needs to be used, but that generally isn't a problem for console applications that will be run locally and with full trust.</p>
<p>Here's the core stream:</p>
<pre><code>class HandleStream : Stream
{
SafeHandle _handle;
FileAccess _access;
bool _eof;
public HandleStream(SafeHandle handle, FileAccess access)
{
_handle = handle;
_access = access;
}
public override bool CanRead
{
get { return (_access & FileAccess.Read) != 0; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return (_access & FileAccess.Write) != 0; }
}
public override void Flush()
{
// use external buffering if you need it.
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
static void CheckRange(byte[] buffer, int offset, int count)
{
if (offset < 0 || count < 0 || (offset + count) < 0
|| (offset + count) > buffer.Length)
throw new ArgumentOutOfRangeException();
}
public bool EndOfStream
{
get { return _eof; }
}
public override int Read(byte[] buffer, int offset, int count)
{
CheckRange(buffer, offset, count);
int result = ReadFileNative(_handle, buffer, offset, count);
_eof |= result == 0;
return result;
}
public override void Write(byte[] buffer, int offset, int count)
{
int notUsed;
Write(buffer, offset, count, out notUsed);
}
public void Write(byte[] buffer, int offset, int count, out int written)
{
CheckRange(buffer, offset, count);
int result = WriteFileNative(_handle, buffer, offset, count);
_eof |= result == 0;
written = result;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32", SetLastError=true)]
static extern unsafe bool ReadFile(
SafeHandle hFile, byte* lpBuffer, int nNumberOfBytesToRead,
out int lpNumberOfBytesRead, IntPtr lpOverlapped);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError=true)]
static extern unsafe bool WriteFile(
SafeHandle hFile, byte* lpBuffer, int nNumberOfBytesToWrite,
out int lpNumberOfBytesWritten, IntPtr lpOverlapped);
unsafe static int WriteFileNative(SafeHandle hFile, byte[] buffer, int offset, int count)
{
if (buffer.Length == 0)
return 0;
fixed (byte* bufAddr = &buffer[0])
{
int result;
if (!WriteFile(hFile, bufAddr + offset, count, out result, IntPtr.Zero))
{
// Using Win32Exception just to get message resource from OS.
Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error());
int hr = ex.NativeErrorCode | unchecked((int) 0x80000000);
throw new IOException(ex.Message, hr);
}
return result;
}
}
unsafe static int ReadFileNative(SafeHandle hFile, byte[] buffer, int offset, int count)
{
if (buffer.Length == 0)
return 0;
fixed (byte* bufAddr = &buffer[0])
{
int result;
if (!ReadFile(hFile, bufAddr + offset, count, out result, IntPtr.Zero))
{
Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error());
int hr = ex.NativeErrorCode | unchecked((int) 0x80000000);
throw new IOException(ex.Message, hr);
}
return result;
}
}
}
</code></pre>
<p><code>BufferedStream</code> can be wrapped around it for buffering if needed, but for console output, the <code>TextWriter</code> will be doing character-level buffering anyway, and only flushing on newlines.</p>
<p>The stream abuses <code>Win32Exception</code> to extract an error message, rather than calling <code>FormatMessage</code> itself.</p>
<p>Building on this stream, I was able to write a simple wrapper for console I/O:</p>
<pre><code>static class ConsoleStreams
{
enum StdHandle
{
Input = -10,
Output = -11,
Error = -12,
}
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
static SafeHandle GetStdHandle(StdHandle h)
{
return new SafeFileHandle(GetStdHandle((int) h), true);
}
public static HandleStream OpenStandardInput()
{
return new HandleStream(GetStdHandle(StdHandle.Input), FileAccess.Read);
}
public static HandleStream OpenStandardOutput()
{
return new HandleStream(GetStdHandle(StdHandle.Output), FileAccess.Write);
}
public static HandleStream OpenStandardError()
{
return new HandleStream(GetStdHandle(StdHandle.Error), FileAccess.Write);
}
static TextReader _in;
static StreamWriter _out;
static StreamWriter _error;
public static TextWriter Out
{
get
{
if (_out == null)
{
_out = new StreamWriter(OpenStandardOutput());
_out.AutoFlush = true;
}
return _out;
}
}
public static TextWriter Error
{
get
{
if (_error == null)
{
_error = new StreamWriter(OpenStandardError());
_error.AutoFlush = true;
}
return _error;
}
}
public static TextReader In
{
get
{
if (_in == null)
_in = new StreamReader(OpenStandardInput());
return _in;
}
}
}
</code></pre>
<p>The final result is that writing to the console output after the other end of the pipe has terminated the connection, results in a nice exception with the message:</p>
<blockquote>
<p>The pipe is being closed</p>
</blockquote>
<p>By catching and ignoring the <code>IOException</code> at the outermost level, it looks like I'm good to go.</p>
|
problem using an instance in a with_statement <p>I've recently started to learn python , and I reached the <strong>with</strong> statement . I've tried to use it with a class instance , but I think I'm doing something wrong . Here is the code :</p>
<pre><code>
from __future__ import with_statement
import pdb
class Geo:
def __init__(self,text):
self.text = text
def __enter__(self):
print "entering"
def __exit__(self,exception_type,exception_value,exception_traceback):
print "exiting"
def ok(self):
print self.text
def __get(self):
return self.text
with Geo("line") as g :
g.ok()
</code></pre>
<p>The thing is that when the interpreter reaches the <strong>ok</strong> method inside the with statement , the following exception is raised :</p>
<pre><code>
Traceback (most recent call last):
File "dec.py", line 23, in
g.ok()
AttributeError: 'NoneType' object has no attribute 'ok'
</code></pre>
<p>Why does the g object have the type NoneType ? How can I use an instance with the <strong>with</strong> statement ?</p>
| <p>Your <code>__enter__</code> method needs to return the object that should be used for the "<code>as g</code>" part of the with statement. See the <a href="http://docs.python.org/reference/compound_stmts.html#with">documentation</a>, where it states:</p>
<ul>
<li>If a target was included in the with statement, the return value from <code>__enter__()</code> is assigned to it.</li>
</ul>
<p>Currently, it has no return statement, so g gets bound to <code>None</code> (the default return value)</p>
|
Command line (or equivalent) tools for .NET development <p>Spending most of my time in Visual Studio and using all the IDE tools, I wish I could spend more time using either of the following.</p>
<ul>
<li>The Command Window in Visual Studio</li>
<li>CMD.EXE</li>
<li><a href="http://en.wikipedia.org/wiki/Cygwin" rel="nofollow">Cygwin</a>, <a href="http://en.wikipedia.org/wiki/MinGW" rel="nofollow">MinGW</a>...</li>
<li>PowerShell.</li>
<li>Scripts?</li>
</ul>
<p>What are your favorite and essential commands to type in, opposed to keyboard shortcuts or clicking around?</p>
| <p>The most critical PowerShell commands are Get-Command (alias gcm) and Get-Member (alias gm). Those two commands allow you to explore and exploit most of the functionality available. Get-Member is great for interactively exploring and working with .NET objects.</p>
<p>The other useful series of commands are:</p>
<pre><code>[System.Reflection.Assembly]::LoadFrom($relativepath)
[System.Reflection.Assembly]::LoadFile($absolutepath)
</code></pre>
<p>which allow you to load other assemblies into PowerShell to work with them.</p>
|
Calling Assembly to get Application Name VB.NET <p>I have a console application (<code>MyProgram.EXE</code>) that references a Utilities assembly.</p>
<p>In my Utilities assembly, I have code that does:</p>
<pre><code>Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim location As String = asm.Location
Dim appName As String = System.IO.Path.GetDirectoryName(location)
Conole.WriteLine("AppName is: {0}", appName)
</code></pre>
<p>When I call it from <code>MyProgram.EXE</code>, I receive "<code>AppName is: Utilities.dll</code>"</p>
<p>What I want is "<code>AppName is: MyProgram.EXE</code>"</p>
<p>What am I doing wrong?</p>
| <p>Use <code>GetEntryAssembly()</code> instead to get the assembly containing the entry point.</p>
<p>The better way to do it is using <code>System.Environment.CommandLine</code> property instead.</p>
<p>Specifically:</p>
<pre><code>Dim location As String = System.Environment.GetCommandLineArgs()(0)
Dim appName As String = System.IO.Path.GetFileName(location)
Conole.WriteLine("AppName is: {0}", appName)
</code></pre>
<p>By the way, you want to use <code>GetFileName</code> instead of <code>GetDirectoryName</code></p>
|
boost::bind with functions that have parameters that are references <p>I noticed that when passing reference parameters to boost bind, those parameters won't act like references. Instead boost creates another copy of the member and the original passed in variable remains unchanged. </p>
<p>When I change the references to pointers, everything works ok.</p>
<p>My question is:</p>
<p>Is it possible to get references to work, or at least give a compiling error when it tries to use reference parameters?</p>
| <p>The <a href="http://www.boost.org/doc/libs/1_37_0/libs/bind/bind.html#with_functions">boost documentation for bind</a> suggests that you can use boost::ref and boost::cref for this.</p>
|
When is it best to change code to match standards? <p>I have recently been put in charge of debugging two different programs which will eventually need to share an XML parsing script, at the minimum. One was written with PureMVC, and another was built from scratch. While it made sence, originally, to write the one from scratch (it saved a good deal of memory, but the memory problems have since been resolved). </p>
<p>Porting the non-PureMVC application will take a good deal of time and effort which does not need to be used, but it will make documentation and code-sharing easier. It will also lower the overall learning curve. With that in mind:</p>
<h2>1. What should be taken into account when considering whether it is best to move things to one standard?</h2>
<p><hr /></p>
<h3>(On a related note)</h3>
<p>Some of the code is a little odd. Because the interpreting App had to convert commands from one syntax to another, it made sense to have an interpreter Object. Because there needed to be communication with the external environment, it made more sense to have one object interact with the environment, and for that to deal with the interpreter <em>exclusively</em>. </p>
<p>Effectively, an anti-Singleton was created. The object would only interface with the interpreter, and that's it. If a member of another class were to try to call one of its public methods, the object would raise an Exception.</p>
<p>There are better ways to accomplish this, but it is definitely a bit odd. There are more standard means of accomplishing the same thing, though they often involve the creation of classes or class files which are extraordinarily large. The only solution which I could find that was standards compliant would involve as much commenting and explanation as is currently required, if not more. Considering this:</p>
<h2>2. If some code is quirky, but effective, is it better to change it to make it less quirky, even if it is made a more unwieldy?</h2>
| <p>In my opinion this type of refactoring is often not considered in schedules and can only be done when there is extra time.</p>
<p>More often than not, the criterion for shipping code is if it works, <strong>not necessarily if it's the best possible code solution</strong>.</p>
<p>So in answer to your question, <strong>I try and refactor when I have time to do so</strong>. Priority One still remains to produce a functional piece of code.</p>
|
Using a Function to create an Object in actionscript 3.0 <p>Since actionscript 3.0 is based on ECMAscript it shares some similarities with javascript. One such similarity that I have been playing around with is creating Objects from functions. </p>
<p>In javascript to create an object,</p>
<pre><code>var student = new Student( 33 );
document.write( student.age );
function Student( age ){
this.age = age;
}
</code></pre>
<p>In actionscript 3.0 Objects are usually created through class, but Objects may be created, like in javascript, through constructer functions.</p>
<pre><code>package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var student = new Student( 33 );
trace( student.age );
}
}
}
function Student( age ) {
this.age = age;
}
</code></pre>
<p>However I get a compile error with the above code</p>
<pre>
Loading configuration file C:\Program Files\Adobe\Flex Builder 3\sdks\3.1.0\frameworks\flex-config.xml
C:\Documents and Settings\mallen\Desktop\as3\Main.as(5): col: 23 Error: Incorrect number of arguments. Expected 0
var student = new Student( 33 );
^
</pre>
<p>I was wondering why this is? To make things even weirder, the following code does work</p>
<pre><code>package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
Student( 33 );
var student = new Student();
trace(student.age);
/* When I add the two lines below, the code wont compile? */
//var student2 = new Student( 33 );
//trace(student2.age);
}
}
}
function Student( age ){
this.age = age;
trace(age);
}
</code></pre>
<p>The output for this code is</p>
<pre>
33
undefined
undefined
</pre>
| <p>Syntactically, this is one area (among many) where the two diverge. ;)</p>
<p>You can create an object using a function:</p>
<pre><code>private var studentName:String = "Joe";
private function init():void
{
var s = new Student("Chris");
trace(s.studentName);
trace(this.studentName);
trace(typeof s);
trace(typeof Student);
s.sayHi();
trace("Hello, " + s.studentName + ". I'm " + studentName + ".");
}
var Student:Function = function(studentName:String):void
{
this.studentName = studentName;
this.sayHi = function():void
{
trace("Hi! I'm " + this.studentName + ".");
};
};
// Chris
// Joe
// object
// function
// Hi! I'm Chris.
// Hello, Chris. I'm Joe.
</code></pre>
<p>... just with a slightly different syntax. The Function class is also dynamic, which means you can graft methods onto its instances at runtime (as I do above with sayHi()), much as you might use JavaScript's "prototype" property. </p>
<p>I'm actually not sure what kinds of annoyances, naming collisions, oddities, etc., you might run into with this approach, since I haven't yet dug deeply into into the docs on it -- but it does work!</p>
|
Where can I find code profiling and/or code coverage modules that work with mod_perl2? <p>Is there a way to get this functionality under mod_perl2?</p>
<p>And can it be triggered via web requests as opposed to the command line? Or do I need to fake whatever $ENV variables and query strings and cookies that my script requires and use the command line somehow?</p>
<p>Google and CPAN searches all seem to point to things that either don't even support mod_perl to begin with, or do, but are old and don't mention mod_perl2.</p>
| <p>Assuming you want to profile your perl code, and not the server itself, the profilers generally do not care if it's mod_perl or mod_perl2, the major difference is in the apache API modules and what you can get apache to do for you using perl.</p>
<p>Take a look at <a href="http://metacpan.org/pod/Devel%3a%3aNYTProf" rel="nofollow">Devel::NYTProf</a>, it's relatively new, actively maintained and improved and provides some very nice profiling features.</p>
|
Main UI windows not updating control -Cross-thread operation not valid <p>Ok..here is the problem</p>
<p>I have a main UI form that has a control container that i can add some buttons item to it,and also i have a backgroundworker object that starts up a listner. When the listner events fire, i would like to create a button in that control container on the main UI form. Everything seems to work fine until i try to add a new control item to that container. I get the following exception</p>
<p>"Cross-thread operation not valid: Control 'RadMagnifier_AcceptReject' accessed from a thread other than the thread it was created on."</p>
<p>the code flows like this</p>
<pre><code>Private Sub Mainform_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.SessionTableAdapter.Fill(Me.BCSSDataSet1.Session)
FormatColumns()
Me.BackgroundWorker2.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker2_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork
Notifications()
End Sub
Private Sub Notifications()
'Start listing for events when event is fired try to add a button to a controls container on the UI thread, and that when i get the problem
End Sub
</code></pre>
| <p>Assuming you moved all UI operations into the RunWorkerCompleted method, it looks like a bug:</p>
<p><a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=116930" rel="nofollow">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=116930</a>
<a href="http://thedatafarm.com/devlifeblog/archive/2005/12/21/39532.aspx" rel="nofollow">http://thedatafarm.com/devlifeblog/archive/2005/12/21/39532.aspx</a></p>
<p>I suggest using the bullet-proof (pseudocode):</p>
<pre><code>if(control.InvokeRequired)
control.Invoke(Action);
else
Action()
</code></pre>
|
java.util.logging.Logger doesn't respect java.util.logging.Level? <p>In plain Java SE 6 environment:</p>
<pre><code>Logger l = Logger.getLogger("nameless");
l.setLevel(Level.ALL);
l.fine("somemessage");
</code></pre>
<p>Nothing shows up in Eclipse console. <em>l.info("")</em> and above works just fine, but anything below <em>fine</em> just doesn't seem to work. What's could be wrong?
TIA.</p>
| <p>Even though the Logger level is set to ALL, the ConsoleHandler (the default Handler on the logger) still has a default level of INFO. This comes from the default logging.properties in *JAVA_HOME/jre/lib*</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.