instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I am using some C++ code that employs the <code>CreateDIBSection</code> function to create a bitmap and return a <code>HBITMAP</code> handle. What is the best way of getting this information into my .NET assembly?</p>
|
<p>The static method <a href="http://msdn.microsoft.com/en-us/library/k061we7x.aspx" rel="nofollow noreferrer">Image.FromHbitmap(IntPtr hbitmap)</a> might be what you are looking for.</p>
|
<p>Have you tried marshalling the byte array for your bitmap across, loading it into a MemoryStream and then using that stream to construct a Bitmap class?</p>
| 44,408
|
<p>I am parsing an Expression Tree. Given a NodeType of ExpressionType.MemberAccess, how do I get the value of that Field? </p>
<p>From C# MSDN docs:
MemberAccess is A node that represents reading from a field or property. </p>
<p>A code snippet would be incredibly, incredibly helpful. Thanks in advance!!!</p>
<p>My code looks something like this: </p>
<pre><code>public static List<T> Filter(Expression<Func<T, bool>> filterExp)
{
//the expression is indeed a binary expression in this case
BinaryExpression expBody = filterExp.Body as BinaryExpression;
if (expBody.Left.NodeType == ExpressionType.MemberAccess)
//do something with ((MemberExpressionexpBody.Left).Name
//right hand side is indeed member access. in fact, the value comes from //aspdroplist.selectedvalue
if (expBody.Right.NodeType == ExpressionType.MemberAccess)
{
//how do i get the value of aspdroplist.selected value?? note: it's non-static
}
//return a list
}
</code></pre>
|
<p>[updated for clarity]</p>
<p>First; cast the <code>Expression</code> to a <code>MemberExpression</code>.</p>
<p>A <code>MemberExpression</code> has two things of interest:</p>
<ul>
<li>.Member - the <code>PropertyInfo</code> / <code>FieldInfo</code> to the member</li>
<li>.Expression - the expression to evaluate to get the "obj" for the .Member</li>
</ul>
<p>i.e. if you can evaluate the <code>.Expression</code> to "obj", and the <code>.Member</code> is a <code>FieldInfo</code>, then you can get the actual value via <code>.GetValue(obj)</code> on the <code>FieldInfo</code> (and <code>PropertyInfo</code> is very similar).</p>
<p>The problem is that evaluating the <code>.Expression</code> is very tricky ;-p</p>
<p>Obviously you get lucky if it turns out to be a <code>ConstantExpression</code> - but in most cases it isn't; it could be a <code>ParameterExpression</code> (in which case you'll need to know the actual parameter value that you want to evaluate), or any other combination of <code>Expression</code>s.</p>
<p>In many cases, a simple (perhaps lazy) option is to use <code>.Compile()</code> to get the .NET framework to do the heavy lifting; you can then evaluate the lambda as a typed delegate (passing in any parameters that the lambda requires). This isn't always an option, however.</p>
<p>To show how complex this is; consider this trivial example (where I've hard-coded at every step, rather than testing etc):</p>
<pre><code>using System;
using System.Linq.Expressions;
using System.Reflection;
class Foo
{
public string Bar { get; set; }
}
static class Program
{
static void Main()
{
Foo foo = new Foo {Bar = "abc"};
Expression<Func<string>> func = () => foo.Bar;
MemberExpression outerMember = (MemberExpression)func.Body;
PropertyInfo outerProp = (PropertyInfo) outerMember.Member;
MemberExpression innerMember = (MemberExpression)outerMember.Expression;
FieldInfo innerField = (FieldInfo)innerMember.Member;
ConstantExpression ce = (ConstantExpression) innerMember.Expression;
object innerObj = ce.Value;
object outerObj = innerField.GetValue(innerObj);
string value = (string) outerProp.GetValue(outerObj, null);
}
}
</code></pre>
|
<p>thank you so so much to Marc Gravell above. I really appreciated his help. </p>
<p>It turns out, in my case. the problem can be solved via:</p>
<pre><code>object value = Expression.Lambda(expBody.Right).Compile().DynamicInvoke();
</code></pre>
<p>Thanks again Mark!</p>
| 29,538
|
<p>Can anyone tell me, where on the web I can find an explanation for Bron-Kerbosch algorithm for clique finding or explain here how it works?</p>
<p>I know it was published in "Algorithm 457: finding all cliques of an undirected graph" book, but I can't find free source that will describe the algorithm.</p>
<p>I don't need a source code for the algorithm, I need an explanation of how it works.</p>
|
<p>Try finding someone with an ACM student account who can give you a copy of the paper, which is here: <a href="http://portal.acm.org/citation.cfm?doid=362342.362367" rel="nofollow noreferrer">http://portal.acm.org/citation.cfm?doid=362342.362367</a></p>
<p>I just downloaded it, and it's only two pages long, with an implementation in Algol 60!</p>
|
<p>For what it is worth, I found a Java implementation: <a href="http://joelib.cvs.sourceforge.net/joelib/joelib2/src/joelib2/algo/clique/BronKerbosch.java?view=markup" rel="nofollow noreferrer">http://joelib.cvs.sourceforge.net/joelib/joelib2/src/joelib2/algo/clique/BronKerbosch.java?view=markup</a></p>
<p>HTH.</p>
| 17,290
|
<p>I'm trying to find <a href="http://httpd.apache.org/docs/2.0/programs/ab.html" rel="noreferrer">ab - Apache HTTP server benchmarking tool</a> for Ubuntu, I'm hoping there's a package I can install for it. I decided I need to do some simple load testing on my applications.</p>
|
<pre><code>% sudo apt-get install apache2-utils</code></pre>
<p>The command-not-found package in Ubuntu provides some slick functionality where if you type a command that can't be resolved to an executable (or bash function or whatever) it will query your apt sources and find a package that contains the binary you tried to execute. So, in this case, I typed <code>ab</code> at the command prompt:</p>
<pre>
<code>
% ab
The program 'ab' is currently not installed. You can install it by typing:
sudo apt-get install apache2-utils
bash: ab: command not found
</code>
</pre>
|
<p>Another way to search for missing files, e.g. if you use zsh, want to disable command-not-found (slows things down when you misstype commandnames), or are looking for a file that is not an executable:</p>
<pre><code>$ sudo aptitude install apt-file
$ sudo apt-file update
$ apt-file search bin/ab
</code></pre>
| 9,209
|
<p>In order to lighten Apache's load people often suggest using lighttpd to serve up static content.</p>
<p>e.g. <a href="http://www.linux.com/feature/51673" rel="noreferrer">http://www.linux.com/feature/51673</a></p>
<p>In this setup Apache passes requests for static content back to lighttpd via mod_proxy, while serving dynamic requests itself.</p>
<p>My question is: how does this reduce the load on the server? Since you still have an apache process spawned for every request that comes in, how does this positively impact the load? From what I can see the size of the Apache process proxying its request through lighttpd is as large as it would be if it were serving the file itself.</p>
|
<p>Running Lighttpd <em>behind</em> Apache to serve static files certainly seems braindead to me. Apache still has to unpack the HTTP packets and parse the request through its parse tree, send proxy requests, and then Lighttpd has to re-unpack, hit the filesystem and send the files back through Apache. I've never heard of anyone using a setup like this in production.</p>
<p>What you will see, is people using a lightweight webserver like <a href="http://nginx.net/" rel="noreferrer">Nginx</a> as a <em>frontend</em> server to serve static files and proxy dynamic URLs to Apache. Or, you can run <a href="http://varnish.projects.linpro.no/" rel="noreferrer">Varnish</a> or <a href="http://www.squid-cache.org/" rel="noreferrer">Squid</a> as a caching reverse proxy frontend, so that all your high-traffic static files (i.e. images, CSS etc. <em>and</em> any dynamic pages you're willing to send cache-friendly headers for) are served out of memory.</p>
<p>Apache can also be optimized to serve static files -- so often when I hear people complain about Apache, they really don't know how to configure it. They've only ever used the prefork MPM (vs. threaded or worker) and have all sorts of modules enabled (usually they're running from a Linux distribution's kitchen-sink Apache package that builds everything as modules and defaults to enabling 10-20 modules or more). Tune Apache by turning off unneeded modules/stupid features like support for .htaccess (which makes Apache scan the filesystem on every request!) first. (You can also run two instances of Apache, with a "light" Apache as frontend that proxies to a "heavy" Apache for dynamic requests ... maybe your frontend is threaded but your backend is prefork because you have to run thread-unsafe external modules like mod_php.)</p>
<p>Re:</p>
<blockquote>
<p>Since you still have an apache process
spawned for every request that comes
in, how does this positively impact
the load? From what I can see the size
of the Apache process proxying its
request through lighttpd is as large
as it would be if it were serving the
file itself.</p>
</blockquote>
<p>If you're spawning processes on every request, then that means you're using the prefork MPM. Keep in mind that when the OS reports memory usage for each of these processes, not all that memory is wired, a lot of those processes are idle. And when you're talking about speed, you're concerned more with request parsing and internal code branches for a given request (how much processing is the server doing?) than with memory usage reported by the OS.</p>
<p>For example, if you enable something like mod_php, then each of those worker processes is going to instantly go up by about 20-40M (depending on what's enabled in your PHP interpreter), but that doesn't mean Apache is using that memory on static requests. Of course if you're optimizing your server for maximum concurrency on small static files, then enabling mod_php would still be very bad, you're not going to be able to fit nearly as many prefork processes into RAM.</p>
<p>I probably could come up with a "nightmare configuration" for Apache that <em>would</em> make it actually slower serving static files than proxying those requests to a backend Lighttpd, but it would involve enabling expensive features like .htaccess in Apache that are disabled in Lighttpd, so it wouldn't really be fair.</p>
|
<p>You don't have an Apache process spawned for each request - static files (images and the like) are fetched directly by lighttpd.</p>
| 21,968
|
<p>I am given a problem where I have been given N nodes in a graph that are interconnected to each other then given a matrix which lists down a node being connected to another (1 if it is, 0 if not). I am wondering how to best approach this problem. I think these are adjacency matrix? But how would I implement that ...</p>
<p>Basically what I am trying to get out of these is find whether a particular node is connected to all other nodes in a given set 'S'. And whether selected items are clique or not...</p>
<p>I'd appreciate any hints.</p>
|
<p>You can implement this using a 2-dimensional array of booleans. So, if node i is connected to node j, then myarray[i][j] would be true. If your edges are not directional, then myarray[j][i] would be true whenever myarray[i][j] is.</p>
<p>This can also be extended to weighted edges by using integers (or another numeric type) instead of booleans as the elements of the array.</p>
|
<p>You might want to use <a href="http://www.sgi.com/tech/stl/bitset.html" rel="nofollow noreferrer">bitset</a> or <a href="http://www.sgi.com/tech/stl/bit_vector.html" rel="nofollow noreferrer">bit_vector</a> instead of bool[][].</p>
<p>If you don't use a jagged array, and your connections are symmetric, consider wrapping with an accessor based on MIN() & MAX() [macros]. Storing the same data in two places is a recipe for pain. Eventually, array[i][j] != array[j][i].</p>
<pre><code>E.g: getValue( int i, int j ) { return array [ MIN(i,j) ] [ MAX(i,j) ] }
</code></pre>
| 45,468
|
<p>I need to send email through an (external) SMTP server from Java however this server will only accept CRAM-MD5 authentication, which is not supported by JavaMail.</p>
<p>What would be a good way to get these emails to send? (It must be in Java.)</p>
|
<p>Here is <a href="http://lists.gnu.org/archive/html/classpathx-javamail/2010-10/msg00004.html" rel="noreferrer">thread</a> which says that you need to add the following property:</p>
<pre><code>props.put("mail.smtp.auth.mechanisms", "CRAM-MD5")
</code></pre>
<p>Also in Geronimo implementation there is <a href="http://geronimo.apache.org/maven/javamail/1.7/geronimo-javamail_1.4_provider/apidocs/org/apache/geronimo/javamail/authentication/CramMD5Authenticator.html" rel="noreferrer">CramMD5Authenticator</a></p>
<p>Hope it helps to resolve this old question.</p>
|
<p><strong>Change:</strong></p>
<pre><code>for (int i=0; i<result.length; i++)
hexString.append(Integer.toHexString(0xFF & result[i]));
</code></pre>
<p><strong>To:</strong></p>
<pre><code>for (int i=0;i < result.length; i++) {
hexString.append(Integer.toHexString((result[i] >>> 4) & 0x0F));
hexString.append(Integer.toHexString(0x0F & result[i]));
}
</code></pre>
| 22,613
|
<p>I'm looking to setup video uploads for users on a site and want to have them viewed through a Flash player. The site is already partially built (by someone else) and I'm wondering what kind of technologies there are to deal with the video files, specifically in PHP.</p>
<p>I'm thinking the files need to be converted to an FLV. After that I think it's just loading the FLV, like an SWF in Flash.</p>
<p>They also want to do mp3's with Flash streaming, so it'd be cool if it could also support mp3's.</p>
|
<p><a href="http://ffmpeg.mplayerhq.hu/" rel="nofollow noreferrer">ffmpeg</a> is the tool for you. It's a major opensource video encoding library that a lot of other tools are based on. It's a bit tricky to use directly, but I think there are a few wrappers around.</p>
|
<p>Use the YouTube API and let them do the heavy lifting for you.</p>
| 35,809
|
<p>Those of us who use multiple languages to solve problems can combine them in a lot of ways. Personally I use PL/SQL, XSLT, JavaScript, and Java plus the pseudo languages HTML, XML, CSS, Ant, and Bash. What do you use? </p>
|
<p>Paraphrasing one of my favorite quotes:</p>
<blockquote>
<p>Always write your code as if it were going to be maintained by a homicidal maniac that knows your home address.</p>
</blockquote>
|
<p>I have a D/MySQL/JavaScript[1]/HTML/CPP[2] app.</p>
<p>[1] compile time D template generated
[2] C pre-processor used to generate apache configs and SQL sprocs</p>
<p>Yes, I <em>am</em> trying to take things to the insane! ;)</p>
| 18,234
|
<p>I'm designing a database table which will hold filenames of uploaded files. What is the maximum length of a filename in NTFS as used by Windows XP or Vista?</p>
|
<p>Individual components of a filename (i.e. each subdirectory along the path, and the final filename) are limited to 255 characters, and the total path length is limited to approximately 32,000 characters.</p>
<p>However, on Windows, you can't exceed <code>MAX_PATH</code> value (259 characters for files, 248 for folders). See <a href="http://msdn.microsoft.com/en-us/library/aa365247.aspx" rel="noreferrer"><a href="http://msdn.microsoft.com/en-us/library/aa365247.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa365247.aspx</a></a> for full details.</p>
|
<p>Actually it is 256, see <em><a href="http://msdn.microsoft.com/en-us/library/ee681827(VS.85).aspx#limits" rel="nofollow noreferrer">File System Functionality Comparison, Limits</a></em>.</p>
<p>To repeat a post on <a href="http://fixunix.com/microsoft-windows/30758-windows-xp-file-name-length-limit.html" rel="nofollow noreferrer">http://fixunix.com/microsoft-windows/30758-windows-xp-file-name-length-limit.html</a></p>
<blockquote>
<p><em>"Assuming we're talking about NTFS and not FAT32, the "255 characters
for path+file" is a limitation of Explorer, not the filesystem itself.
NTFS supports paths up to 32,000 Unicode characters long, with each
component up to 255 characters.</em></p>
<p><em>Explorer -and the Windows API- limits you to 260 characters for the
path, which include drive letter, colon, separating slashes and a
terminating null character. It's possible to read a longer path in
Windows if you start it with a <code>\\</code>"</em></p>
</blockquote>
<p>If you read the above posts you'll see there is a 5th thing you can be certain of:
Finding at least one obstinate computer user! </p>
| 33,326
|
<p>Background: we have a system that was written in an older CMS based on Java back during the 2002-2003 days. We want to keep moving forward with our new stuff, using tomcat, stripes, and sitemesh. We have navigation, layouts, "pods", js, css, etc, that we've taken out of the old CMS and into a few of our new apps so we have consistent look and feel.</p>
<p>We now need some sort of solution to get rid of all the code duplication going on. Our apps are running on the same VM at the moment, but that might change. We need a way for all of our tomcat instances to access some common elements (and those elements may/may not need to do some server side stuff). </p>
<p>The best we've come up with so far is making a fairly standard sitemesh decorator, that uses c:import to get what it needs, and plugs it right in. This solution has some network overhead which could bog it down and introduce a fail point. We've looked at <%@ include file="/something.jsp" %> as well but that seems to be only context relative. We could use c:import and point it at localhost, which seems to be the best solution so far. </p>
<p>Are there other templating/decorating frameworks out there (Tiles?) that could make this simpler? What are we missing?</p>
|
<p>Five things I hate about Java:</p>
<ul>
<li>No first-class functions.</li>
<li>No type inference.</li>
<li>Lack of sane defaults in eg graphics.</li>
<li>NullPointerException not containing more information about what is null.</li>
<li>The proliferation of pointlessly "configurable" frameworks/service provider interfaces/factory classes/dependency injection systems. The configurability is almost never used, DRY is violated egregiously, and code quadruples in size and halves in legibility.</li>
</ul>
<p>I know, I should check out Scala.</p>
|
<p>Perl represents a horrid language.</p>
<ol>
<li>No "public" or "private" or "protected" declarations/definitions.</li>
<li>The "my $variable_name;" does not declare a global outside of a subroutine.</li>
<li>The "my $variable_name;" gets accessed by subroutines but "use strict;" or other "use " creates warnings.</li>
<li>Function prototypes end up unexplained, undemonstrated, unwanted, or some other excuse.</li>
<li>Overzealous symbol use ends up "cool and quick" when reading globs of symbols.</li>
<li>When one gets hot they like to stay hot, and need nothing to cool them.</li>
<li>After a week of Perl, I end up unable to write a function and prototype it.</li>
<li>What exactly is a module and does it actually NEED a ".pm" extension?</li>
<li>If you want to create a public variable and access it from inside a subroutine, how do you accomplish this without creating a warning?</li>
<li>Where do you find some neat scripts that teach one some neat Perl?</li>
</ol>
| 35,754
|
<p>Okay, here's the scenario. I have a utility that processes tons of records, and enters information to the Database accordingly.</p>
<p>It works on these records in multi-threaded batches. Each such batch writes to the same log file for creating a workflow trace for each record. Potentially, we could be making close to a million log writes in a day.</p>
<p>Should this log be made into a database residing on another server? Considerations:</p>
<ol>
<li>The obvious disadvantage of multiple threads writing to the same log file is that the log messages are shuffled amongst each other. In the database, they can be grouped by batch id.</li>
<li>Performance - which would slow down the batch processing more? writing to a local file or sending log data to a database on another server on the same network. Theoretically, the log file is faster, but is there a gotcha here?</li>
</ol>
<p>Are there any optimizations that can be done on either approach?</p>
<p>Thanks.</p>
|
<p>I second the other answers here, <strong>depends on what you are doing with the data</strong>.</p>
<p>We have two scenarios here:</p>
<ol>
<li><p>The majority of the logging is to a DB since admin users for the products we build need to be able to view them in their nice little app with all the bells and whistles.</p></li>
<li><p>We log all of our diagnostics and debug info to file. We have no need for really "prettifying" it and TBH, we don't even often need it, so we just log and archive for the most part.</p></li>
</ol>
<p>I would say if the user is doing anything with it, then log to DB, if its for you, then a file will probably suffice.</p>
|
<p>I think it depends greatly on what you are doing with the log files afterwards.</p>
<p>Of the two operations writing to the log file will be faster - especially as you are suggesting writing to a database on another server.</p>
<p>However if you are then trying to process and search the log files on a regular basis then the best place to do this would be a database.</p>
<p>If you use a logging framework like log4net they often provide simple config file based ways of redirecting input to file or database.</p>
| 4,930
|
<p>In this thread, we look at examples of good uses of <code>goto</code> in C or C++. It's inspired by <a href="https://stackoverflow.com/questions/244445/best-refactoring-for-the-dreaded-while-true-loop#244644">an answer</a> which people voted up because they thought I was joking.</p>
<p>Summary (label changed from original to make intent even clearer):</p>
<pre><code>infinite_loop:
// code goes here
goto infinite_loop;
</code></pre>
<p>Why it's better than the alternatives:</p>
<ul>
<li>It's specific. <code>goto</code> is the
language construct which causes an
unconditional branch. Alternatives
depend on using structures
supporting conditional branches,
with a degenerate always-true
condition.</li>
<li>The label documents the intent
without extra comments.</li>
<li>The reader doesn't have to scan the
intervening code for early <code>break</code>s
(although it's still possible for an
unprincipled hacker to simulate
<code>continue</code> with an early <code>goto</code>).</li>
</ul>
<p><strong>Rules:</strong></p>
<ul>
<li>Pretend that the gotophobes didn't
win. It's understood that the above
can't be used in real code because
it goes against established idiom.</li>
<li>Assume that we have all heard of
'Goto considered harmful' and know
that goto can be used to write
spaghetti code.</li>
<li>If you disagree with an example,
criticize it on technical merit
alone ('Because people don't like
goto' is not a technical reason).</li>
</ul>
<p>Let's see if we can talk about this like grown ups.</p>
<p><strong>Edit</strong></p>
<p>This question seems finished now. It generated some high quality answers. Thanks to everyone,
especially those who took my little loop example seriously. Most skeptics were concerned
by the lack of block scope. As @quinmars pointed out in a comment, you can always put braces around the
loop body. I note in passing that <code>for(;;)</code> and <code>while(true)</code> don't give you the braces
for free either (and omitting them can cause vexing bugs). Anyway, I won't waste any more
of your brain power on this trifle - I can live with the harmless and idiomatic <code>for(;;)</code> and <code>while(true)</code> (just as well if I want to keep my job). </p>
<p>Considering the other responses, I see that many people view <code>goto</code> as something you always
have to rewrite in another way. Of course you can avoid a <code>goto</code> by introducing a loop,
an extra flag, a stack of nested <code>if</code>s, or whatever, but why not consider whether <code>goto</code> is
perhaps the best tool for the job? Put another way, how much ugliness are people prepared to endure to avoid using a built-in language feature for its intended purpose? My take is that
even adding a flag is too high a price to pay. I like my variables to represent things in
the problem or solution domains. 'Solely to avoid a <code>goto</code>' doesn't cut it.</p>
<p>I'll accept the first answer which gave the C pattern for branching to a cleanup block. IMO, this makes the strongest case for a <code>goto</code> of all the posted answers, certainly
if you measure it by the contortions a hater has to go through to avoid it.</p>
|
<p>Heres one trick I've heard of people using. I've never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically. </p>
<pre><code>void foo()
{
if (!doA())
goto exit;
if (!doB())
goto cleanupA;
if (!doC())
goto cleanupB;
/* everything has succeeded */
return;
cleanupB:
undoB();
cleanupA:
undoA();
exit:
return;
}
</code></pre>
|
<p>@Greg:</p>
<p>Why not do your example like this:</p>
<pre><code>void foo()
{
if (doA())
{
if (doB())
{
if (!doC())
{
UndoA();
UndoB();
}
}
else
{
UndoA();
}
}
return;
}
</code></pre>
| 30,485
|
<p>I've been utlising a "web browser control" in desktop based applications (in my case Windows Forms .NET) for a number of years. I mostly use it to create a familiar flow-based user interface that also allows a seamless transition to the internet where required.</p>
<p>I'm really tired of the IE browser control because of the poor quality html it generates on output. Also, I guess that it is really just IE7 behind the scenes and so has many of that browser "issues". Despite this, it is quite a powerful control and provides rich interaction with your desktop app.</p>
<p>So, what other alternatives to the IE browser control are there? I looked at a Mosaic equivalent a year ago but was disappointed with the number of unimplemented features, maybe this has improved recently?</p>
|
<p>hmm..Interestingly </p>
<ol>
<li><a href="http://www.iol.ie/~locka/mozilla/control.htm" rel="nofollow noreferrer">Mozilla</a> seems to provide ActiveX control</li>
<li><a href="http://kmeleon.sourceforge.net/" rel="nofollow noreferrer">K-Melon</a> is another Gecko based browser control</li>
</ol>
|
<p>Popular layout engines:</p>
<ol>
<li>Mozilla Gecko</li>
<li>KHTML</li>
<li>WebKit (based on KHTML)</li>
</ol>
<p>Though I'm not sure how easy it is to embed those in a .Net app.</p>
| 8,631
|
<p>I have 50+ kiosk style computers that I want to be able to get a status update, from a single computer, on demand as opposed to an interval. These computers are on a LAN in respect to the computer requesting the status.</p>
<p>I researched WCF however it looks like I'll need IIS installed and I would rather not install IIS on 50+ Windows XP boxes -- so I think that eliminates using a webservice unless it's possible to have a WinForm host a webservice?</p>
<p>I also researched using System.Net.Sockets and even got a barely functional prototype going however I feel I'm not skilled enough to make it a solid and reliable system. Given this path, I would need to learn more about socket programming and threading.</p>
<p>These boxes are running .NET 3.5 SP1, so I have complete flexibility in the .NET version however I'd like to stick to C#.</p>
<p>What is the best way to implement this? Should I just bite the bullet and learn Sockets more or does .NET have a better way of handling this?</p>
<p>edit:
I was going to go with a two way communication until I realized that all I needed was a one way communication.</p>
<p>edit 2:
I was avoiding the traditional server/client and going with an inverse because I wanted to avoid consuming too much bandwidth and wasn't sure what kind of overhead I was talking about. I was also hoping to have more control of the individual kiosks. After looking at it, I think I can still have that with WCF and connect by IP (which I wasn't aware I could connect by IP, I was thinking I would have to add 50 webservices or something).</p>
|
<p>Unless you have plans to scale this to several thousand clients I don't think WCF performance will even be a fringe issue. You can easily host WCF services from windows services or Winforms applications, and you'll find getting something working with WCF will be fairly simple once you get the key concepts.</p>
<p>I've deployed something similar with around 100-150 clients with great success.</p>
<p>There's plenty of resources out on the web to get you started - here's one to get you going:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa480190.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa480190.aspx</a></p>
|
<p>For me its is better to learn networking.. or the manual way of socket communication.. web services are mush slower because it contains metadata..</p>
<p>your clients and the servers can transform to multithreaded application. just imitate the request and response architecture. it is much easy to implement a network application like this..</p>
| 29,425
|
<p>Let's say I have a class</p>
<pre><code>public class ItemController:Controller
{
public ActionResult Login(int id)
{
return View("Hi", id);
}
}
</code></pre>
<p>On a page that is not located at the Item folder, where <code>ItemController</code> resides, I want to create a link to the <code>Login</code> method. So which <code>Html.ActionLink</code> method I should use and what parameters should I pass?</p>
<p>Specifically, I am looking for the replacement of the method </p>
<pre><code>Html.ActionLink(article.Title,
new { controller = "Articles", action = "Details",
id = article.ArticleID })
</code></pre>
<p>that has been retired in the recent ASP.NET MVC incarnation. </p>
|
<p>I think what you want is this:</p>
<h2>ASP.NET MVC1</h2>
<pre><code>Html.ActionLink(article.Title,
"Login", // <-- Controller Name.
"Item", // <-- ActionMethod
new { id = article.ArticleID }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
</code></pre>
<p>This uses the following method ActionLink signature:</p>
<pre><code>public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string controllerName,
string actionName,
object values,
object htmlAttributes)
</code></pre>
<h2>ASP.NET MVC2</h2>
<p><em>two arguments have been switched around</em></p>
<pre><code>Html.ActionLink(article.Title,
"Item", // <-- ActionMethod
"Login", // <-- Controller Name.
new { id = article.ArticleID }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
</code></pre>
<p>This uses the following method ActionLink signature:</p>
<pre><code>public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object values,
object htmlAttributes)
</code></pre>
<h2>ASP.NET MVC3+</h2>
<p><em>arguments are in the same order as MVC2, however the id value is no longer required:</em></p>
<pre><code>Html.ActionLink(article.Title,
"Item", // <-- ActionMethod
"Login", // <-- Controller Name.
new { article.ArticleID }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
</code></pre>
<p>This avoids hard-coding any routing logic into the link.</p>
<pre><code> <a href="/Item/Login/5">Title</a>
</code></pre>
<p>This will give you the following html output, assuming:</p>
<ol>
<li><code>article.Title = "Title"</code></li>
<li><code>article.ArticleID = 5</code></li>
<li>you still have the following route defined</li>
</ol>
<p>.
.</p>
<pre><code>routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
</code></pre>
|
<p>This type use:</p>
<p>@Html.ActionLink("MainPage","Index","Home")</p>
<p>MainPage : Name of the text
Index : Action View
Home : HomeController</p>
<p>Base Use ActionLink</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<meta name="viewport" content="width=device-width" />
<title>_Layout</title>
<link href="@Url.Content("~/Content/bootsrap.min.css")" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div class="col-md-12">
<button class="btn btn-default" type="submit">@Html.ActionLink("AnaSayfa","Index","Home")</button>
<button class="btn btn-default" type="submit">@Html.ActionLink("Hakkımızda", "Hakkimizda", "Home")</button>
<button class="btn btn-default" type="submit">@Html.ActionLink("Iletişim", "Iletisim", "Home")</button>
</div>
@RenderBody()
<div class="col-md-12" style="height:200px;background-image:url(/img/footer.jpg)">
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| 24,458
|
<p>I believe that Agile is nothing but another implementation of Spiral Model. I am a big supporter of Spiral (The spiral model is a software development process combining elements of both design and prototyping-in-stages, in an effort to combine advantages of top-down and bottom-up concepts) since its beginnings and have seen that lot of projects implement Spiral without knowing that they are operating in a Spiral world. Since the day Agile started gaining popularity the concept of spiral started getting overlooked a little bit. I am sure that for complex projects spiral is still the best alternative but I would like to get a better understanding of the similarities and differences between Agile and Spiral techniques. Can anyone explain their differences/similarities?</p>
|
<p>Agile <strong>is</strong> spiral. Totally. In part, the name was changed for marketing purposes.</p>
<p>The problem is that spiral tends to imply "big design up front" -- where you plan out many spirals, each in order of risk. Spiral, however, isn't Agile -- it's just incremental execution in order of risk.</p>
<p>One big distinction that Agile adds is the "don't overplan things you can't know yet."
Agile <em>is</em> spiral, but you create detailed plans for just <em>one</em> increment at a time.</p>
<p>Agile adds a lot of other things, also. Spiral is a very technical approach. Agile, however, recognizes that technology is built by people. The <a href="http://agilemanifesto.org/" rel="noreferrer">Agile Manifesto</a> has four principles that are above and beyond the Boehm's simple risk management approach.</p>
|
<p>First Agile is actually a number of different processes that follow a similar philosophy. One of the philosophy's that makes it different is that each iteration produces a working product. It could be described as iterative and incremental. A lot of emphasis is placed on the working product and on testing. In many agile models testing comes before coding.</p>
<p>In the spiral model the number of iterations are fixed, while each phase of an agile model may consist of any number of iterations.</p>
<p>You are right that there are similarities but the underlying philosophy makes the difference. This <a href="http://en.wikipedia.org/wiki/Agile_software_development" rel="nofollow noreferrer">page</a> explains in more detail and compares agile to other methods.</p>
<p>You can say that agile processes are Use Case driven...placing a lot of emphasis on people, the end user.</p>
| 31,641
|
<p>I am trying to refactor some code I have for software that collects current status of agents in a call queue. Currently, for each of the 6 or so events that I listen to, I check in a Mnesia table if an agent exists and change some values in the row depending on the event or add it as new if the agent doesn't exist. Currently I have this Mnesia transaction in each event and of course that is a bunch of repeated code for checking the existence of agents and so on. </p>
<p>I'm trying to change it so that there is one function like <em>change_agent/2</em> that I call from the events that handles this for me. </p>
<p>My problems are of course records.... I find no way of dynamically creating them or merging 2 of them together or anything. Preferably there would be a function I could call like:</p>
<pre><code>change_agent("001", #agent(id = "001", name = "Steve")).
change_agent("001", #agent(id = "001", paused = 0, talking_to = "None")).
</code></pre>
|
<p>I wrote some code a while ago that merges two records. Is not entirely dynamic, but whith macros you could easily use it for several records.</p>
<p>It works like this: The merge/2 function takes two records and converts them to lists together with the empty record for reference (the record type is defined at compile time, and must be. This is the "undynamic" part). These are then run through the generic function merge/4 which works with lists and takes elements from A if they are defined, otherwise from B if they are defined, or lastly from Default (which is always defined).</p>
<p>Here's the code (please excuse StackOverflow's poor Erlang syntax highlighting):</p>
<pre><code>%%%----------------------------------------------------------------------------
%%% @spec merge(RecordA, RecordB) -> #my_record{}
%%% RecordA = #my_record{}
%%% RecordB = #my_record{}
%%%
%%% @doc Merges two #my_record{} instances. The first takes precedence.
%%% @end
%%%----------------------------------------------------------------------------
merge(RecordA, RecordB) when is_record(RecordA, my_record),
is_record(RecordB, my_record) ->
list_to_tuple(
lists:append([my_record],
merge(tl(tuple_to_list(RecordA)),
tl(tuple_to_list(RecordB)),
tl(tuple_to_list(#my_record{})),
[]))).
%%%----------------------------------------------------------------------------
%%% @spec merge(A, B, Default, []) -> [term()]
%%% A = [term()]
%%% B = [term()]
%%% Default = [term()]
%%%
%%% @doc Merges the lists `A' and `B' into to a new list taking
%%% default values from `Default'.
%%%
%%% Each element of `A' and `B' are compared against the elements in
%%% `Default'. If they match the default, the default is used. If one
%%% of them differs from the other and the default value, that element is
%%% chosen. If both differs, the element from `A' is chosen.
%%% @end
%%%----------------------------------------------------------------------------
merge([D|ATail], [D|BTail], [D|DTail], To) ->
merge(ATail, BTail, DTail, [D|To]); % If default, take from D
merge([D|ATail], [B|BTail], [D|DTail], To) ->
merge(ATail, BTail, DTail, [B|To]); % If only A default, take from B
merge([A|ATail], [_|BTail], [_|DTail], To) ->
merge(ATail, BTail, DTail, [A|To]); % Otherwise take from A
merge([], [], [], To) ->
lists:reverse(To).
</code></pre>
<p>Feel free to use it in any way you want.</p>
|
<p>It is difficult to write generic access functions for records.
One workaround for this is the <a href="http://forum.trapexit.org/viewtopic.php?p=21790#21790" rel="nofollow noreferrer">'exprecs'</a> library, which
will generate code for low-level record access functions.</p>
<p>The thing you need to do is to add the following lines to
a module:</p>
<pre><code>-compile({parse_transform, exprecs}).
-export_records([...]). % name the records that you want to 'export'
</code></pre>
<p>The naming convention for the access functions may look strange, but was inspired by a proposal from Richard O'Keefe. It is, at least, consistent, and unlikely to clash with existing functions. (:</p>
| 8,762
|
<p>I am trying to program a small server+client in Javascript on Firefox, using XPCOM.</p>
<p>To get the HTTP message in Javascript, I am using the nsIScriptableInputStream interface.
This f**ing component through the read() method randomly cut the message and I cannot make it reliable.</p>
<p>Is anybody know a solution to get reliably the information? (I already tried a binary stream, same failure.)</p>
<p>J.</p>
|
<p>I had the same problem with unreliability... I ended up using XMLHTTPRequest, which when used from the XPCOM component can do cross site requests. The second part of the <a href="http://developer.mozilla.org/en/XMLHttpRequest" rel="nofollow noreferrer">docs</a> detail how to instantiate the XPCOM version.</p>
<p>If you're looking to serve HTTP request I'd take a look at the <a href="https://addons.mozilla.org/en-US/firefox/addon/3002" rel="nofollow noreferrer">POW</a> source code and the use of <a href="http://www.xulplanet.com/tutorials/mozsdk/serverpush.php" rel="nofollow noreferrer">server sockets</a>, which implements a basic HTTP server in JavaScript. Also check out <a href="http://mxr.mozilla.org/mozilla/source/netwerk/test/httpserver/httpd.js" rel="nofollow noreferrer">httpd.js</a></p>
|
<p>If you control the protocol (that is, both the client and server) I would highly recommend using Javascript/JSON for your server-to-client messages. The client can open a stream either via dynamically adding a <script> tag to the DOM. The server can then send a stream of Javascript commands like:</p>
<pre><code>receiveMsg({type:"text", content:"this is my message"});
</code></pre>
<p>Then the client just needs to define a receiveMsg function. This allows you to rely on fast browser code to parse the message and determine where the end of each message is, at which point it will call your handler for you.</p>
<p>Even if you're working with an existing HTTP protocol and can't use JSON, is there some reason you can't use XMLHttpRequest? I would expect it to be more stable than some poorly documented Firefox-specific XPCOM interface.</p>
<p>--Chouser</p>
| 9,857
|
<p>The Weblogic servers we are using have been configured to allow JNDI datasource names like "appds".</p>
<p>For development (localhost), we might be running Tomcat and when declared in the <context> section of server.xml, Tomcat will hang JNDI datasources on "java:comp/env/jdbc/*" in the JNDI tree.</p>
<p><strong>Problem:</strong> in Weblogic, the JNDI lookup is "appds" whilst in Tomcat, it seems that that I must provide the formal "java:comp/env/jdbc/appds". I'm afraid the Tomcat version is an implicit standard but unfortunately, I can't change Weblogic's config ... so that means we end up with two different spring config files (we're using spring 2.5) to facilitate the different environments.</p>
<p>Is there an elegant way to address this. Can I look JNDI names up directly in Tomcat? Can Spring take a name and look in both places? Google searches or suggestions would be great.</p>
|
<p><code>JndiLocatorSupport</code> has a property <code>resourceRef</code>. When setting this true, "java:comp/env/" prefix will be prepended automatically. So I believe it would be correct to differentiate this parameter when moving from Tomcat to Weblogic.</p>
|
<p>My application also had a similar problem and this is how I solved it:</p>
<p>1) <code>WEB-INF/classes/application.properties</code> contains the entry:</p>
<pre>
ds.jndi=java:comp/env/jdbc/tcds
</pre>
<p>2) On the WLS machine, I have an entry in the <code>/etc/sysenv</code> file:</p>
<pre>
ds.jndi=wlsds
</pre>
<p>3) I configured spring to lookup the JNDI vis the property <code>${ds.jndi}</code>, using a <code>PropertyPlaceholderConfigurer</code> bean with <code>classpath:application.properties</code> and <code>file:/etc/sysenv</code> as locations. I also set the <code>ignoreResourceNotFound</code> to <code>true</code> so that developers need not have <code>/etc/sysenv</code> on their machines.</p>
<p>4) I run an integration test using Cargo+Jetty and I could not properly set up a JNDI environment there. So I have a fallback <code>BasicDataSource</code> configured too using the <code>defaultObject</code> property of <code>JndiObjectFactoryBean</code>.</p>
| 6,992
|
<p>How are you supposed to unit test a web service in C# with Visual Studio 2008? When I generate a unit test it adds an actual reference to the web service class instead of a web reference. It sets the attributes specified in:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms243399(VS.80).aspx#TestingWebServiceLocally" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms243399(VS.80).aspx#TestingWebServiceLocally</a></p>
<p>Yet, it will complete without executing the test. I attempted to add the call to <code>WebServiceHelper.TryUrlRedirection(...)</code> but the call does not like the target since it inherits from <code>WebService</code>, not <code>WebClientProtocol</code>.</p>
|
<p>What I usually do is not test directly against the web-service, but to try and put as little code as possible in the service, and call a different class which does all the real work. Then I write unit tests for that other class. It turns out that class can sometimes be useful outside of the web-service context, so this way - you gain twice.</p>
|
<p>Above my web method unit tests, I have the following:</p>
<pre><code>// TODO: Ensure that the UrlToTest attribute specifies a URL to an ASP.NET page (for example,
// http://.../Default.aspx). This is necessary for the unit test to be executed on the web server,
// whether you are testing a page, web service, or a WCF service.
[HostType("ASP.NET")]
[UrlToTest("http://localhost/MyWebService")]
</code></pre>
<p>In addition to the usual:</p>
<pre><code>[TestMethod()]
[DeploymentItem("MyWebService.dll")]
</code></pre>
<p>This code came about from using the Visual Studio 2008 Unit Test Wizard.</p>
| 48,616
|
<p>I have a very strange bug cropping up right now in a fairly massive C++ application at work (massive in terms of CPU and RAM usage as well as code length - in excess of 100,000 lines). This is running on a dual-core Sun Solaris 10 machine. The program subscribes to stock price feeds and displays them on "pages" configured by the user (a page is a window construct customized by the user - the program allows the user to configure such pages). This program used to work without issue until one of the underlying libraries became multi-threaded. The parts of the program affected by this have been changed accordingly. On to my problem. </p>
<p>Roughly once in every three executions the program will segfault on startup. This is not necessarily a hard rule - sometimes it'll crash three times in a row then work five times in a row. It's the segfault that's interesting (read: painful). It may manifest itself in a number of ways, but most commonly what will happen is function A calls function B and upon entering function B the frame pointer will suddenly be set to 0x000002. Function A:</p>
<pre><code> result_type emit(typename type_trait<T_arg1>::take _A_a1) const
{ return emitter_type::emit(impl_, _A_a1); }
</code></pre>
<p>This is a simple signal implementation. impl_ and _A_a1 are well-defined within their frame at the crash. On actual execution of that instruction, we end up at program counter 0x000002. </p>
<p>This doesn't always happen on that function. In fact it happens in quite a few places, but this is one of the simpler cases that doesn't leave that much room for error. Sometimes what will happen is a stack-allocated variable will suddenly be sitting on junk memory (always on 0x000002) for no reason whatsoever. Other times, that same code will run just fine. So, my question is, what can mangle the stack so badly? What can actually change the value of the frame pointer? I've certainly never heard of such a thing. About the only thing I can think of is writing out of bounds on an array, but I've built it with a stack protector which should come up with any instances of that happening. I'm also well within the bounds of my stack here. I also don't see how another thread could overwrite the variable on the stack of the first thread since each thread has it's own stack (this is all pthreads). I've tried building this on a linux machine and while I don't get segfaults there, roughly one out of three times it will freeze up on me. </p>
|
<p>Stack corruption, 99.9% definitely.</p>
<p>The smells you should be looking carefully for are:-</p>
<ul>
<li>Use of 'C' arrays</li>
<li>Use of 'C' strcpy-style functions</li>
<li>memcpy</li>
<li>malloc and free</li>
<li>thread-safety of anything using pointers</li>
<li>Uninitialised POD variables.</li>
<li>Pointer Arithmetic</li>
<li>Functions trying to return local variables by reference</li>
</ul>
|
<p>Is something meaning to assign a value of 2 to a variable but instead is assigning its address to 2?</p>
<p>The other details are lost on me but "2" is the recurring theme in your problem description. ;)</p>
| 31,399
|
<p>I'm using Microsoft Visual C++ 2008 Express, and have a pretty annoying problem. It doesn't seem to happen in XP but in Vista I can't find a way around it. Whenever I declare variables non-dynamically, if their combined size exceeds about 30mb, the program will crash immediately at start-up. I know that Vista limits non-Win32 apps to 32mb of memory, but I don't think that's my issue. I'm using the Microsoft compiler, and it happens regardless if it's a win32 console app or a win32 window app. I just declare like...</p>
<pre><code>int foo[1000][1000]
</code></pre>
<p>...or any combination of variables resulting in a similar size anywhere, and that's good-bye-application. Funny thing is, about 25 % of the times it runs even though this error exists. Am I missing some fundamental programming thingy here? Is static allocation obsolete? Am I going to have to redo the entire application to make use of dynamic allocation?</p>
|
<blockquote>
<p>Is static allocation obsolete? </p>
</blockquote>
<p>You're not doing <em>static</em> allocation - you're doing <em>automatic</em> allocation and as the others have said, you're running out of stack.</p>
<p>There are basically three common ways to reserve space for data in C++:</p>
<ol>
<li><p>On the stack - these are called 'automatic variables', and they're what ordinary function-local variables are. Assuming your "int foo[][]" is local to main(), then this is what this is. Automatic data is limited by the available stack size, but it's <em>very</em> fast to allocate (basically zero time).</p></li>
<li><p>Statically - these are either function-local or class variables which are proceeded by the word 'static', or they're variables defined outside functions or classes scope. Static data is reserved by the compiler There's no allocation time overhead, but the memory is reserved for the entire run-time of the application.</p></li>
<li><p>On the heap - these are allocated with 'new' or 'malloc' or some mechanism which makes those calls internally. Allocation and release are slow compared with the first two, but you can have as much memory as the system will give you, and you can return it when you've finished with it.</p></li>
</ol>
<p>There are subtle variations on these three - for example alloca is a hybrid of 1 & 3, but these are the basics.</p>
|
<p>The problem is that non-dynamically allocated variables in methods are allocated on the stack, and the maximum stack size is MUCH less than the total available memory. I think it's around 30MB in Windows, yes. What you have done here is, ironically, this very site's namesake. A Stack Overflow.</p>
<p>Edit: According to <a href="http://www.cs.nyu.edu/exact/core/doc/stackOverflow.txt" rel="nofollow noreferrer">http://www.cs.nyu.edu/exact/core/doc/stackOverflow.txt</a> ,Window's maximum stack size is 32MB.</p>
| 44,424
|
<p>Using jQuery, <strong>how do you match elements that are prior to the current element in the DOM tree?</strong> Using <code>prevAll()</code> only matches previous siblings.</p>
<p>eg:</p>
<pre><code><table>
<tr>
<td class="findme">find this one</td>
</tr>
<tr>
<td><a href="#" class="myLinks">find the previous .findme</a></td>
</tr>
<tr>
<td class="findme">don't find this one</td>
</tr>
</table>
</code></pre>
<p>In my specific case, I'll be searching for the <em>first</em> <code>.findme</code> element prior to the link clicked.</p>
|
<p>Ok, here's what I've come up with - hopefully it'll be useful in many different situations. It's 2 extensions to jQuery that I call <code>prevALL</code> and <code>nextALL</code>. While the standard <code>prevAll()</code> matches previous siblings, <code>prevALL()</code> matches ALL previous elements all the way up the DOM tree, similarly for <code>nextAll()</code> and <code>nextALL()</code>.</p>
<p>I'll try to explain it in the comments below:</p>
<pre><code>// this is a small helper extension i stole from
// http://www.texotela.co.uk/code/jquery/reverse/
// it merely reverses the order of a jQuery set.
$.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
// create two new functions: prevALL and nextALL. they're very similar, hence this style.
$.each( ['prev', 'next'], function(unusedIndex, name) {
$.fn[ name + 'ALL' ] = function(matchExpr) {
// get all the elements in the body, including the body.
var $all = $('body').find('*').andSelf();
// slice the $all object according to which way we're looking
$all = (name == 'prev')
? $all.slice(0, $all.index(this)).reverse()
: $all.slice($all.index(this) + 1)
;
// filter the matches if specified
if (matchExpr) $all = $all.filter(matchExpr);
return $all;
};
});
</code></pre>
<p>usage:</p>
<pre><code>$('.myLinks').click(function() {
$(this)
.prevALL('.findme:first')
.html("You found me!")
;
// set previous nodes to blue
$(this).prevALL().css('backgroundColor', 'blue');
// set following nodes to red
$(this).nextALL().css('backgroundColor', 'red');
});
</code></pre>
<hr>
<p><em>edit</em> - function rewritten from scratch. I just thought of a much quicker and simpler way to do it. Take a look at the edit history to see my first iteration.</p>
<p><em>edit again</em> - found an easier way to do it!</p>
|
<p>had the same problem, heres what i came up with. my function uses <a href="http://www.w3schools.com/jsref/met_node_comparedocumentposition.asp" rel="nofollow">compareDocumentPosition</a>. dont know how it compares to the other solutions in terms of performance though.</p>
<pre><code>$.fn.findNext = function ( selector ) {
var found, self = this.get(0);
$( selector )
.each( function () {
if ( self.compareDocumentPosition( this ) === 4 ){
found = this;
return false;
}
})
return $(found);
}
</code></pre>
<p>of course one could change this quite easily to fetch ALL elements following the calling element.</p>
<pre><code>$.fn.nextALL= function ( selector ) {
var found = [], self = this.get(0);
$( selector )
.each( function () {
if ( self.compareDocumentPosition( this ) === 4 )
found.push(this);
})
return $(found);
}
</code></pre>
<h3>EDIT: streamlined version</h3>
<pre><code>$.fn.findNext = function( s ){
var m = this[0], f=function(n){return m.compareDocumentPosition(n)===4;};
return this.pushStack( $(s).get().filter(f) );
}
</code></pre>
| 41,792
|
<p>I've got a JScript error on my page. I know where the error's happening, but I'm attempting to decipher the JScript on that page (to figure out where it came from -- it's on an ASPX page, so any number of user controls could have injected it).</p>
<p>It'd be easier if it was indented properly. Are there any free JScript reformatters for Windows?</p>
|
<p>You really should use Firebug or some similar debugging tool to actually <em>find</em> the problem, but, if you want to just format your JavaScript code, <a href="http://javascript.about.com/library/blformat.htm" rel="nofollow noreferrer">here's a reformatter I found on Google</a>.</p>
|
<p>How about if you just run Firebug, it will tell you what the error is and will take you to where it is.</p>
<p>Tools like phpDesigner (there's a free trial) have a code beautifier that will work on JavaScript, but nothing beats the good old TAB key (and shift tab to remove junk indention) :P</p>
| 46,524
|
<p>My application draws all its own window borders and decorations. It works fine with Windows taskbars that are set to auto-hide, except when my application window is maximized. The taskbar won't "roll up". It will behave normally if I have the application not maximized, even when sized all the way to the bottom of the screen. It even works normally if I just resize the window to take up the entire display (as though it was maximized). </p>
|
<p>I found the problem. My application was handling the WM_GETMINMAXINFO message, and was overriding the values in the parameter MINMAXINFO record. The values that were in the record were inflated by 7 (border width) the screen pixel resolution. That makes sense in that when maximized, it pushes the borders of the window beyond the visible part of the screen. It also set the ptMaxPosition (point that the window origin is set to when maximized) to -7, -7. My application was setting that to 0,0, and the max height and width to exactly the screen resolution size (not inflated). Not sure why this was done; it was written by a predecessor. If I comment out that code and don't modify the MINMAXINFO structure, the Auto-hide works.</p>
<p>As to why, I'm not entirely sure. It's possible that the detection for popping up an "autohidden" taskbar is hooked into the mechanism for handling WM_MOUSEMOVE messages, and not for WM_NCMOUSEMOVE. With my application causing the maximize to park my border right on the bottom of the screen, I would have been generating WM_NCMOUSEMOVE events; with the MINMAXINFO left alone, I would have been generating WM_MOUSEMOVE.</p>
|
<p>This is dependant on whether 'Keep the taskbar on top of other windows' is checked on the taskbar properties. If it's checked then the taskbar will appear.</p>
<p>But don't be tempted to programmatically alter this setting on an end users machine just to suit your needs, it's considered rude and bad practice. Your app should fit whatever environment it gets deployed to.</p>
| 16,573
|
<p>When modelling for 3D printing, can I distinguish somehow the type of infill in various areas of the model? Say there may be some areas in the model where I want 100% infill (maximum strength) but some areas where the infill can be less (maybe 25%).</p>
<p>I am new to 3D printing, doing my first model (enclosure for electronics - camera module). Using tinkercad.com only so far. Places where 100% infill is wanted are usually walls of the case and "threads" for the bolts but I want to make the enclosure as stiff as possible as a whole so I am thinking about using some sparse infill in the "free space" inside of the enclosure (so that it does not break so easily when it falls to the ground etc). I just do not know how to define this within the model.</p>
|
<p>To achieve additional localised stiffness, you can also insert small voids (gaps) inside the model. These become double thickness walls once sliced and can be used to support things like screw holes.</p>
<p>See the 'negative' parts used with a cube, and the sliced result here:
<a href="https://i.stack.imgur.com/eULwV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eULwV.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/z7uzX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z7uzX.png" alt="enter image description here"></a></p>
|
<p>I found out I misunderstood some principles of designing/modelling for 3D printing.</p>
<p>I designed my object for 100% infill which is not really necessary. It turned out that one does not mostly have to take care of the infill % and just model the object for example as solid 3D cube and the printing service will then take care of it to print well, hopefully slicing it well for printing and choosing the correct infill percentage.</p>
<p>So instead of designing a "hollow" cube with 3mm thick walls filled with 100% infill and free space inside, one can design a solid cube and the printing service will then print it "somehow" - they may make the walls only 1 mm thick but fill the inside of the cube with 10% infill which may work just fine for final object stiffness etc.</p>
| 1,050
|
<p>I was reading an article on MSDN Magazine about using the <a href="http://msdn.microsoft.com/en-us/magazine/cc700332.aspx" rel="noreferrer">Enumerable class in LINQ</a> to generate a random array. The article uses VB.NET and I'm not immediately sure what the equivalent is in C#:</p>
<pre><code>Dim rnd As New System.Random()
Dim numbers = Enumerable.Range(1, 100). _
OrderBy(Function() rnd.Next)
</code></pre>
|
<p>The <a href="http://www.developerfusion.com/tools/convert/vb-to-csharp/" rel="noreferrer">Developer Fusion VB.Net to C# converter</a> says that the equivalent C# code is:</p>
<pre><code>System.Random rnd = new System.Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());
</code></pre>
<p>For future reference, they also have a <a href="http://www.developerfusion.com/tools/convert/csharp-to-vb/" rel="noreferrer">C# to VB.Net converter</a>. There are <a href="http://www.dotnetspider.com/convert/Vb-To-Csharp.aspx" rel="noreferrer">several other tools</a> available for this as well.</p>
|
<p>Best I can do off the top of my head without access to Visual Studio (crosses fingers):</p>
<pre><code>System.Random rnd = New System.Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(rnd => rnd.Next);
</code></pre>
| 31,793
|
<p>It is much more convenient and cleaner to use a single statement like</p>
<pre><code>import java.awt.*;
</code></pre>
<p>than to import a bunch of individual classes</p>
<pre><code>import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
</code></pre>
<p>What is wrong with using a wildcard in the <code>import</code> statement?</p>
|
<p>The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need <code>java.awt.Event</code>, and are also interfacing with the company's calendaring system, which has <code>com.mycompany.calendar.Event</code>. If you import both using the wildcard method, one of these three things happens:</p>
<ol>
<li>You have an outright naming conflict between <code>java.awt.Event</code> and <code>com.mycompany.calendar.Event</code>, and so you can't even compile.</li>
<li>You actually manage only to import one (only one of your two imports does <code>.*</code>), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.</li>
<li>When you compile your code there is no <code>com.mycompany.calendar.Event</code>, but when they later add one your previously valid code suddenly stops compiling.</li>
</ol>
<p>The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly <em>wrong</em>, but future maintainers will thank you for your clarity otherwise.</p>
|
<p>Importing all the classes in a package is considered a blind approach. A major reason for this is that it clutters the class namespace and could lead to conflicts between classes in different packages with the same name.</p>
<p>Specifically populating the necessary classes avoids that problem and clearly shows which versions were wanted. This is good for code maintainability.</p>
| 17,751
|
<p>Given a string as below, I need to convert:</p>
<p>1 Dec 2008 06:43:00 +0100</p>
<p>to</p>
<p>MM/DD/YYYY HH:MM:SSAM</p>
<p>using jython what is the best way to do this?</p>
|
<p>I don't have jython handy, but I'd expect something like this to work:</p>
<pre><code>import java
sdf = java.text.SimpleDateFormat
fmt_in = sdf('d MMM yyyy HH:mm:ss Z')
fmt_out = sdf('MM/dd/yyyy HH:mm:ssaa')
fmt_out.format(fmt_in.parse(time_str))
</code></pre>
|
<p><a href="http://www.jython.org/" rel="nofollow noreferrer">Jython</a> 2.5b0 (beta) has an implementation of the <a href="http://www.python.org/doc/2.5.2/lib/module-time.html" rel="nofollow noreferrer">time module</a> that includes</p>
<blockquote>
<p><code>strptime(string[, format])</code>.</p>
<p>Parse a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().</p>
</blockquote>
<p>(<code>strptime</code> is missing in Jython2.2.1).</p>
<p>A python version of the conversion formats will look like (not sure of the zone component):</p>
<pre><code>import time
mytime = time.strptime("1 Dec 2008 06:43:00 +0100", "%d %b %Y %H:%M:%S %Z")
new_time_string = time.strftime("%m/%d/%Y %I:%M:%S%p", mytime)
</code></pre>
| 42,797
|
<p>What's the easiest way to play a sound file (.wav) in Python? By easiest I mean both most platform independent and requiring the least dependencies. pygame is certainly an option, but it seems overkill for just sound.</p>
|
<p>For Windows, you can use winsound. It's built in</p>
<pre><code>import winsound
winsound.PlaySound('sound.wav', winsound.SND_FILENAME)
</code></pre>
<p>You should be able to use ossaudiodev for linux:</p>
<pre><code>from wave import open as waveOpen
from ossaudiodev import open as ossOpen
s = waveOpen('tada.wav','rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')
try:
from ossaudiodev import AFMT_S16_NE
except ImportError:
from sys import byteorder
if byteorder == "little":
AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
else:
AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(data)
dsp.close()
</code></pre>
<p>(Credit for ossaudiodev: Bill Dandreta <a href="http://mail.python.org/pipermail/python-list/2004-October/288905.html" rel="noreferrer">http://mail.python.org/pipermail/python-list/2004-October/288905.html</a>)</p>
|
<p>For Linux user, if low level pcm data manipulation is needed, try <a href="http://pyalsaaudio.sourceforge.net/index.html" rel="nofollow">alsaaudio</a> module. There is a playwav.py example inside the package too. </p>
| 39,545
|
<p>I need to store database passwords in a config file. For obvious reasons, I want to encrypt them (preferably with AES). Does anyone know a Delphi implementation that is easy to introduce into an existing project with > 10,000 lines of historically grown (URGH!) source code?</p>
<p>Clarification: Easy means adding the unit to the project, adding max. 5 lines of code where the config file is read and be done with it. Should not take more than 15 minutes.</p>
<p>Another clarification: The password is needed in order to create a connection to the db, not to support a user management scheme for the application. So using hashes does not help. The db engine checks if the password is valid, not the app.</p>
|
<p>I second the recommendation for David Barton's <a href="http://www.cityinthesky.co.uk/cryptography.html" rel="noreferrer">DCPCrypt library</a>. I've used it successfuly in several projects, and it won't take more than 15 minutes after you've read the usage examples. It uses MIT license, so you can use it freely in commercial projects and otherwise. DCPCrypt implements a number of algorithms, including Rijndael, which is AES.</p>
<p>There are many googlable stand-alone (single-unit) implementations too - the question is which one you trust, unless you are prepared to verify the correctedness of a particular library yourself.</p>
|
<p>Nick is of course right - I just assume you know what you are doing when you say you want to spend all of 15 minutes on implementing a security solution. The DCPCrypt library also implements a number of hashing algorithms if you decide to go that (better) route.</p>
| 16,149
|
<p>You're building a web application. You need to store the state for a <em>shopping cart like</em> object during a user's session.</p>
<p>Some notes:</p>
<ul>
<li>This is not exactly a shopping cart, but more like an itinerary that the user is building... but we'll use the word cart for now b/c ppl relate to it.</li>
<li>You do not care about "abandoned" carts</li>
<li>Once a cart is completed we will persist it to some server-side data store for later retrieval.</li>
</ul>
<p><strong>Where</strong> do you store that stateful object? And <strong>how</strong>?</p>
<ul>
<li>server (session, db, etc?)</li>
<li>client (cookie key-vals, cookie JSON object, hidden form-field, etc?)</li>
<li>other...</li>
</ul>
<p><strong>Update</strong>: It was suggested that I list the platform we're targeting - tho I'm not sure its totally necessary... but lets say the front-end is built w/ASP.NET MVC.</p>
|
<p>It's been my experience with the Commerce Starter Kit and MVC Storefront (and other sites I've built) that no matter what you think now, information about user interactions with your "products" is paramount to the business guys. There's so many metrics to capture - it's nuts.</p>
<p>I'll save you all the stuff I've been through - what's by far been the most successful for me is just creating an Order object with "NotCheckedOut" status and then adding items to it and the user adds items. This lets users have more than one cart and allows you to mine the tar out of the Orders table. It also is quite easy to transact the order - just change the status.</p>
<p>Persisting "as they go" also allows the user to come back and finish the cart off if they can't, for some reason. Forgiveness is massive with eCommerce. </p>
<p>Cookies suck, session sucks, Profile is attached to the notion of a user and it hits the DB so you might as well use the DB.</p>
<p>You might <em>think</em> you don't want to do this - but you need to <em>trust</em> me and know that you WILL indeed need to feed the stats wonks some data later. I promise you.</p>
|
<p>If you care about supporting users without Javascript enabled, then the server side sessions will let you use URL rewriting.</p>
| 12,175
|
<p>We have an ASP.NET application that manages it's own User, Roles and Permission database and we have recently added a field to the User table to hold the Windows domain account. </p>
<p>I would like to make it so that the user doesn't have to <strong>physically</strong> log in to our application, but rather would be automatically logged in based on the currently logged in Windows domain account DOMAIN\username. We want to authenticate the Windows domain account against our own User table. </p>
<p>This is a piece of cake to do in Windows Forms, is it possible to do this in Web Forms?</p>
<p>I don't want the user to be prompted with a Windows challenge screen, I want our system to handle the log in.</p>
<p><strong>Clarification</strong>: We are using our own custom Principal object.</p>
<p><strong>Clarification</strong>: Not sure if it makes a difference or not, but we are using IIS7.</p>
|
<p>I did pretty much exactly what you want to do a few years ago. Im trying to find some code for it, though it was at a previous job so that code is at home.</p>
<p>I do remember though i used <a href="http://msdn.microsoft.com/en-us/library/ms998360.aspx" rel="nofollow noreferrer">this article</a> as my starting point. You set up the LDAP provider so you can actually run a check of the user vs the LDAP. One thing to make sure of if you try the LDAP approach. In the setting file where you set up the LDAP make sure LDAP is all caps, if it is not it will not resolve.</p>
|
<p>You can use <code>System.Threading.Thread.CurrentPrincipal</code>.</p>
| 7,765
|
<p>I am evaluating BPEL engine for our high performance telecom application but performance seem to be very poor. We have evaluated Apache Ode, SunBPEL engine, Active BPEL etc. Do you know any faster BPEL engine implementation or BPEL implementation in C/C++ ?</p>
|
<p>I believe your performance measurements were very brief.</p>
<p>For example, I'm familiar with Apache ODE and I must say there is quite a lot of possibilities to speed things up.
After doing configuration optimizations, like using in-memory processes and disabling debug events, I got 60 TPS in SoapUI. After I did some code improvements, it went up to 150. So there is field for optimization in future.</p>
<p>I don't know how many TPS do you need, but 60 on a single machine is quite enough.</p>
<p>As for optimizing persistent processes, you need to tune indexes in database. </p>
<p>If you want more details on optimization, you can make a post to <a href="http://markmail.org/search/apache+ode+list:org.apache.ode.user" rel="nofollow noreferrer">ODE user group</a>.</p>
|
<p>Have you looked at Oracle BPEL? If it's like their database, it's probably fast but hard to configure and administer.</p>
| 34,949
|
<p>I'm a VMware user and far too often I use keyboard shortcuts while programming. However, this has proved to be quite distressing as sometimes the VMware gets hold of it and turns off / pauses (<kbd>Ctrl</kbd>+<kbd>Z</kbd>) the virtual machine.</p>
<p>Is there a way to disable keyboard shortcuts on VMware? Has anyone here ever found a workaround? </p>
|
<p>I use AutoHotKey (are you running VMWare on Windows ?) to disable certain shortcuts. You can find this tool here:</p>
<p><a href="http://www.autohotkey.com/" rel="noreferrer">http://www.autohotkey.com/</a></p>
<p>It's open source and I quite like it. Can be used for automation tasks, but you can also have it respond differently to different windows. With some AHK scripting, I think you should be able to fix your problem.</p>
<p>The site had got loads of tutorials too on writing handy scripts.</p>
<p>Good luck.</p>
|
<p>If it is Ok for you - here's a bit of hacky solution which is very simple - just use ResHacker program to get rid of those annoying accelerators (they are defined as resources in vmware.exe).</p>
| 18,449
|
<p>I have been working with Visual Studio (WinForm and ASP.NET applications using mostly C#) for several months now. For the most part my IDE is set up fairly standard but I have been wondering what are some suggestions in terms of plugins/settings that you find to be the most useful?</p>
<p><strong>Update</strong>: Thanks for all the great suggestions. It looks like a general consensus that I should look into 'Resharper' along with some eye-candy with themes and custom fonts.</p>
<hr>
<p><strong>Themes</strong></p>
<ul>
<li><a href="http://www.microsoft.com/downloads/details.aspx?familyid=22e69ae4-7e40-4807-8a86-b3d36fab68d3&displaylang=en" rel="nofollow noreferrer">Consolas Font Pack for Visual Studio 2005/2008</a></li>
<li><a href="http://www.hanselman.com/blog/VisualStudioProgrammerThemesGallery.aspx" rel="nofollow noreferrer">Scott Hanselman's Visual Studio Themes Gallery</a></li>
<li><a href="http://frickinsweet.com/tools/Theme.mvc.aspx" rel="nofollow noreferrer">Visual Studio Theme Generator</a></li>
</ul>
<p><strong>Free Tools</strong></p>
<ul>
<li><a href="http://visualstudiogallery.msdn.microsoft.com/en-us/df3f0c30-3d37-4e06-9ef8-3bff3508be31" rel="nofollow noreferrer">PowerCommands for Visual Studio 2008</a></li>
<li><a href="http://submain.com/products/ghostdoc.aspx" rel="nofollow noreferrer">GhostDoc</a></li>
<li><a href="http://www.codeplex.com/hyperAddin" rel="nofollow noreferrer">HyperAddin</a></li>
<li><a href="http://www.hanselman.com/blog/IntroducingRockScroll.aspx" rel="nofollow noreferrer">RockScroll</a></li>
<li><a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/CodeRushX/" rel="nofollow noreferrer">CodeRush XPress</a></li>
<li><a href="http://www.red-gate.com/products/reflector/" rel="nofollow noreferrer">.NET Reflector</a> - (Not a plugin but still useful)</li>
</ul>
<p><strong>Paid Tools</strong></p>
<ul>
<li><a href="http://www.jetbrains.com/resharper/" rel="nofollow noreferrer">Resharper</a> - Free (Open Source), $49 (Academic), $199 (Personal), $349 (Commercial)</li>
<li><a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/" rel="nofollow noreferrer">CodeRush with Refactor!™ Pro</a> - $249</li>
</ul>
|
<p><strong><a href="http://www.jetbrains.com/resharper/" rel="nofollow noreferrer">Resharper</a></strong> is definitely a great tool. It has a moderate learning curve but is easy to pick up for some simple things and add mastery later. It is a good price for students and kinda expensive for the rest of us. Resharper is similar to CodeRush, but seems to have a larger following.</p>
<p><strong><a href="http://www.visualstudiogallery.com/ExtensionDetails.aspx?ExtensionID=df3f0c30-3d37-4e06-9ef8-3bff3508be31" rel="nofollow noreferrer">PowerCommands</a></strong> is a great set of add-ons that comes free from Microsoft. Things like "Open in Windows Explorer", "Command Prompt Here", and Copy/Paste references. </p>
<p>A discussion regarding <strong>add-ins</strong> is <a href="https://stackoverflow.com/questions/2767/do-you-have-any-recommended-add-onsplugins-for-microsoft-visual-studio">floating around here somewhere</a>.</p>
<p>For straight-up customization, <strong>changing colors</strong> is fun, easy, and gives you a big bang for your buck. I prefer a slightly personalized version of <a href="http://blog.wekeroad.com/2007/10/17/textmate-theme-for-visual-studio-take-2/" rel="nofollow noreferrer">Rob Conery's TextMate theme for Visual Studio.</a> Once you get colors you like, you can just <a href="http://msdn.microsoft.com/en-us/library/zbhkx167(VS.80).aspx" rel="nofollow noreferrer">export the settings</a> and carry them with you wherever you go.</p>
<p>Related to colors and themes, the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=22e69ae4-7e40-4807-8a86-b3d36fab68d3&displaylang=en" rel="nofollow noreferrer"><strong>Consolas</strong> font pack</a> is pretty nifty and easy on the eye.</p>
<p>And like John recommends, a <a href="https://stackoverflow.com/questions/20507/give-me-awesome-visual-studio-keyboard-short-cuts">mastery of <strong>keyboard shortcuts</strong></a> will pay big dividends.</p>
|
<p>I have Resharper and SQL Prompt, both are excellent.</p>
| 6,331
|
<p>If you've worked on a project that stores data for use with the semantic web, do you use RDF or even OWL as the internal data format or do you have your own data model/ontology that you map to RDF for interoperability? </p>
<p>If you use RDF, what are your experiences with implementing various things like cyclical class hierachies?</p>
<p>If you do your own thing, how does it differ from RDF/OWL?</p>
|
<p>I work alongside the Jena team at HP (indeed, have contributed to Jena myself), so using Jena is a fairly straightforward choice in our team. However, there are more reasons than just "next-bench" convenience. The various standards for the semantic web contain quite a bit of detail and complexity, and getting that right isn't an easy thing to do by yourself. I've come across a number of downloadable ontologies and other datasets that, for example, don't conform to the IRI spec. In an entirely self-contained application it probably doesn't matter too much if you cut corners against the standards, but in that case you need to ask why you are using semantic web techniques in the first place. For me, a strong value in the semweb approach for an application would be data-interop and open data linking, in which case standards conformance is pretty central. </p>
<p>Most of my data is in a triple store, but I do use custom tables as indexes for commonly asked queries. If you know the query pattern ahead of time, a well-indexed table in a good db engine is going to be hard to beat for a generic schemaless triple store.</p>
<p>Obviously, one drawback to using Jena is that it's Java specific. I do use Jena with jruby, but I'm looking forwards to a good native Ruby RDF library (work is <a href="http://tommorris.org/blog/2008/02/27" rel="nofollow noreferrer">underway</a>). I'd also like more complete RDF/OWL support in Javascript and Flex for when we're doing complex rich client interfaces.</p>
<p>Ian</p>
|
<p>I'm currently working on some really small projects in this area and I "mostly" use RDF there, although for parsing purposes I use a simple URI-registry in order to avoid cycles in the data structure itself. Although, I have to say that I'm still in the conceptual stage of these projects. In the end I rely mostly on 3rd-party storage backends like Jena, rdflib et al.</p>
| 16,737
|
<p>I ran across this situation this afternoon, so I thought I'd ask what you guys do.</p>
<p>We have a randomized password generator for user password resets and while fixing a problem with it, I decided to move the routine into my (slowly growing) test harness.</p>
<p>I want to test that passwords generated conform to the rules we've set out, but of course the results of the function will be randomized (or, well, pseudo-randomized).</p>
<p>What would you guys do in the unit test? Generate a bunch of passwords, check they all pass and consider that good enough?</p>
|
<p>A unit test should do the same thing every time that it runs, otherwise you may run into a situation where the unit test only fails occasionally, and that could be a real pain to debug.</p>
<p>Try seeding your pseudo-randomizer with the same seed every time (in the test, that is--not in production code). That way your test will generate the same set of inputs every time.</p>
<p>If you can't control the seed and there is no way to prevent the function you are testing from being randomized, then I guess you are stuck with an unpredictable unit test. :(</p>
|
<p>Well, considering they are random, there is no really way to make sure, but testing for 100 000 password should clear most doubts :)</p>
| 11,365
|
<p>I am looking for an app that will let me type in code ON my cellphone. I don't need to compile or anything, and its not to program for the cellphone. Just something nice to have when an idea pops in my head.</p>
<p>Am I completely overlooking a simple code editor for Symbian S60v3 phones? </p>
<p>I am looking for something similar to <a href="http://www.logicalsky.com/Product_CEdit.php" rel="nofollow noreferrer">CEdit</a> which is for Windows Mobile. </p>
|
<p>I've used <a href="http://users.tkk.fi/~lhuovine/mobile/python.html" rel="nofollow noreferrer">pyEdit</a> on my S60v2 phone, it looks like it's supported under v3 as well.</p>
<p>It depends on the python runtime, so you'll need to install that first.</p>
|
<p>You can use visual studio :</p>
<p><a href="http://wiki.forum.nokia.com/index.php/Using_Visual_Studio_6.0_with_S60_3rd_Edition" rel="nofollow noreferrer">http://wiki.forum.nokia.com/index.php/Using_Visual_Studio_6.0_with_S60_3rd_Edition</a></p>
| 17,176
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/144833/most-useful-attributes-in-c">Most Useful Attributes in C#</a> </p>
</blockquote>
<p>besides:</p>
<pre><code>[DefaultValue(100)]
[Description("Some descriptive field here")]
public int MyProperty{get; set;}
</code></pre>
<p>What other C# Attributes are useful for Properties, after learning these I feel like I'm Missing out.</p>
<p><strong>Related Questions</strong></p>
<p><a href="https://stackoverflow.com/questions/144833/most-useful-attributes-in-c#144929">Most Useful Attributes in C#</a></p>
|
<pre><code>[Obsolete("This is an obsolete property")]
</code></pre>
<p>That's one of my favourites. Allows you to mark a property/method obsolete, which will cause a compiler warning (optionally, a compiler error) on build.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.localizableattribute(VS.71).aspx" rel="nofollow noreferrer">Localizable </a>
as well as
<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.listbindableattribute(VS.71).aspx" rel="nofollow noreferrer">ListBindable</a>
may be interesting for custom component designers.</p>
| 25,792
|
<p>Without using Javascript, is there a way to make a CSS property toggle on and off through nested elements.</p>
<p>The problem I'm trying to solve is that I have a number of tags and classes which make some text italic (<code><em></code>, <code><blockquote></code>, <code><cite></code>, <code><q></code>, <code><dfn></code>, and some other classes), and when one of these is inside another one of these, the italicisation needs to toggle.</p>
<pre>
<blockquote>
And so the man said, <q>That's not from <cite>Catcher In The Rye</cite>, dear
fellow!</q>, can you believe that?!
</blockquote>
</pre>
<p>Should render as:</p>
<blockquote>
<p><em>And so the man said,</em> "That's not from <em>Catcher In The Rye</em>, dear fellow!"<em>, can you believe that?!</em></p>
</blockquote>
<p>The CSS I've got for this is getting a bit messy:</p>
<pre><code>q, em, dfn, cite, blockquote {
font-style: italic;
}
q q, q em, q dfn, q cite,
em q, em em, em dfn, em cite,
dfn q, dfn em, dfn dfn, dfn cite,
cite q, cite em, cite dfn, cite cite,
blockquote q, blockquote em, blockquote dfn, blockquote cite {
font-style: normal;
}
</code></pre>
<p>...and I'm pretty sure that won't even work past one level of nesting (as in my example).</p>
<p>Is there a way I can do this without have to list every permutation of the tags?</p>
|
<p>I couldn't tell you which browsers (if any) implement the CSS3 <code>:not</code> pseudo-class, but if we see it supported sometime it seems like we can do:</p>
<pre>
q:not(q, em, dfn, cite, blockquote),
em:not(q, em, dfn, cite, blockquote),
dfn:not(q, em, dfn, cite, blockquote),
cite:not(q, em, dfn, cite, blockquote),
blockquote:not(q, em, dfn, cite, blockquote) { font-style: italic; }
</pre>
<p>It's anyone's guess as to how browsers will implement this when they do, so it might not work more than 2 levels deep (like your example).</p>
<p>Other than that, unfortunately I can't think of another pure CSS solution.</p>
|
<p>You say you have all sorts of elements that needs displaying as italic, but once nested they need to break previous italication. Forgive me for saying, but I am truly wondering if one should really want such behavior.</p>
<p>Allow me to explain myself: you have different markup such as a quote, citation, emphasis etc. When used nested, the emphasis inside a quote should really have a different meaning than when used outside the quote. Therefore, default css rules apply to all that lies underneath. And therefore, I do not understand the desire of flattening your meaningful nested markup to italic and non-italic, because it hides the underlying meaning of the contents at hand (because similar formatting will be applied to different meaningful parts of the document).</p>
<p>My recommendation would be to either:</p>
<ul>
<li>Assume that your markup is there for a reason, so leave the styling as it is. An emphasis nested within a blockquote should always have the styling of its ancestor elements, because there is a reason for this nesting and it should not be hidden for the user in a visual way</li>
<li>Go over the requirements of your document and see if you really want such nesting. If not, a generic HTML editor might not be sufficient to your needs and you might be better off using an xml format that validates to a certain schema that, in your case, would forbid certain element usage within others. Then use an xml editor such as Xopus or XmlSpy to edit your document.</li>
</ul>
<p>Sorry if this is not a direct solution to your question, but I hope to be able to give you another perspective towards the problem and perhaps see that there might not be a problem at all. Good luck!</p>
| 25,387
|
<p><strong>Background</strong>:</p>
<p>I have a VB6 application I've "inherited" that generates a PDF for the user to review using unsupported Acrobat Reader OCX integration. The program generates an FDF file with the data, then renders the merged result when the FDF is merged with a PDF. It only works correctly with Acrobat Reader 4 :-(. Installing a newer version of Acrobat Reader breaks this application, making the users very unhappy.</p>
<p>I want to re-architect this app so that it will send the data to be merged to a PDF output generation server. This server will merge the data passed to it onto the form, generate a PDF image of this, and store it, so that any user wishing to view the final result can then simply get the PDF (it is generated just once). If the underlying data is changed, the PDF will be deleted and regenerated next time it is requested. The client program can then have any version of Acrobat Reader they wish, as it will be used exclusively for displaying PDF files (as it was intended). The server will most likely be written in .NET (C#) with Visual Studio 2005, probably as a Web Service... </p>
<p><strong>Question</strong>:</p>
<p>How would others recommend I go about this? Should I use Adobe's Acrobat 9 at the server to do this, puting the data into FDF or Adobe's XML format, and letting Acrobat do the merge? Are there great competitors in the "merge data onto form and output a PDF" space? How do others do this? It has to be API based, no GUI at the server, of course...</p>
<p>While some output is generated via FDF/PDF, another part of the application actually sends lines, graphics, and text to the printer (or a form for preview purposes) one page at a time, giving the proper x/y coordinates, font, size, etc. for each, knowing when it is at the end of a page, etc. This code is currently in the program that displays this for the user to review, and it is also in the program that prints the final form to the printer. For consistency between reviewer and printer, I'd like to move this output generation logic to a server as well, either using a good PDF generation API tool or use the code as is and generate a PDF with a PDF printer... and saving this PDF for display by the clients.</p>
<p>Googling "Form software" or "fill form software" or similar searches returns sooooooooo much unrelated material, mostly related to UI for users to fill in forms, I just don't know how to properly narrow down my search. This site seems the perfect place to ask such a question, as other programmers must also need to generate similar outputs, and have tried out some great tools.</p>
<p><strong>EDIT:</strong> </p>
<p>I've added PDF tag as well as PDF-generation.
Also, my current customer insists on PDF output, but I appreciate the alternative suggestions.</p>
|
<p>can't help with VB6 solution, can help with .net or java solution on the server.<br>
Get iText or iTextSharp from <a href="http://www.lowagie.com/iText/" rel="nofollow noreferrer">http://www.lowagie.com/iText/</a>.<br>
It has a PdfStamper class that can merge a PDF and FDF FDFReader/FDFWriter classes to generate FDF files, get field names out of PDF files, etc... </p>
|
<p>Take my advice. Ditch PDF for XPS. I am working on two apps, both server based. One displays image-based documents as PDFs in a browser. The second uses FixedPage templates to construct XPS documents bound to data sources. </p>
<p>My conclusion after working on both projects is that PDFs suck; XPS documents less so. You have to pay cash money for a decent PDF library, whereas XPS comes with the framework. PDF document generation is a memory hog, has lots of potholes and isn't very server friendly. XPS docs have a much smaller footprint and less chances of shooting yourself in the foot. </p>
| 7,844
|
<p>I am having some trouble with model adherence to my print bed. As shown in the attached photo, my model is pulled away at the sides leaving it bowed even though it is designed to be flat. Other than this "bowing", the model is of good quality.</p>
<p>The model is printed solid on an Anycubic Photon M3 Plus with Anycubic 3D Printing UV Sensitive Resin. My print settings are:</p>
<ul>
<li>Bottom layer count: 6</li>
<li>Bottom layer exposure: 22 secs (also tried 30 secs and 40 secs with the same results)</li>
<li>Normal layer height: 0.05 mm</li>
<li>Normal layer exposure: 2.5 secs</li>
<li>Off time: 0.5 secs</li>
<li>Z lift height: 6 mm</li>
<li>Z lift speed : 360 mm/sec</li>
<li>Z lift retract: 6 mm</li>
</ul>
<p>The bed is aligned. Could anyone suggest what is wrong and what I could try to remove this "bowing" effect?</p>
<p><a href="https://i.stack.imgur.com/VmF9H.jpg" rel="nofollow noreferrer" title="Resin printed model with a bowing effect"><img src="https://i.stack.imgur.com/VmF9H.jpg" alt="Resin printed model with a bowing effect" title="Resin printed model with a bowing effect" /></a></p>
|
<h2>Print orientation</h2>
<p>Your model is pulled up from the FEP film with a huge force. It releases from the film first at the corners, then progresses to the center. The force bends the model down as it is still flexible, so it creates a bent item.</p>
<p>This can be mitigated by reducing the area that you pull at. Commonly, you'll turn the item so the area is minimized, and you also might want to angle the item. This will cost some material in support structure, but you reduce the force on the part that can deform it in printing.</p>
|
<h2>Print orientation</h2>
<p>Your model is pulled up from the FEP film with a huge force. It releases from the film first at the corners, then progresses to the center. The force bends the model down as it is still flexible, so it creates a bent item.</p>
<p>This can be mitigated by reducing the area that you pull at. Commonly, you'll turn the item so the area is minimized, and you also might want to angle the item. This will cost some material in support structure, but you reduce the force on the part that can deform it in printing.</p>
| 2,204
|
<p>I'm writing a PHP script and the script outputs a simple text file log of the operations it performs. How would I use PHP to delete the first several lines from this file when it reaches a certain file size?</p>
<p>Ideally, I would like it to keep the first two lines (date/time created and blank) and start deleting from line 3 and delete X amount of lines. I already know about the <code>filesize()</code> function, so I'll be using that to check the file size.</p>
<p>Example log text:</p>
<pre><code>*** LOG FILE CREATED ON 2008-10-18 AT 03:06:29 ***
2008-10-18 @ 03:06:29 CREATED: gallery/thumbs
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9423.JPG to gallery/IMG_9423.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9188.JPG to gallery/IMG_9188.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9236.JPG to gallery/IMG_9236.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9228.JPG to gallery/IMG_9228.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_3104.JPG to gallery/IMG_3104.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/First dance02.JPG to gallery/First dance02.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/BandG02.JPG to gallery/BandG02.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/official03.JPG to gallery/official03.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/Wedding32.JPG to gallery/Wedding32.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/Gettaway car16.JPG to gallery/Gettaway car16.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/Afterparty05.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/IMG_9254.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/IMG_9175.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/official05.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/First dance01.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/Wedding29.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/men walking.jpg
</code></pre>
|
<h2>Use the SPL, Luke</h2>
<p>PHP 5 comes with plenty of iterators goodness :</p>
<pre><code><?php
$line_to_strip = 5;
$new_file = new SplFileObject('test2.log', 'w');
foreach (new LimitIterator(new SplFileObject('test.log'), $line_to_strip) as $line)
$new_file->fwrite($line);
?>
</code></pre>
<p>It's cleaner that what you can do while messing with fopen, it does not hold the entire file in memory, only one line at a time, and you can plug it and reuse the pattern anywhere since it's full OO.</p>
|
<p>Typical operating systems don't provide the capability to insert or delete content of a file "in-place". What you will need to do is write a function that reads the first file, and creates a <em>new</em> output file containing the lines you want to keep. Then when you're done, delete the old file and rename the new one to the old name.</p>
<p>In pseudocode:</p>
<pre><code>open original file IN for reading
create new output file OUT
read the first two lines from IN
write these lines to OUT
for each line to skip:
read a line from IN
for the remainder of the file:
read a line from IN
write the line to OUT
close IN
close OUT
delete IN
rename OUT to IN
</code></pre>
<p>The advantage of this method over some of the other ones presented is that it <em>doesn't</em> require you to read the whole file into memory first. You didn't mention how large your upper size limit was, but if it's something like 100 MB you might find that loading the file into memory is not an acceptable use of space.</p>
| 26,537
|
<p>For a project I am working on in ruby I am overriding the method_missing method so that I can set variables using a method call like this, similar to setting variables in an ActiveRecord object:</p>
<p><code>Object.variable_name= 'new value'</code> </p>
<p>However, after implementing this I found out that many of the variable names have periods (.) in them. I have found this workaround:</p>
<p><code>Object.send('variable.name=', 'new value')</code></p>
<p>However, I am wondering is there a way to escape the period so that I can use</p>
<p><code>Object.variable.name= 'new value'</code></p>
|
<p>Don't do it!</p>
<p>Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:</p>
<pre><code>attr_writer :bar
attr_reader :baz
attr_accessor :foo
</code></pre>
<p>Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go.</p>
<pre><code>class SillySetter
def initialize path=nil
@path = path
end
def method_missing name,value=nil
new_path = @path ? "#{@path}.#{name}" : name
if name.to_s[-1] == ?=
puts "setting #{new_path} #{value}"
else
return self.class.new(path=new_path)
end
end
end
s = SillySetter.new
s.foo = 5 # -> setting foo= 5
s.foo.bar.baz = 4 # -> setting foo.bar.baz= 4
</code></pre>
<p>I didn't want to encourage ruby sillyness, but I just couldn't help myself!</p>
|
<p>If there's no hope of changing the canonical names, you could alias the getters and setters manually:</p>
<pre><code>def variable_name
send 'variable.name'
end
def variable_name=(value)
send 'variable.name=', value
end
</code></pre>
| 7,173
|
<p>The reason I ask is that Stack Overflow has been <a href="http://slashdot.org/firehose.pl?op=view&id=1170403" rel="nofollow noreferrer">Slashdotted</a>, and <a href="http://www.reddit.com/r/programming/comments/71i4v/stack_overflow_launched_into_public/" rel="nofollow noreferrer">Redditted</a>.</p>
<p>First, what kinds of effect does this have on the servers that power a website? Second, what can be done by system administrators to ensure that their sites remain up and running as best as possible?</p>
|
<p>Unfortunately, if you haven't planned for this before it happens, it's probably too late and your users will have a poor experience. </p>
<p>Scalability is your first immediate concern. You may start getting more hits per second than you were getting per month. Your first line of defense is good programming and design. Make sure you're not doing anything stupid like reloading data from a database multiple times per request instead of caching it. Before the spike happens, you need to do some fairly realistic load tests to see where the bottlenecks are.</p>
<p>For absurdly high traffic, consider the ability to switch some dynamic pages over to static pages. </p>
<p>Having a server architecture that can scale also helps. Shared hosts generally don't scale. A single dedicated machine generally doesn't scale. Using something like Amazon's EC2 to host can help, especially if you plan for a cluster of servers from the beginning (even if your cluster is a single computer).</p>
<p>You're next major concern is security. You're suddenly a much bigger target for the bad guys. Make sure you have a good security plan in place. This is something you should always have, but it become more important with high usage.</p>
|
<p>The app designer needs to think about scaling up (larger machines with more cores and higher performance) and/or scaling out (distributing workload across multiple systems). The IT guy needs to work out how to best support that. The network is what you look at first, because obviously everything rides on top of it. Starting at the border, that usually means network load balancers and redundant routers being served by multiple providers. You can also look at geographic caching services and apps such as cachefly.</p>
<p>You want to reduce your bottlenecks as much as possible. You also want to design the environment such that it can be scaled out as needed without much work. Do the design work up front and it'll mean less headaches when you do get dugg.</p>
| 8,780
|
<p>I'm using flex builder to compile my SWF. Im using mp3's on my local machine and computeSpectrum() to analyze the mp3. </p>
<p>After playing for 20secs, my computeSpectrum stops returning values, instead, it starts returning this error:</p>
<pre><code>SecurityError: Error #2121: Security sandbox violation: SoundMixer.computeSpectrum: file:///C|/Documents%20and%20Settings/Kasper/My%20Documents/Flex%20Builder%203/Soundanalizer/bin%2Ddebug/Soundanalizer.swf cannot access . This may be worked around by calling Security.allowDomain.
</code></pre>
<p>If I compile with flash, it doesn't throw this error :/</p>
|
<p>The flash player thinks it's trying to open a local file from a website. This is ignored if you run it from the flash ide. It should also work as it is if you upload it to a webserver.</p>
<p>To be able to test locally add access to your swf (or the entire project folder) using the security tab on <a href="http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html" rel="nofollow noreferrer">http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html</a></p>
|
<p>Issues I've had with computeSpectrum in the past were caused by the global way Flash checks the audio sandbox, meaning other unrelated Flash content open in the browser (e.g. YouTube) is treated as if your swf was trying to load it - this means that if you run your app and then open YouTube you will get an error.</p>
<p>Could this be the cause?</p>
| 27,465
|
<p>I'm writing a custom blog engine and would like to have trackbacks similar to Wordpress. I could look at the Wordpress source, but I'd really prefer a tutorial of some sort and so far I haven't been able to find one. Are there any good tutorials for implementing trackbacks or pingbacks in PHP5? </p>
|
<p>Trackbacks are fine, but they're very prone to spam, since there's no verification of their origin. You use a simple discovery method to find the trackpack entrypoint; look for RDF in the target site's source. Then it's simply a RESTful POST request to the destination site's trackback entrypoint passing the requisite trackback information. The specification linked by Sebastian Hörl should give you plenty of information for that.</p>
<p>Pingbacks are a bit more complex, because they require both XMLRPC and a linkback. So while you can just use REST calls to send anonymous trackbacks to any site, sites that you pingback will look at your site to determine whether you're actually linking to the pinged page.</p>
<p>Also, implementing Pingback on the receiving end is a little more complicated, because you have to verify the ping. I suppose you don't have to, but it would be foolish not to, otherwise it would be susceptible to the same spamming techniques as Trackbacks.</p>
<p>The <a href="http://hixie.ch/specs/pingback/pingback-1.0" rel="nofollow noreferrer">Pingback specification</a> has all the information you need to get that implementation off the ground.</p>
<p>Another recommendation is rather than wade through the inevitably dense and spaghetti-ish WordPress Pingback code, have a look at <a href="http://habariproject.org/" rel="nofollow noreferrer">Habari</a>'s self-contained <a href="https://trac.habariproject.org/habari/browser/trunk/htdocs/system/plugins/pingback/pingback.plugin.php" rel="nofollow noreferrer">Pingback implementation</a>, which isolates some of the key features of the task into more easily digestible units.</p>
|
<p>Dunno what trackbacks are, all I've noticed of them is that they clutter up websites with messy blocks of text, often interpersed with article comments.</p>
<p>But if they allow you to see who is linking to you in real time without log analysis:</p>
<p>You could use the HTTP-Referer (sic) header to see if people have linked to your article.
Each article would have a map of these referrers (and a count, so you can organise by popularity). You then implement a basic crawler that visits new referrers to scrape content.</p>
<p>I'm sure there's a third party implementation available as well. Or a specification. As the other poster has linked to, so, err, ignore this.</p>
| 35,698
|
<p>I've seen a few sites that list related searches when you perform a search, namely they suggest other search queries you may be interested in.</p>
<p>I'm wondering the best way to model this in a medium-sized site (not enough traffic to rely on visitor stats to infer relationships). My initial thought is to store the top 10 results for each unique query, then when a new search is performed to find all the historical searches that match some amount of the top 10 results but ideally not matching all of them (matching all of them might suggest an equivalent search and hence not that useful as a suggestion).</p>
<p>I imagine that some people have done this functionality before and may be able to provide some ideas of different ways to do this. I'm not necessarily looking for one winning idea since the solution will no doubt vary substantially depending on the size and nature of the site.</p>
|
<p>Here are some interesting sources:</p>
<ul>
<li>the <a href="http://dddcommunity.org/books/index.html#DDD" rel="noreferrer">DDD</a> book by Eric Evans</li>
<li>the free <a href="http://dddcommunity.org/books/index.html#DDD_quickly" rel="noreferrer">DDD Quickly</a> book</li>
<li>the <a href="http://groups.yahoo.com/group/domaindrivendesign/" rel="noreferrer">DDD newsgroup</a></li>
</ul>
|
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0321268202" rel="nofollow noreferrer" rel="nofollow noreferrer">Applying Domain-Driven Design and Patterns</a> is a very good book on the subject. Lots of good examples as well as discussion of related subjects like test driven development and how they apply.</p>
<p>Also check out <a href="http://domaindrivendesign.org/" rel="nofollow noreferrer">domaindrivendesign.org</a>.</p>
| 15,068
|
<p>The only reliable method that I a have found for using a script to download text from wikipedia is with cURL. So far the only way I have for doing that is to call <code>os.system()</code>. Even though the output appears properly in the python shell I can't seem to the function it to return anything other than the exit code(<code>0</code>). Alternately somebody could show be how to properly use <code>urllib</code>.</p>
|
<p>From <a href="http://diveintopython.net/html_processing/extracting_data.html" rel="nofollow noreferrer">Dive into Python:</a> </p>
<pre><code>import urllib
sock = urllib.urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)")
htmlsource = sock.read()
sock.close()
print htmlsource
</code></pre>
<p>That will print out the source code for the Python Wikipedia article. I suggest you take a look at Dive into Python for more details.</p>
<p>Example using urllib2 from the <a href="http://www.python.org/doc/2.5.2/lib/urllib2-examples.html" rel="nofollow noreferrer">Python Library Reference:</a> </p>
<pre><code>import urllib2
f = urllib2.urlopen('http://www.python.org/')
print f.read(100)
</code></pre>
<p>Edit: Also you might want to take a look at <a href="http://en.wikipedia.org/wiki/Wget#Using_Wget" rel="nofollow noreferrer">wget.</a><br>
Edit2: Added urllib2 example based on S.Lott's advice</p>
|
<p>As an alternetive to urllib, you could use the libCurl <a href="http://curl.haxx.se/libcurl/python/" rel="nofollow noreferrer">Python bindings</a>.</p>
| 45,756
|
<p>If I have an NSString with a text file in it, how do I get an NSArray of NSString with each NSString containing a line of the file.</p>
<p>In 10.5 I did this:</p>
<pre><code>NSArray* lines = [str componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
</code></pre>
<p>But that doesn't work in 10.4, and my program needs to work in 10.4.</p>
<p>As well, it needs to work with \r, \n and \r\n line endings. </p>
|
<p>The following code is straight from <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/Strings/Articles/stringsParagraphBreaks.html" rel="nofollow noreferrer">Apple's documentation regarding paragraphs and line breaks</a>:</p>
<pre><code>unsigned length = [string length];
unsigned paraStart = 0, paraEnd = 0, contentsEnd = 0;
NSMutableArray *array = [NSMutableArray array];
NSRange currentRange;
while (paraEnd < length)
{
[string getParagraphStart:&paraStart end:&paraEnd
contentsEnd:&contentsEnd forRange:NSMakeRange(paraEnd, 0)];
currentRange = NSMakeRange(paraStart, contentsEnd - paraStart);
[array addObject:[string substringWithRange:currentRange]];
}
</code></pre>
<p>I'm not 100% sure if it will work with 10.4</p>
|
<p>You can also do <code>enumerateSubstringsInRange:</code> with the <code>NSStringEnumerationByLines</code> and/or <code>NSStringEnumerationByParagraphs</code> options.</p>
<p>The benefit of doing it that way is that you get the NSRange of each substring, and can also set the initial range of the string to enumerate.</p>
<pre><code>[myString enumerateSubstringsInRange:NSMakeRange(0, myString.length) options:NSStringEnumerationByLines | NSStringEnumerationByParagraphs usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
}];
</code></pre>
| 44,540
|
<p>Windows XP Disk Defragmenter report shows a constant <strong>gap</strong> in disk usage on a number of disk partitions on my system. I'm not referring to the little transitory gaps that occur. In disk D below, the gap in question is the one under the word "defragmentation". In disk P below, the gap is the one under "usage before def" the but a bigger one. The C partition doesn't have this anomaly. The size and placement pattern isn't obvious. It is as though there was an area, a no-man's land, that both the file system and the defragmenter avoid. These gaps survive daily use and defragmentation. I don't believe this is a residue from a paging file -- it should show up in green, anyway. Recycle bin is empty.</p>
<p>Any ideas? </p>
<p>Disk D (20 Gig):
<img src="https://i.stack.imgur.com/e8HYu.jpg" alt="Disk D"></p>
<p>Disk P (40 Gig):
<img src="https://i.stack.imgur.com/20fvO.jpg" alt="Disk P"></p>
|
<p>That is probably the space reserved for the <a href="http://en.wikipedia.org/wiki/Master_File_Table" rel="nofollow noreferrer">MFT</a>, which will only be used for files if the disk gets really full. This empty space allows it to grow for a while without getting fragmented.</p>
<p>References:</p>
<ul>
<li><a href="http://support.microsoft.com/?scid=kb%3Ben-us%3B174619" rel="nofollow noreferrer">How NTFS reserves space for its Master File Table (MFT)</a></li>
</ul>
|
<p>No idea what's causing this, but the defragger that comes with Win XP is Diskkeeper Lite, which is not very good. A better defragger might get rid of the gap if it's not being caused by anything. I personally use O&O Defrag; it's not free, but there's a 30-day trial.</p>
| 32,193
|
<p>Here is a simplified version of my application showing what I'm doing. </p>
<pre><code>/*
in my app's main():
Runner run = new Runner();
run.dowork();
*/
class Runner
{
private int totalWorkers = 2;
private int workersDone = 0;
public synchronized void workerDone()
{
workersDone++;
notifyAll();
}
public synchronized void dowork()
{
workersDone = 0;
//<code for opening a file here, other setup here, etc>
Worker a = new Worker(this);
Worker b = new Worker(this);
while ((line = reader.readLine()) != null)
{
//<a large amount of processing on 'line'>
a.setData(line);
b.setData(line);
while (workersDone < totalWorkers)
{
wait();
}
}
}
}
class Worker implements Runnable
{
private Runner runner;
private String data;
public Worker(Runner r)
{
this.runner = r;
Thread t = new Thread(this);
t.start();
}
public synchronized void setData(String s)
{
this.data = s;
notifyAll();
}
public void run
{
while (true)
{
synchronized(this)
{
wait();
//<do work with this.data here>
this.runner.workerDone();
}
}
}
}
</code></pre>
<p>The basic concept here is that I have a bunch of workers which all do some processing on an incoming line of data, all independently, and write out the data wherever they like - they do not need to report any data back to the main thread or share data with each other. </p>
<p>The problem that I'm having is that this code deadlocks. I'm reading a file of over 1 million lines and I'm lucky to get 100 lines into it before my app stops responding.</p>
<p>The workers, in reality, all do differing amounts of work so I want to wait until they all complete before moving to the next line.</p>
<p>I cannot let the workers process at different speeds and queue the data internally because the files I am processing are too large for this and won't fit in memory.</p>
<p>I cannot give each worker its own FileReader to independently get 'line', because I do a ton of processing on the line before the workers see it, and do not want to have to re-do the processing in each worker.</p>
<p>I know I'm missing some fairly simple aspect of synchronization in Java but I'm stuck at this point. If someone could explain what I'm doing wrong here I would appreciate it. I believe I'm misunderstanding some aspect of the synchronization but I'm out of ideas for attempting to fix it.</p>
|
<p>Working directly with <code>synchronized</code>, <code>wait()</code>, and <code>notify()</code> is definitely tricky.</p>
<p>Fortunately the <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html" rel="nofollow noreferrer">Java Concurrency API</a> provides some excellent control objects for this sort of thing that are much more intuitive. In particular, look at <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/CyclicBarrier.html" rel="nofollow noreferrer"><code>CyclicBarrier</code></a> and <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html" rel="nofollow noreferrer"><code>CountDownLatch</code></a>; one of them almost certainly will be what you're looking for.</p>
<p>You may also find a <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html" rel="nofollow noreferrer"><code>ThreadPoolExecutor</code></a> to be handy for this situation.</p>
<p>Here's a simple example / conversion of your snippet that produces the following output (without deadlock, of course):</p>
<blockquote>
<p>Read line: Line 1<br>
Waiting for work to be complete on line: Line 1<br>
Working on line: Line 1<br>
Working on line: Line 1<br>
Read line: Line 2<br>
Waiting for work to be complete on line: Line 2<br>
Working on line: Line 2<br>
Working on line: Line 2<br>
Read line: Line 3<br>
Waiting for work to be complete on line: Line 3<br>
Working on line: Line 3<br>
Working on line: Line 3<br>
All work complete!</p>
</blockquote>
<pre><code>public class Runner
{
public static void main(String args[]) {
Runner r = new Runner();
try {
r.dowork();
} catch (IOException e) {
// handle
e.printStackTrace();
}
}
CyclicBarrier barrier;
ExecutorService executor;
private int totalWorkers = 2;
public Runner() {
this.barrier = new CyclicBarrier(this.totalWorkers + 1);
this.executor = Executors.newFixedThreadPool(this.totalWorkers);
}
public synchronized void dowork() throws IOException
{
//<code for opening a file here, other setup here, etc>
//BufferedReader reader = null;
//String line;
final Worker worker = new Worker();
for(String line : new String[]{"Line 1", "Line 2", "Line 3"})
//while ((line = reader.readLine()) != null)
{
System.out.println("Read line: " + line);
//<a large amount of processing on 'line'>
for(int c = 0; c < this.totalWorkers; c++) {
final String curLine = line;
this.executor.submit(new Runnable() {
public void run() {
worker.doWork(curLine);
}
});
}
try {
System.out.println("Waiting for work to be complete on line: " + line);
this.barrier.await();
} catch (InterruptedException e) {
// handle
e.printStackTrace();
} catch (BrokenBarrierException e) {
// handle
e.printStackTrace();
}
}
System.out.println("All work complete!");
}
class Worker
{
public void doWork(String line)
{
//<do work with this.data here>
System.out.println("Working on line: " + line);
try {
Runner.this.barrier.await();
} catch (InterruptedException e) {
// handle
e.printStackTrace();
} catch (BrokenBarrierException e) {
// handle
e.printStackTrace();
}
}
}
}
</code></pre>
|
<p>IMHO you have improperly placed "workersDone = 0".</p>
<pre><code>public synchronized void dowork()
{
// workersDone = 0;
//<code for opening a file here, other setup here, etc>
Worker a = new Worker(this);
Worker b = new Worker(this);
while ((line = reader.readLine()) != null)
{
workersDone = 0;
//<a large amount of processing on 'line'>
a.setData(line);
b.setData(line);
while (workersDone < totalWorkers)
{
wait();
}
}
}
</code></pre>
| 45,679
|
<p>My team uses an internal team maven repo that is shared from a development server using Apache. We also run the Continuum CI server on the same machine. Maven builds in Continuum are run with the "install" goal, which copies the final artifact directly into the shared directory.</p>
<p>The question is, what is the difference between adding files to the shared repo using <code>mvn install</code> and using the deploy goal (mvn-deploy plugin)?</p>
<p>It seems to me that using <code>mvn deploy</code> creates additional configuration hassles, but I have read somewhere that installing files into a shared repo is a bad idea for some reason related to the internal workings of maven.</p>
<p>update: I get the functional differences between <code>deploy</code> and <code>install</code>; I am actually more interested in the low level details in terms of what files are created in the maven repo.</p>
|
<p>Ken, good question. I should be more explicit in the <a href="http://www.sonatype.com/books/maven-book/reference/public-book.html" rel="noreferrer">The Definitive Guide</a> about the difference. "install" and "deploy" serve two different purposes in a build. "install" refers to the process of installing an artifact in your local repository. "deploy" refers to the process of deploying an artifact to a remote repository.</p>
<p>Example: </p>
<ol>
<li><p>When I run a large multi-module project on a my machine, I'm going to usually run "mvn install". This is going to install all of the generated binary software artifacts (usually JARs) in my local repository. Then when I build individual modules in the build, Maven is going to retrieve the dependencies from the local repository. </p></li>
<li><p>When it comes time to deploy snapshots or releases, I'm going to run "mvn deploy". Running this is going to attempt to deploy the files to a remote repository or server. Usually I'm going to be deploying to a repository manager such as <a href="http://nexus.sonatype.org" rel="noreferrer">Nexus</a></p></li>
</ol>
<p>It is true that running "deploy" is going to require some extra configuration, you are going to have to supply a distributionManagement section in your POM. </p>
|
<p>"matt b" has it right, but to be specific, the "install" goal copies your built target to the local repository on your file system; useful for small changes across projects not currently meant for the full group.</p>
<p>The "deploy" goal uploads it to your shared repository for when your work is finished, and then can be shared by other people who require it for their project.</p>
<p>In your case, it seems that "install" is used to make the management of the deployment easier since CI's local repo <em>is</em> the shared repo. If CI was on another box, it would have to use the "deploy" goal.</p>
| 25,399
|
<p>Is it possible to have all the computing capacity of all the hardware nodes allocated to one instance (for eg. one basic linux installation)?</p>
<p>How to manage the cloud?</p>
|
<p>I think you're confusing cloud computing and grid computing here. Although they do have similarities.</p>
<p>Cloud computing is usually used to refer to solutions where data is stored somewhere on the internet and made available on any workstation that is online.</p>
<p>Grid computing is used to refer to applications where a lot of different agents solve parts of the same computing problem in parallel. (think Seti-at-home or folding-at-home)</p>
<p>But you can't use cloud or grid computing to just seamlessly run existing platforms. Both refer to architectures. There are a couple of platforms that are general implementations of these architectures but they're so different that you can't easilly run software on them that's not designed to run distributed.</p>
|
<p>For a defenition of cloud computing,I like <a href="https://stackoverflow.com/questions/108037/what-is-cloud-computing#108042">blowdart's reply here</a>, it's basically using online resources, so you're not allocating the resources yourself on a LAN, but using 3rd party services (like amazon/google and maybe microsoft soon?) to have access to processing and storage that you can scale if and when you need to. Developing for the cloud is completely different from normal development.</p>
<p>You could basically start with one node (like an amazon EC2 instance, and an S3 account), and in case you need more processing power, you could setup a process to power-up more instances, but they would still be different virtual servers running either the same, or many different images. You cannot treat the cloud (or grid) as one basic linux installation.</p>
| 28,819
|
<p>I've so far dabbled in Flash doing 1-man shows for quite some time, but have never done any big projects with it, where actually source management and code-reuse was truly necessary. However I'm considering Flash for a new project, but this time around it's won't be a 1-man show, that's when it struck me that I had no experience of how one is supposed to do that with flash.</p>
<p>What are some good tips or resources that could help us figure out a good workflow?</p>
|
<ul>
<li>Good communication</li>
<li>Don't work in .fla's. 100% of the code in .as files</li>
<li>UML (at least discussed)</li>
<li>Different tasks for everybody</li>
<li>Comments in commits to code repository</li>
<li>"Manage your code so that anybody can at any time take over your job"</li>
<li>Consider <a href="http://en.wikipedia.org/wiki/Bus_factor" rel="nofollow noreferrer">the bus factor</a></li>
</ul>
<p>With junior developers it's also good to go through basic stuff such as package structures etc, just so that everybody is on the same page.</p>
<p>I think it's also good if somebody is kind of like a technical manager of the project, overseeing what the developers are doing. It may also be one of the developers but i think it's important to have one person who knows what everybody else is doing.</p>
|
<p>Antti has a bunch of good ones, externalizing code and appointing a leader in particular, I'd just add that when you're picking different tasks for everyone, tell people to code their piece as a modular class that provides the functionality you'll need - that'll make the code more reuseable in the future, and make integration smoother as well.</p>
| 23,161
|
<p>I have a main canvas 'blackboard' in a panel,
this canvas has itself several children, like a toolbar (tiles), a label and some skinning.</p>
<p>The problem is that when I move to the rectangle tool and I start drawing rectangles if I want to change the tool when I click on an other tool such as 'circle' or 'select' the button won't catch the click event, instead the canvas will catch the mouse down and start drawing.</p>
<p>Just like on the picture. So I am unable to change tool once I start drawing.</p>
<p><a href="http://www.freeimagehosting.net/uploads/397a7cd49e.png" rel="nofollow noreferrer">alt text http://www.freeimagehosting.net/uploads/397a7cd49e.png</a></p>
<p>How could I not make the canvas react when it is on a tool, or how could I make the button catch the click first and tell the canvas no to do draw anything.</p>
<p>Of course I could just put the toolbar somewhere else not on the canvas, but since space is important I would like the buttons to be on the canvas.</p>
<p>I am open to any suggestions.</p>
<p>=== Here are some code to show how it works internally. ===</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:degrafa="http://www.degrafa.com/2007"
xmlns:comp="org.foo.bar.view.components.*"
layout="absolute"
title="Tableau">
<mx:Script>
<![CDATA[
import org.edorado.edoboard.ApplicationFacade;
]]>
</mx:Script>
<mx:Canvas id="blackBoard">
<degrafa:Surface id="boardSurfaceContainer">
skinning
</degrafa:Surface>
<!-- Tool bar -->
<comp:ToolbarView
id = "toolbar"
name = "toolbar"
verticalScrollPolicy="off"
horizontalScrollPolicy="off"
bottom="5"
right="5"
top="5"
direction="vertical"
width="30" />
<mx:Label x="10" y="10" text="Label" color="#FFFFFF" id="lbl"/>
</mx:Canvas>
</mx:Panel>
</code></pre>
<p>The toolbar is a list of buttons contained in a tile.
The canvas 'blackboard' is linked to several events handling, in particular mouse up down and move for drawing shapes.</p>
<pre><code>...
boardCanvas.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
boardCanvas.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
...
private function handleMouseDown(event:MouseEvent):void {
// Get the current mouse location which may be adjusted to the grid
var selectPoint:Point = boardCanvas.globalToLocal(new Point(event.stageX, event.stageY));
startPoint = snapPoint(selectPoint.x, selectPoint.y);
boardView.lbl.text = '(' + startPoint.x +',' + startPoint.y + ')';
....
</code></pre>
<p>The toolbar also listen to clicks</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Tile xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.charts.BubbleChart;
import org.edorado.edoboard.view.components.shapes.*;
public static const TOOL_CHANGE:String = "toolChange";
public static const TEXT_TOOL:String = "textTool";
public static const SELECT_TOOL:String = "selectTool";
public static const RECTANGLE_TOOL:String = "rectangleTool";
private var b:Button = null;
private function handleButtonClick(event:MouseEvent):void {
trace("CLICKED TOOL");
// selectButton.dispatchEvent(new Event(TOOL_CHANGE, true, true))
b = event.target as Button;
b.dispatchEvent(new Event(TOOL_CHANGE, true, true));
}
]]>
</mx:Script>
<!-- Use class facotry ? -->
<mx:Button id="selectButton"
name="{SELECT_TOOL}"
selectedUpSkin="assets.skins.ToolButtonSkin"
width="30"
height="30"
styleName="selectButton"
toolTip="selection"
click="handleButtonClick(event); " />
<mx:Button id="textButton"
name = "{TEXT_TOOL}"
selectedUpSkin="assets.skins.ToolButtonSkin"
width="30"
height="30"
styleName="textButton"
toolTip="text"
click="handleButtonClick(event);" />
<mx:Button id="rectButton"
name = "{RECTANGLE_TOOL}"
selectedUpSkin="assets.skins.ToolButtonSkin"
width="30"
height="30"
styleName="rectButton"
toolTip="rectButton"
click="handleButtonClick(event);" />
</mx:Tile>
</code></pre>
|
<p>Well, int64 uses 8 byte of memory storage, while int uses 4 byte... however, you pointed out most of the disadvantages already. Of course calculations performed will also be slower on many systems (a 64 bit system running in 64 bit mode can perform operations on 64 bit as fast as on 32 bit, but a 32 bit system needs to perform extra work, that means adding two 64 bit numbers is performed by two 32 bit adds plus some extra code - other math operations will be equally broken down into 32 bit operations). However unless you store millions of these numbers and perform tons of operations with them, I doubt you will see any performance difference, though, neither in CPU time nor in memory.</p>
|
<p>Portability... though C# isn't really know as lingua franca if you're going for portable, so this might be moot for your perspective?</p>
| 30,087
|
<p>When there are one of more columns that reference another, I'm struggling for the best way to update that column while maintaining referential integrity. For example, if I have a table of labels and descriptions and two entries:</p>
<pre><code>Label | Description
------------------------------------
read | This item has been read
READ | You read this thing already
</code></pre>
<p>Now, I don't want these duplicates. I want to add a constraint to the column that doesn't allow values that are case-insensitively duplicates, as in the example. However, I have several rows of several other tables referencing 'READ', the one I want to drop.</p>
<p>I know Postgres knows which fields of other rows are referencing this, because I can't delete it as long as they are there. So, how could I get any field referencing this to update to 'read'? This is just an example, and I actually have a few places I want to do this. Another example is actually an int primary key for a few tables, where I want to add a new table as a sort of 'base table' that the existing ones extend and so they'll all need to have unique IDs now, which means updating the ones they have.</p>
<p>I am open to recipes for functions I can add to do this, tools I can utilize, or anything else.</p>
|
<p>If you have many rows referencing READ, you could alter the foreign key to be on cascade update, update that table set Label = 'read' where Label = 'READ' and everything will get automagically fixed. After that you can alter the constraint again to be as it was before.</p>
<p>To find all the tables referencing the column, you can use</p>
<pre><code>select TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME from
INFORMATION_SCHEMA.KEY_COLUMN_USAGE where
REFERENCED_TABLE_NAME = '<table>' AND REFERENCED_COLUMN_NAME = '<column>'
</code></pre>
|
<p>For the future you could create an unique index on the column "label", for example:</p>
<pre><code>CREATE UNIQUE INDEX index_name ON table ((lower(label)));
</code></pre>
<p>Or check the <a href="http://www.postgresql.org/docs/current/static/sql-createindex.html" rel="nofollow noreferrer">manual</a>.
That would help you to avoid this situation for the next time.</p>
| 29,479
|
<p>I have a database table called "Posts" which stores all the information regarding an article submission on a website. There is a column named "Views" which is a value that gets incremented each time that particular post gets viewed. </p>
<p>The process is this:</p>
<ol>
<li>Get the record from the database </li>
<li>Increment the current by one</li>
<li>Save the changes to the database.</li>
</ol>
<p>Pretty straightforward. My concern is that if multiple people click the link at the same time, the updates wont be accurate. How should I approach this? Should this only be done ina stored procedure?</p>
<pre><code> /// <summary>
/// Updates the view count of a post.
/// </summary>
/// <param name="postId">The Id of the post to update</param>
public bool UpdateViewCount(int postId)
{
Repository repository = new Repository();
Post p = repository.Posts.Where(p => p.Id == postId).SingleOrDefault();
if (p != null)
{
p.Views++;
}
repository.SubmitChanges(System.Data.Linq.ConflictMode.ContinueOnConflict);
}
</code></pre>
|
<p>Do it in one go:</p>
<pre><code>UPDATE table SET views=views+1 WHERE myId=12;
</code></pre>
|
<p>If your db context is called _db you can use this.</p>
<pre><code>_db.ExecuteCommand("UPDATE posts SET views=views+1 WHERE id={0}", postId);
</code></pre>
<p>for further reading check out the Gu's post here.</p>
<p><a href="http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx</a></p>
| 49,284
|
<p>When trying to launch and run a flex/java project in eclipse I kept getting a "Out of Memory Exception" and "Java Heap Space" using Eclipse, Tomcat and a JRE.</p>
<p>While researching trying to adjust the memory settings I found three places to adjust these:</p>
<ul>
<li><p>Eclipse.ini</p></li>
<li><p>The JRE Settings under Window > Preferences</p></li>
<li><p>Catalina.sh or Catalina.bat</p></li>
</ul>
<p>What are the differences between setting -xms and -xmx in these different places and what does is mean?</p>
<p>Is there any way to verify these memory settings are being set accordingly?</p>
<p>What are the optimal -xms and -xmx settings for a computer with 2gb of RAM?</p>
<p>Any other memory tips?</p>
<p>Thanks.</p>
|
<p>-xms is the start memory (at the VM start), -xmx is the maximum memory for the VM</p>
<ul>
<li>eclipse.ini : the memory for the VM running eclipse</li>
<li>jre setting : the memory for java programs run from eclipse</li>
<li>catalina.sh : the memory for your tomcat server</li>
</ul>
|
<p>If you see an out of memory, consider if that is plausible: Do you really need that much memory? If not (i.e. when you don't have huge objects and if you don't need to create millions of objects for some reason), chances are that you have a memory leak.</p>
<p>In Java, this means that you're keeping a reference to an object somewhere even though you don't need it anymore. Common causes for this is forgetting to call close() on resources (files, DB connections, statements and result sets, etc.).</p>
<p>If you suspect a memory leak, use a profiler to find which object occupies all the available memory.</p>
| 43,312
|
<p>In my case, I have a number of column names coming from a form. I want to filter to make sure they're all true. Here's how I currently do it:</p>
<pre><code>for op in self.cleaned_data['options']:
cars = cars.filter((op, True))
</code></pre>
<p>Now it <em>works</em> but there are are a possible ~40 columns to be tested and it therefore doesn't appear very efficient to keep querying.</p>
<p>Is there a way I can condense this into one filter query?</p>
|
<p>Build the query as a dictionary and use the ** operator to unpack the options as keyword arguments to the filter method.</p>
<pre><code>op_kwargs = {}
for op in self.cleaned_data['options']:
op_kwargs[op] = True
cars = CarModel.objects.filter(**op_kwargs)
</code></pre>
<p>This is covered in the <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-all-objects" rel="nofollow noreferrer">django documentation</a> and has been covered on <a href="https://stackoverflow.com/questions/310732/in-django-how-does-one-filter-a-queryset-with-dynamic-field-lookups">SO</a> as well.</p>
|
<p>Build the query as a dictionary and use the ** operator to unpack the options as keyword arguments to the filter method.</p>
<pre><code>op_kwargs = {}
for op in self.cleaned_data['options']:
op_kwargs[op] = True
cars = CarModel.objects.filter(**op_kwargs)
</code></pre>
<p>This is covered in the <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-all-objects" rel="nofollow noreferrer">django documentation</a> and has been covered on <a href="https://stackoverflow.com/questions/310732/in-django-how-does-one-filter-a-queryset-with-dynamic-field-lookups">SO</a> as well.</p>
| 46,038
|
<p>I am working on an ASP site hosted using SUN One (used to be called Chillisoft) server. I am having trouble loading in an XML file, the code I am using is below</p>
<pre><code>dim directory
set directory = Server.CreateObject("MSXML2.DOMDocument")
if(directory.load(Server.MapPath("directory.xml"))) then
Response.Write("Loaded")
else
Response.Write("NotLoaded")
If directory.parseError.errorCode Then
Response.Write( "Parse error" )
end if
end if
</code></pre>
<p>My asp page and directory.xml are both in the same folder "/public_html/".</p>
<p>I think the problem might have something to do with the mappath not finding the file, but no errors are returned so not sure what to do.</p>
<p>Thanks</p>
|
<p>I don't know much about Sun One but I do know it has a Bean that emulates MSXML.</p>
<p>Oridinarily, you would use:-</p>
<pre><code>Set directory = Server.CreateObject("MSXML2.DOMDocument")
directory.async = false
directory.load(Server.MapPath("directory.xml")
</code></pre>
<p>Otherwise load returns immeadiately whilst the xml is loaded asynchronously.</p>
<p>It can't see how the code you have posted would not return something without error.</p>
<p>First diagnositic I would is:-</p>
<pre><code>Response.Write(Server.MapPath("directory.xml"))
</code></pre>
<p>and then</p>
<pre><code>Dim direcotory
Set directory = Server.CreateObject("MSXML.DOMDocument")
Response.Write(Not (directory Is Nothing))
</code></pre>
|
<p>The load likely returns false because it hasn't fully loaded the document yet. You need to find a way to set async to false. If the Sun One is emulating MSXML2.DOMDocument well then async should accept false but you could try -<code>1</code> or <code>Response.Write(directory.async)</code> to get an idea of what it is originally set to.</p>
| 19,480
|
<p>We need a good CMS that supports data clustering (managing and storing data on different servers). By "good" , I mean : reliable , minimum bugs , the faster the better. (Oh , and it should make coffee :) ) </p>
|
<p>Yes … kitchen sink + community + support: Plone. Development heading very much in the right direction. </p>
<p>Plone is in some ways a different creature from many other systems. Depending on the environment, ultra-high performance may require some attention but in the community there's great expertise to steer any attention that may be required.</p>
<p><a href="http://plone.org/support" rel="nofollow noreferrer">http://plone.org/support</a> | Chat Room is a great venue for diverse and honest advice on this subject. We regularly steer people away from Plone -- when some other system will better suit their needs. </p>
|
<p>I am not sure about "Performance-oriented" means for you. There are sites with Drupal and Joomla that receives million of visits month after month, and do not need special configurations like data clustering.</p>
<p>I think you must ask yourself if you need all you said.</p>
<p>For reliability, and no bugs or minimum bugs i can stand for Joomla.</p>
<p>I think the performance is a function of the hardware.</p>
| 9,521
|
<p>How can I assign a keyboard shortcut to a VBA macro in Outlook 2007?</p>
<p>I know how to create a tool for the macro and put it in a menu with an underscore shortcut. This solution requires me to use a shortcut of <kbd>Alt</kbd> + <kbd>{menu key}</kbd> + <kbd>{tool key}</kbd>. What if I want to assign it to <kbd>Alt</kbd> + <kbd>F12</kbd> or something like that?</p>
<p>The Visual Basic Editor is assigned to the keyboard shortcut <kbd>Alt</kbd> + <kbd>F11</kbd> in Outlook 2007. I want to assign a keyboard shortcut like that to a macro, or if necessary a macro on a tool in either a menu or a toolbar.</p>
|
<p>Since Outlook doesn't have the OnKey event, the easiest way is to assign a toolbar button to the macro and put an ampersand in its name somewhere. This only works if your shortcut letter doesn't conflict with an existing shortcut.</p>
<p>You may also have luck with setting a global hotkey, but it's usually more pain then it's worth:</p>
<p><a href="http://www.mvps.org/vbvision/_samples/HotKey_Demo.zip" rel="noreferrer">http://www.mvps.org/vbvision/_samples/HotKey_Demo.zip</a></p>
|
<p>Since Outlook doesn't have the OnKey event, the easiest way is to assign a toolbar button to the macro and put an ampersand in its name somewhere. This only works if your shortcut letter doesn't conflict with an existing shortcut.</p>
<p>You may also have luck with setting a global hotkey, but it's usually more pain then it's worth:</p>
<p><a href="http://www.mvps.org/vbvision/_samples/HotKey_Demo.zip" rel="noreferrer">http://www.mvps.org/vbvision/_samples/HotKey_Demo.zip</a></p>
| 8,127
|
<p>I use emacs for viewing and editing code and other text files. I wanted to know if there is a way to search forward or backward for text which is marked in the current buffer. Similar to what I can do in notepad or wordpad. As in can I mark some text in the buffer and do a C-s or C-r and be able to search with the marked text without actually typing in the whole search text? </p>
<p>Thank you,</p>
<p>Rohit</p>
|
<p>@Alex nails it.</p>
<p>Another option I use quite often is <code>C-s C-w</code> to search for the word after the current mark. Hitting <code>C-w</code> repeatedly increases the search with additional words (e.g., <code>C-s C-w C-w C-w</code> searches for the 3 words after the current mark).</p>
<p>Similarly, <code>C-s M-s C-e</code> searches for the rest of the line after the current mark and <code>C-s C-M-y</code> searches for the character after the mark. These are both repeatable in the same way (the former by somewhat-awkwardly repeating <code>M-s C-e</code> after <code>C-s</code>).</p>
|
<p>You can find C-s help by doing C-h k C-s, and it says:</p>
<blockquote>
<p>Type DEL to cancel last input item from end of search string. Type RET
to exit, leaving point at location found. Type LFD (C-j) to match end
of line. Type C-s to search again forward, C-r to search again
backward. <strong><em>Type C-w to yank next word or character in buffer</em></strong> onto the
end of the search string, and search for it. Type C-M-w to delete
character from end of search string. Type C-M-y to yank char from
buffer onto end of search string and search for it. Type M-s C-e to
yank rest of line onto end of search string and search for it. Type
C-y to yank the last string of killed text. Type M-y to replace string
just yanked into search prompt with string killed before it. Type C-q
to quote control character to search for it. Type C-x 8 RET to add a
character to search by Unicode name, with completion. C-g while
searching or when search has failed cancels input back to what has
been found successfully. C-g when search is successful aborts and
moves point to starting point.</p>
<p>If you try to exit with the search string still empty, it invokes
nonincremental search.</p>
<p>Type M-c to toggle search case-sensitivity. Type M-s i to toggle
search in invisible text. Type M-r to toggle regular-expression mode.
Type M-s w to toggle word mode. Type M-s _ to toggle symbol mode. Type
M-s ' to toggle character folding.</p>
<p>Type M-s SPC to toggle whitespace matching. In incremental searches, a
space or spaces normally matches any whitespace defined by the
variable ‘search-whitespace-regexp’; see also the variables
‘isearch-lax-whitespace’ and ‘isearch-regexp-lax-whitespace’.</p>
<p>Type M-s e to edit the search string in the minibuffer.</p>
<p>Also supported is a search ring of the previous 16 search strings.
Type M-n to search for the next item in the search ring. Type M-p to
search for the previous item in the search ring. Type C-M-i to
complete the search string using the search ring.</p>
<p>Type M-% to run ‘query-replace’ with string to replace from last
search string. Type C-M-% to run ‘query-replace-regexp’ with the last
search string. Type M-s o to run ‘occur’ that shows the last search
string. Type M-s h r to run ‘highlight-regexp’ that highlights the
last search string.</p>
<p>Type C-h b to display all Isearch key bindings. Type C-h k to display
documentation of Isearch key. Type C-h m to display documentation of
Isearch mode.</p>
</blockquote>
| 24,806
|
<p>It's been a while since I used Java in anger so please forgive me if this is silly.</p>
<p>I have just got started on a Java project where we are using JAXB to de-serializing an incoming XML string (from Jetty Server). The project is only using JAXB for this situation.</p>
<p>What are the alternatives to JAXB?<br>
What are pros/cons of JAXB to these alternatives<br></p>
<p>I have done some googling and found lots of reference material, but is there a definitive source that is the goto place for JAXB questions or do people just see what people are doing and interpret from there.</p>
<p>Thanks.</p>
|
<p>I've found JAX-B pretty useful and actually like it better than many of the alternatives, especially if I'm starting from scratch and generating a schema from Java objects rather than Java objects from a schema. </p>
<p>In my experience, for whatever reason, I've found good documentation hard to come by from just Google searches. The best electronic documentation is provided in the JAX-B download where you'll also find numerous examples. "<a href="https://rads.stackoverflow.com/amzn/click/com/0130449687" rel="nofollow noreferrer" rel="nofollow noreferrer">SOA Using Java Web Services</a>" also has a good overview.</p>
<p>As for alternatives, there is:</p>
<ul>
<li><a href="http://xstream.codehaus.org/" rel="nofollow noreferrer">XStream</a></li>
<li><a href="http://castor.codehaus.org/xml-framework.html" rel="nofollow noreferrer">Castor</a></li>
</ul>
<p>and probably several more.</p>
|
<p>For alternatives to JAXB you might want to check out XFire (<a href="http://xfire.codehaus.org/" rel="nofollow noreferrer">http://xfire.codehaus.org/</a>) or Axis2 (<a href="http://ws.apache.org/axis2/" rel="nofollow noreferrer">http://ws.apache.org/axis2/</a>). Those seem to be 2 popular alternatives, and I believe both are now JAX-WS complaint.</p>
| 48,583
|
<p>I've tried to the letter to search for mistakes in my code, but i can't myself get that autocomplete extender to work. Help wanted. </p>
<p>Here's my code: (excerpt from my aspx page) </p>
<pre><code> <asp:TextBox ID="TextBox1" Width="120px" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="TextBox1" ServiceMethod="GetCompletionList" ServicePath="SearchAutoComplete.asmx" MinimumPrefixLength="1">
</cc1:AutoCompleteExtender>
</code></pre>
<p>My Webservice code: </p>
<pre><code> [WebMethod]
public static string[] GetCompletionList(string prefixText, int count)
{
List<string> returnData = new List<string>();
MySqlConnection con = new MySqlConnection(Connection.ConnectionString());
string sql = "select title from blog where title like '%" + prefixText + "%'";
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
returnData.Add(reader["title"].ToString());
}
return returnData.ToArray();
}
</code></pre>
|
<p>How to troubleshoot this:</p>
<p>Comment out your SQL code. Just return an array with some test data. Does that work? Do you see it? If not, your webservice code is not getting called. If that works, your problem is with your database code.... Is your webservice code on the calling page?</p>
|
<p>I think your problem is that the <code>GetCompletionList</code> method is declared <code>static</code>.</p>
<p>If you run up just the .asmx code in a debugger session (or browse to the .asmx file if you have deployed your code to a webserver) you should see a list of available operations for the web-service. When I change the code in the Ajax control toolkit examples to declare this method as static the operation is no longer in the list and the autocomplete extender also stops working.</p>
<p>Change your method signature to:</p>
<pre><code>public string[] GetCompletionList(string prefixText, int count)
</code></pre>
| 40,253
|
<p>I know there is done some research on TDD at the North Carolina State University. They have published a paper called '<a href="http://collaboration.csc.ncsu.edu/laurie/Papers/TDDpaperv8.pdf" rel="nofollow noreferrer">An Initial Investigation of Test Driven Development in Industry</a>'. Other publications by NCSU can be found <a href="http://collaboration.csc.ncsu.edu/laurie/publications.html" rel="nofollow noreferrer">here</a>.</p>
<p>Can anybody point me to other good publications on this topic? </p>
|
<p><a href="http://www.cs.du.edu/~snarayan/sada/teaching/COMP3705/lecture/p1/NRC-47445.pdf" rel="nofollow noreferrer">On the Effectiveness of the Test-First Approach to Programming</a>, by Hakan Erdogmus, Maurizio Morisio, and Marco Torchiano. </p>
<p>Despite the name it covers TDD:</p>
<p>Abstract:</p>
<blockquote>
<p>Test-Driven Development (TDD) is based
on formalizing a piece of
functionality as a test, implementing
the functionality such that the test
passes, and iterating the process.</p>
<p>This paper describes a controlled
experiment for evaluating an important
aspect of TDD: In TDD, programmers
write functional tests before the
corresponding implementation code. The
experiment was conducted with
undergraduate students. While the
experiment group applied a test-first
strategy, the control group applied a
more conventional development
technique, writing tests after the
implementation. Both groups followed
an incremental process, adding new
features one at a time and regression
testing them. </p>
<p>We found that test-first
students on average wrote more tests
and, in turn, students who wrote more
tests tended to be more productive. We
also observed that the minimum quality
increased linearly with the number of
programmer tests, independent of the
development strategy employed.</p>
</blockquote>
|
<p>As a TDD Practitioner myself, I have launched a new site <a href="http://WeDoTDD.com" rel="nofollow">WeDoTDD.com</a> that lists just that. Companies practicing it, and stories behind how they practice Test Driven Development!</p>
| 19,868
|
<p>I have a stored procedure currently executing a complicated fetch that is frequently timing out when used. The proposed solution in my department has been to simply increase the timeout time length; which I don't really want to do. I'd like to refactor this sproc, but because it's so complicated and undocumented (yay legacy systems) I'm concerned my refactoring my not result in the same functionality executing more efficiently. Are there any strategies to use when refactoring a stored procedure to ensure the same functions are being performed in less time?</p>
<p>This is a Microsoft SQL Server 2005 stored procedure.</p>
|
<p>I have been faced with this situation in the past. The best thing to do is create a simple C# or VB .Net application. When you refactor the sp, give it a new name. Use the application to call both the old and new sp's. Then compare the output of the two sp's to ensure they return the exact same values in the same order.</p>
<p>You would want to test as wide a variety of input parameters as you can to ensure your refactoring hasn't modified the business logic.</p>
<p>Also, using NUnit can help simplify this task.</p>
<p>When I started my current position, I was given a database that had to be modified for a new schema. It required changing over 100 sp's. Using the application I've described, I was able to be reasonably sure that one of my modifications did not break the business rules.</p>
<p>You're right, just increasing the timeout is the wrong first answer. Improve the sp as best you can, then increase the timeout if necessary.</p>
|
<p>Use the <a href="http://msdn.microsoft.com/en-us/library/ms187929.aspx" rel="nofollow noreferrer">SQL Server Profiler</a> to study how the current SP runs; it will highlight inefficiencies and allow you to target just those specific areas to begin with, whilst leaving the more performant bits alone. You can then use the profiler again on your revised SP to compare performance.</p>
<p>I would echo Gunny's recommendation to take a good look at function calls - in set based operations these can have a real impact on performance. I've achieved massive performance gains in the past just by stripping out a single UDF and replicating the logic inline.</p>
| 27,001
|
<p>How do I use the softkeys with a CDialog based application in windows mobile 6 via MFC?</p>
<p>I have a CDialog based Windows Mobile 6 (touchscreen) Professional app that I am workign on.</p>
<p>The default behavior of a CDialog based app in WM6 Professional is to not use any softkeys by default... I want to map the softkeys to "Cancel" and "OK" functionality that sends IDOK and IDCANCEL to my Main Dialog class.</p>
<p>I have been trying to work with CCommandBar with no luck, and SHCreateMenuBar was not working out for me either. </p>
<p>Does anyone have a sample of how to get this to work?</p>
|
<p>What's "not working" with the CCommandBar for you? You should be able to add a CCommandBar member to your dialog class, then in teh DIalog's InitDialog you call Create and InsertMenuBar on the command bar - something like this:</p>
<pre><code>m_cmdBar.Create(this);
m_cmdBar.InsertMenuBar(IDR_MENU_RESRC_ID);
</code></pre>
<p>Your menu resource might look something like this:</p>
<pre><code>IDR_MENU_RESRC_ID MENU DISCARDABLE
BEGIN
MENUITEM "OK", IDOK
MENUITEM "Cancel", IDCANCEL
END
</code></pre>
|
<p>thank you so much... I was going crazy with this...</p>
<p>your code worked exactly as expected... </p>
<p>At first I used it and had the same results, the softkey area would be blank except for the SIP input button.</p>
<p>After an hour or so of debugging I tried putting those 2 lines of code at the END of my OnInitDIalog() and it worked :)</p>
<p>My problem ende dup being that in my OnIitDialog() I am creating some child dialogs. when I put the CCommandBar.InsertMenuBar() before I create child dialogs I do not get my "ok" or "Cancel" soft keys, when I put that line after the creation of child dialogs the softkeys show as expected and work great.</p>
<p>Thanks again</p>
| 13,127
|
<p>I'm have a ADO DataSet that I'm loading from its XML file via ReadXml. The data and the schema are in separate files.</p>
<p>Right now, it takes close to 13 seconds to load this DataSet. I can cut this to 700 milliseconds if I don't read the DataSet's schema and just let ReadXml infer the schema, but then the resulting DataSet doesn't contain any constraints.</p>
<p>I've tried doing this:</p>
<pre><code>Console.WriteLine("Reading dataset with external schema.");
ds.ReadXmlSchema(xsdPath);
Console.WriteLine("Reading the schema took {0} milliseconds.", sw.ElapsedMilliseconds);
foreach (DataTable dt in ds.Tables)
{
dt.BeginLoadData();
}
ds.ReadXml(xmlPath);
Console.WriteLine("ReadXml completed after {0} milliseconds.", sw.ElapsedMilliseconds);
foreach (DataTable dt in ds.Tables)
{
dt.EndLoadData();
}
Console.WriteLine("Process complete at {0} milliseconds.", sw.ElapsedMilliseconds);
</code></pre>
<p>When I do this, reading the schema takes 27ms, and reading the DataSet takes 12000+ milliseconds. And that's the time reported <em>before</em> I call EndLoadData on all the DataTables.</p>
<p>This is not an enormous amount of data - it's about 1.5mb, there are no nested relations, and all of the tables contain two or three columns of 6-30 characters. The only thing I can figure that's different if I read the schema up front is that the schema includes all of the unique constraints. But BeginLoadData is supposed to turn constraints off (as well as change notification, etc.). So that shouldn't apply here. (And yes, I've tried just setting EnforceConstraints to false.)</p>
<p>I've read many reports of people improving the load time of DataSets by reading the schema first instead of having the object infer the schema. In my case, inferring the schema makes for a process that's about 20 times faster than having the schema provided explicitly.</p>
<p>This is making me a little crazy. This DataSet's schema is generated off of metainformation, and I'm tempted to write a method that creates it programatically and just deseralizes it with an XmlReader. But I'd much prefer not to.</p>
<p>What am I missing? What else can I do to improve the speed here?</p>
|
<p>It's not an answer, exactly (though it's better than nothing, which is what I've gotten so far), but after a long time struggling with this problem I discovered that it's completely absent when my program's not running inside Visual Studio. </p>
<p>Something I didn't mention before, which makes this even more mystifying, is that when I loaded a different (but comparably large) XML document into the DataSet, the program performed just fine. I'm now wondering if one of my DataSets has some kind of metainformation attached to it that Visual Studio is checking at runtime while the other one doesn't. I dunno.</p>
|
<p>Another dimesion to try is to read the dataset without the schema and then <a href="http://msdn.microsoft.com/en-us/library/06t089d7.aspx" rel="nofollow noreferrer"><strong><em>Merge</em></strong></a> it into a typed dataset that has the constraints enabled. That way it has all of the data on hand as it builds the indexes used to enforce constraints -- maybe it would be more efficient?</p>
<p>From <a href="http://msdn.microsoft.com/en-us/library/06t089d7.aspx" rel="nofollow noreferrer">MSDN</a>:</p>
<blockquote>
<p>The Merge method is typically called
at the end of a series of procedures
that involve validating changes,
reconciling errors, updating the data
source with the changes, and finally
refreshing the existing DataSet</p>
</blockquote>
<p>. </p>
| 39,559
|
<p>I like LINQ to SQL, but it seems like the classes it generates are tightly coupled to the database they are stored in, which seems like a Bad Thing. </p>
<p>For example, using ye olde Northwind database, if I create the dbml with the Products table, a <code>Product</code> class is generated. I can use this class in any other tier, which is all well and good, but if I decide I'd rather use plain old ADO.NET (or switch databases), I'll have to recreate the <code>Product</code> class, along with every other "model."</p>
<p>Is there a way around this? Or to create your object models separately, and then have the tables mapped to them? I've played around with the various mapping classes provided, but haven't found a satisfactory answer yet.</p>
|
<p>All these answers and no links! Maybe I can help:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic3" rel="nofollow noreferrer">The attributes thing that damieng mentioned</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb546176.aspx" rel="nofollow noreferrer">The partial class thing that Marcus King mentioned</a></p>
<p>I have languished through this difficulty a couple of times, what I ended up doing on my last project was using interfaces as the contract that's shared between all of the different projects in the solution, and having the partial classes implement it.</p>
<pre><code>[Table(Name="Products")]
public partial class Product: IProduct { }
</code></pre>
<p>And yes, unfortunately it took some reflection magic to make it work for the POCO implementation.</p>
<p>In the end, if you are truly concerned about it, I'd go with NHibernate (I don't really like it either), which does exactly what Garry Shulter seems to be describing.</p>
<p>Hope that helps!</p>
|
<p>Just copy the generated code into your own classes and switch off the code generation. The magic is in the attributes not anything else.</p>
<p>Alternatively you can write your own plain CLR objects without the attributes and use an external XML mapping file to describe the relationship between the objects and the database. More information can be found in the LINQ to SQL documentation on MSDN.</p>
| 27,507
|
<p>How can I retrieve the page title of a webpage (title html tag) using Python?</p>
|
<p>I'll always use <a href="http://lxml.de/" rel="nofollow noreferrer">lxml</a> for such tasks. You could use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow noreferrer">beautifulsoup</a> as well.</p>
<pre><code>import lxml.html
t = lxml.html.parse(url)
print(t.find(".//title").text)
</code></pre>
<p>EDIT based on comment:</p>
<pre><code>from urllib2 import urlopen
from lxml.html import parse
url = "https://www.google.com"
page = urlopen(url)
p = parse(page)
print(p.find(".//title").text)
</code></pre>
|
<p>Using lxml...</p>
<p>Getting it from page meta tagged according to the Facebook opengraph protocol:</p>
<pre><code>import lxml.html.parse
html_doc = lxml.html.parse(some_url)
t = html_doc.xpath('//meta[@property="og:title"]/@content')[0]
</code></pre>
<p>or using .xpath with lxml:</p>
<pre><code>t = html_doc.xpath(".//title")[0].text
</code></pre>
| 7,423
|
<p>Stuggling a little bit with the RegEx, I've got 4 codes in a string</p>
<p>CODE4:CODE3:CODE2:CODE1</p>
<p>each code is optional apart from CODE1</p>
<p>So I could have ab:bc:de:fg</p>
<p>or</p>
<p>bc::fg</p>
<p>of </p>
<p>ab:::fg</p>
<p>In each case of the above CODE1 = fg dnd for the dear life of me I can't work out the RegEX</p>
<p>Would be easy to do as a standard string parse, but unforunatly because of buisness objects in needs to be done via regex :-( and return via a vb.net RegEX.matche,groups("Code1") fg (I hope that makes sense)</p>
<p>Thanks in advance for any help</p>
<p>Ended up with a bit of RegEx that does the job, bit messy but it works</p>
<pre><code>(^(?<code1>[\w]*)$)|(^(?<code2>[\w]*):(?<code1>[\w]*)$)|(^(?<code3>[\w]*):(?<code2>[\w]*):(?<code1>[\w]*)$)|(^(?<code4>[\w]*):(?<code3>[\w]*):(?<code2>[\w]*):(?<code1>[\w]*)$)
</code></pre>
<p>Ta all</p>
|
<p>There's no need to use a regular expression here.</p>
<p>I don't know what language you're using, but split the string on ':' and you'll have an array of codes.</p>
<p>If you really just want to validate whether a string is valid for this then</p>
<pre><code>/(\w*:){0,3}\w+/
</code></pre>
<p>matches your description and the few examples you've given.</p>
|
<p>I'm not sure why you have to match the codes right to left. Simply use a regular expression to pick apart the string:</p>
<pre><code>/(.*):(.*):(.*):(.+)/
</code></pre>
<p>and then you have CODE1 in $4, CODE2 in $3, CODE3 in $2, CODE4 in $1.</p>
| 49,884
|
<p>I have printed a MPCNC machine. It has a print area of about 30" x 30" and up to 11" tall. (yes, those numbers are correct).</p>
<p>I found a perfect piece of glass at a garage sale for $5.00 to use as my print bed. </p>
<p>My problem now is how to heat the glass? I was wondering if there is some sort of tape that would perhaps mimic what is on the rear window of a car, but I couldn't find it anywhere.</p>
<p>Any ideas or links to something that can get me some progress on my search would be greatly appreciated.</p>
|
<p>Your best option may be to seek out a silicone rubber heating mat, using those terms for your web search. A quick search on my part shows many resources, some of which are known to the 3d printing manufacturing world, while others are equally suited for that purpose.</p>
<p>Don't bond the heater to the glass. You'll need to replace it when it breaks. Consider to use borosilicate glass for better heat tolerance and smaller chance of breakage. A quick search for such a large size pane comes up empty, invalidating that suggestion.</p>
<p>I've read of some people using water bed heaters for large area coverage, but they may heat the area unevenly.</p>
<p>It could be to your advantage to use multiple heater panels with temperature controls for each one. This would provide more uniform heating although more complex temperature management.</p>
<p>I would post links, but there are so many from which to choose.</p>
|
<p>Maybe you can stick a <a href="https://en.wikipedia.org/wiki/Nichrome" rel="nofollow" title="nichrome">nichrome</a> wire under the glass using a heat resistant tape. You'll have to make the appropriate calcs (or just trial/error) to achieve the desired temperature at a consistent timing.</p>
| 370
|
<p>I've got this code:</p>
<pre><code>rs1 = getResults(sSQL1)
rs2 = getResults(sSQL2)
</code></pre>
<p>rs1 and rs2 and 2D arrays. The first index represents the number of columns (static) and the second index represents the number of rows (dynamic).</p>
<p>I need to join the two arrays and store them in rs3. I don't know what type rs1 and rs2 are though.</p>
|
<p>I've figured it out. Turns out I was doing it the right way all along, I was just off by one. You don't need a third array either.</p>
<pre><code> aRS_RU = rowsQuery(sSQL & ", 'RU'")
aRS_KR = rowsQuery(sSQL & ", 'KR'")
uboundRU1 = UBound(aRS_RU, 1)
uboundRU2 = UBound(aRS_RU, 2)
uboundKR2 = Ubound(aRS_KR, 2)
' Redim original array
ReDim Preserve aRS_RU(uboundRU1, uboundRU2 + uboundKR2 + 1 )
uboundRU2 = UBound(aRS_RU, 2)
' Add the values from the second array
For m = LBound(aRS_KR, 1) To UBound(aRS_KR, 1) 'Loop for 1st dimension
For n = LBound(aRS_KR, 2) To UBound(aRS_KR, 2) 'Loop for 2nd dimension
aRS_RU(m, uboundRU2 + n) = aRS_KR(m,n)
Next
Next
</code></pre>
|
<p>I know this post is old, but I adapted the code to fix some errors I had during its execution. The following code sample works for me:</p>
<pre><code>Sub ConcatRecordSets(ByRef avFirstRS As Variant, ByRef avSecondRS As Variant)
Dim lIndex1 As Long, lIndex2 As Long
Dim lFirstRSSize As Long, lSecondRSSize As Long
' Redim original array
lFirstRSSize = UBound(avFirstRS, 2) - LBound(avFirstRS, 2) + 1
lSecondRSSize = UBound(avSecondRS, 2) - LBound(avSecondRS, 2) + 1
ReDim Preserve avFirstRS(LBound(avFirstRS, 1) To UBound(avFirstRS, 1), LBound(avFirstRS, 2) To UBound(avFirstRS, 2) + lSecondRSSize)
' Add the values from the second array
For lIndex1 = LBound(avSecondRS, 1) To UBound(avSecondRS, 1) ' Loop for 1st dimension
For lIndex2 = LBound(avSecondRS, 2) To UBound(avSecondRS, 2) ' Loop for 2nd dimension
avFirstRS(lIndex1, lFirstRSSize + lIndex2) = avSecondRS(lIndex1, lIndex2)
Next lIndex2
Next lIndex1
End Sub
</code></pre>
| 21,086
|
<p>Due to the packaged nature of the release, a SQL Server script (well more of a statement) needs to be created that can execute correctly on SQL Server 7.0 thru 2008 which can essentially achieve this:</p>
<pre><code>if exists(select * from sys.databases where name = 'Blah')
</code></pre>
<p>Reasons this is difficult:</p>
<p>SQL 7 'sys.databases' is not valid</p>
<p>SQL 2008 'sysdatabases' is not valid</p>
<p>I stupidly parsed out the version number using serverproperty, to allow an IF depending on the version:</p>
<pre><code>if (select CONVERT(int,replace(CONVERT(char(3),serverproperty ('productversion')),'.',''))) >= 80
</code></pre>
<p>Then discovered serverproperty does not exist under SQL 7.</p>
<p>Note that the SQL can be remote from the install, so no futzing around on the local machine - reg entries/file versions etc is of any use. </p>
<p>SQL Server error handling (especially 7.0) is poor, or maybe I don't understand it well enough to make it do a kind of try/catch.</p>
<p>I am now getting problem blindness to this, so any pointers would be appreciated.</p>
<p>Thanks,</p>
<p>Gareth</p>
|
<p>Try</p>
<p>USE database </p>
<p>and test @@ERROR.</p>
<blockquote>
<p>USE database<br>
IF @@ERROR <> 0 GOTO ErrExit</p>
<p>logic ...</p>
<p>RETURN 0</p>
<p>ErrExit:<br>
RETURN 1</p>
</blockquote>
<p>(or RAISERROR, or ...)</p>
|
<p>You could try a TRY... CATCH around a USE [DatabaseName].</p>
| 47,499
|
<p>I am trying to access Outlook 2007 from C#. I have installed the PIA msi after following the directions found on msdn. After a successful install nothing shows up in Visual Studio's references under the .net tab.</p>
|
<p>Office interaction is available through COM objects found on the 'COM' tab of the 'Add Reference' dialog window.</p>
|
<p>After you downloaded the installer and ran it, did you run the MSI installer it extracted and placed in the folder it asked you to create?</p>
| 18,849
|
<p>I've got an unmanaged Linux VPS running ubuntu that I'm using for the web server for a personal website. I'd like to get a barebones email server up and running. All the installation guides I've found so far are for a full-fledged email server with a webmail interface and everything. That's a lot more than I need. There's only two things I need:</p>
<ul>
<li>My web application needs to be able to send email. Specifically, it'll be emailing me when an exception occurs.</li>
<li>I want all email sent to [anything]@domain.com forwarded to my personal gmail account. The server doesn't even need to retain the email or anything.</li>
</ul>
<p>I want to reserve resources for the actual web app, so I don't want to install anything I won't need for this.</p>
|
<p><a href="http://msmtp.sourceforge.net/" rel="nofollow noreferrer">msmtp</a> or <a href="http://untroubled.org/nullmailer/" rel="nofollow noreferrer">nullmailer</a> sounds like it would fit the bill for the former. You could use google mail for domains for the latter.</p>
|
<p>Your web application needs a SMTP server. That server can be a hosted service like Google's or <a href="https://help.ubuntu.com/community/PostfixBasicSetupHowto" rel="nofollow noreferrer">MailHop</a>. If you really want to be an email administrator postfix should be installed <a href="http://www.dyndns.com/services/mailhop/" rel="nofollow noreferrer">HOWTO is here</a>.</p>
<p>If not:</p>
<pre><code>sudo apt-get install postfix
</code></pre>
| 26,529
|
<p>I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.</p>
<p>The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?</p>
<p>To clarify from current responses:</p>
<ol>
<li>I am using the subprocess module</li>
<li>I am passing the command line + arguments in as a list</li>
<li>The issue is with the path to the command itself, not any of the arguments</li>
<li>I've tried quoting the command. It causes a <code>[Error 123] The filename, directory name, or volume label syntax is incorrect</code> error</li>
<li>I'm using no shell argument (so <code>shell=false</code>) </li>
<li>In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin</li>
<li>It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.</li>
<li>The command that is failing is: </li>
</ol>
<blockquote>
<p>p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)</p>
</blockquote>
<p>when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.</p>
|
<p>Make sure you are using lists and no shell expansion:</p>
<pre><code>subprocess.Popen(['command', 'argument1', 'argument2'], shell=False)
</code></pre>
|
<p>Try quoting the argument that contains the &</p>
<pre><code>wget "http://foo.com/?bar=baz&amp;baz=bar"
</code></pre>
<p>Is usually what has to be done in a Linux shell</p>
| 14,674
|
<p>I have a database with one table, like so:</p>
<pre><code>UserID (int), MovieID (int), Rating (real)
</code></pre>
<p>The userIDs and movieIDs are large numbers, but my database only has a sample of the many possible values (4000 unique users, and 3000 unique movies)</p>
<p>I am going to do a matrix SVD (singular value decomposition) on it, so I want to return this database as an ordered array. Basically, I want to return each user in order, and for each user, return each movie in order, and then return the rating for that user, movie pair, or null if that user did not rate that particular movie. example:</p>
<pre><code>USERID | MOVIEID | RATING
-------------------------
99835 8847874 4
99835 8994385 3
99835 9001934 null
99835 3235524 2
.
.
.
109834 8847874 null
109834 8994385 1
109834 9001934 null
etc
</code></pre>
<p>This way, I can simply read these results into a two dimensional array, suitable for my SVD algorithm. (Any other suggestions for getting a database of info into a simple two dimensional array of floats would be appreciated)</p>
<p>It is important that this be returned in order so that when I get my two dimensional array back, I will be able to re-map the values to the respective users and movies to do my analysis.</p>
|
<pre><code>SELECT m.UserID, m.MovieID, r.Rating
FROM (SELECT a.userid, b.movieid
FROM (SELECT DISTINCT UserID FROM Ratings) AS a,
(SELECT DISTINCT MovieID FROM Ratings) AS b
) AS m LEFT OUTER JOIN Ratings AS r
ON (m.MovieID = r.MovieID AND m.UserID = r.UserID)
ORDER BY m.UserID, m.MovieID;
</code></pre>
<p><em>Now tested and it seems to work!</em></p>
<p>The concept is to create the cartesian product of the list of UserID values in the Ratings table with the list of MovieID values in the Ratings table (ouch!), and then do an outer join of that complete matrix with the Ratings table (again) to collect the ratings values.</p>
<p>This is <strong>NOT</strong> efficient.</p>
<p>It might be effective.</p>
<p>You might do better though to just run the plain simple select of the data, and arrange to populate the arrays as the data arrives. If you have many thousands of users and movies, you are going to be returning many millions of rows, but most of them are going to have nulls. You should treat the incoming data as a description of a sparse matrix, and first set the matrix in the program to all zeroes (or other default value), and then read the stream from the database and set just the rows that were actually present.</p>
<p>That query is the basically trivial:</p>
<pre><code>SELECT UserID, MovieID, Rating
FROM Ratings
ORDER BY UserID, MovieID;
</code></pre>
|
<p>If I understand your question correctly, you have all the data in your table, and you just want to extract it in the right order. Is that correct? If so, it should just be a mattter of:</p>
<pre><code>select userid, movieid, rating
from ratings
order by userid, movieid
</code></pre>
| 41,335
|
<p>In a <a href="https://stackoverflow.com/questions/194272">related question</a>, my team is about to (hopefully) start using LINQ, and I'd like to take advantage of anonymous types. What is the best way to mix VB.NET's Option Strict (which we've been using through the life of the project) and the new Option Infer directives?</p>
|
<p>Option Strict and <a href="http://msdn.microsoft.com/en-us/library/bb384665.aspx" rel="noreferrer">Option Infer</a> do not conflict, so I see no harm in having both on.</p>
<p>As a style guide, I prefer to put Option Strict, Explicit, and Infer at the top of each class file - this prevents differences in project or IDE settings from causing issues, and makes it clear what settings are used. </p>
|
<p>Option Strict can be used without Option Infer, but Option Infer should not be used without Option Strict as that can lead to a difference in the resulting IL.</p>
<p>Consider this line of code:</p>
<pre><code>txtBox.Text = If(str="", Nothing, CDate(str))
</code></pre>
<p>With Option Strict Off and Option Infer Off, that is the equvalent of:</p>
<pre><code>txtBox.Text = CStr(If(str="", Nothing, CType(CDate(str), Object)))
</code></pre>
<p>If str="" then txtBox.Text is set to Nothing/empty string.</p>
<p>With Option Infer On but Option Strict Off that becomes:</p>
<pre><code>txtBox.Text = Cstr(If(str="", CDate(Nothing), CType(CDate(str), Object)))
</code></pre>
<p>And CDate(Nothing) = Date.MinValue and so txtBox.Text = "01/01/0001"</p>
<p>Option Strict can only make your code not compile, Option Infer can change its meaning. That is not to say that Infer can’t be a good thing, in general it is, but there are a few caveats that you need to be aware of.</p>
<p>The original code could be written as:</p>
<pre><code> txtBox.Text = Cstr(If(str="", Nothing, CDate(str)))
</code></pre>
<p>In which case Option Strict won’t save you if you turn Option. Infer On, but in a code base without Strict the original version is more likely. </p>
| 23,603
|
<p>I have a small VB.NET application that I'm working on using the full version of Visual Studio 2005. In the <strong>Publish</strong> properties of the project, I have it set to <em>Automatically increment revision with each publish</em>.</p>
<p>The issue is that it's only incrementing the revision in the Setup files. It doesn't seem to be updating the version number in the About Box (which is the generic, built-in, About Box template). That version number seems to be coming from <em>My.Application.Info.Version</em>.</p>
<p>What should I be using instead so that my automatically incrementing revision number shows up in the about box?</p>
|
<p>Change the code for the About box to </p>
<pre><code>Me.LabelVersion.Text = String.Format("Version {0}", My.Application.Deployment.CurrentVersion.ToString)
</code></pre>
<p>Please note that all the other answers are correct for "how do I get my assembly version", not the stated question "how do I show my publish version".</p>
|
<p>I'm no VB.NET expert, but have you tried to set the value to for example 1.0.0.*?
This should increase the revision number (at least it does in the AssemblyInfo.cs in C#).</p>
| 3,242
|
<p>I am building my CoreXY 3D printer with 350x350 mm heated bed at about 4 mm thickness. I just found out that borosilicate glass is unavailable at the local glazier. He offered tempered or ceramic glass instead. Which one should I go for? I read that both are a more expensive option to borosilicate glass, but I worry about the temperature stability, warping of the glass (in case of the tempered one), and parts (not) sticking to it. Any experience is appreciated.</p>
<p>PS. The ceramic glass of this size would cost me about 45 USD. The glazier did not tell me the price of the tempered option, but I reckon it will be around 30 USD, which is much more acceptable if it does the same job.</p>
|
<p>The primary advantage of borosilicate isn't that it's resistant to thermal shock -- as someone already noted, there's not much in the way of rapid heating or cooling in FDM printing (yes, the filament is hot, but its mass is low enough the glass it touches won't pick up much heat). Rather, it's the low expansion. Common soda-lime glass (window glass, mirror glass) expands several times as much as borosilicate, which means it will also shrink several times as much when it cools back down.</p>
<p>If you're holding constant temp throughout the print, and give adequate preheat time, that won't matter, but if (for instance) you heat the bed 10 °C hotter for the first layer, then cool it, plain glass will shrink enough to potentially cause the print to come loose, while borosilicate won't.</p>
<p>Ceramic glass is like borosilicate only more so (akin to Corningware) -- but again, not worth paying for unless you expect to change your bed temperature during the print.</p>
<p>For any kind of glass, my own preference is to use glue stick. I apply a "squiggle" (a precise metric volume), use 91% isopropyl to spread it evenly over the build area, and my prints stay stuck, but pop right off when the glass cools a little.</p>
|
<p>People choose borosilicate because of its thermal properties.</p>
<p>Between ceramic and tempered, I would suggest tempered glass, it's not good as borosilicate when comes to adapting to rapid temperatures but better than ceramic. The other option I would suggest will be "Aluminium", which is much better.</p>
| 2,015
|
<p>I have a working copy of my project, checked out using Subversion 1.5.1. When I attempt to run <a href="http://www.statsvn.org/" rel="nofollow noreferrer">StatSVN</a> against it, I get the following error:</p>
<blockquote>
<p>Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger info
INFO: StatSVN - SVN statistics generation</p>
<p>Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger info
INFO: svn: '.' is not a working copy
Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger error
SEVERE: Repository root not available - verify that the project was checked out with svn version 1.3.0 or above.</p>
</blockquote>
<p>Has anyone experienced this? I've seen suggestions it might be related to using a locale other than <code>en_US</code>, but I <em>am</em> using <code>en_US</code>.</p>
|
<p>Just guessing here, but are you sure that statSVN is compatible with working copies created with version 1.5 of the client? The format changed with svn 1.5...</p>
|
<p>@agnul</p>
<p>You were right. Here's the <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=2016015&group_id=164845&atid=833327" rel="nofollow noreferrer">relevant feature request</a> from their bugzilla.</p>
| 11,985
|
<p>I have an single threaded, embedded application that allocates and deallocates lots and lots of small blocks (32-64b). The perfect scenario for a cache based allocator. And although I could TRY to write one it'll likely be a waste of time, and not as well tested and tuned as some solution that's already been on the front lines.</p>
<p>So what would be the best allocator I could use for this scenario?</p>
<p>Note: I'm using a Lua Virtual Machine in the system (which is the culprit of 80+% of the allocations), so I can't trivially refactor my code to use stack allocations to increase allocation performance.</p>
|
<p>I did some research on this very topic recently, as we had an issue with memory fragmentation. In the end we decided to stay with GNU libc's implementation, and add some application-level memory pools where necessary. There were other allocators which had better fragmentation behavior, but we weren't comfortable enough with them replace malloc globally. GNU's has the benefit of a long history behind it.</p>
<p>In your case it seems justified; assuming you can't fix the VM, those tiny allocations are very wasteful. I don't know what your whole environment is, but you might consider wrapping the calls to malloc/realloc/free on just the VM so that you can pass it off to a handler designed for small pools.</p>
|
<p>I am writing a C memory allocator called tinymem that is intended to be able to defragment the heap, and re-use memory. Check it out:</p>
<p><a href="https://github.com/vitiral/tinymem" rel="nofollow">https://github.com/vitiral/tinymem</a></p>
<p>Note: this project has been discontinued to work on the rust implementation:</p>
<p><a href="https://github.com/vitiral/defrag-rs" rel="nofollow">https://github.com/vitiral/defrag-rs</a></p>
<p>Also, I had not heard of umm_malloc before. Unfortunately, it doesn't seem to be able to deal with fragmentation, but it definitely looks useful. I will have to check it out.</p>
| 21,345
|
<p>What is your preferred way of keeping controls centered on its parent when the parent change width or height? </p>
|
<p>If by 'centered' you mean "it was already in the middle and you want to keep it there without resizing it", then remove all anchors. If it should be resized, gabr's solution is the one to with :)</p>
|
<p>If you mean a sort of "updating, please wait..." type thing, I manually move it in the Form's OnResize event. This allows me to keep a panel out of the way during design, and hidden normally, but I can make it visible when needed.</p>
<pre><code>procedure TMyForm.FormResize(Sender: TObject);
var
nNewTop : Integer;
begin
inherited;
pnlRegenerating.Left := (ClientWidth - pnlRegenerating.Width) div 2;
nNewTop := (ClientHeight div 5) {* 4};
if (nNewTop + pnlRegenerating.Height) > ClientHeight then
nNewTop := ClientHeight - pnlRegenerating.Height - 4;
pnlRegenerating.Top := nNewTop;
end;
</code></pre>
| 40,452
|
<p>My current place of employment is currently in a transition, new ownership has taken over, things are finally getting standardized and proper guidelines are being enforced. </p>
<p>But we are still using VSS, there really isn't any reason for using it other then that's what whats initially setup. We don't use Visual Studio, or any tool really that specifically requires it. </p>
<p>What would be the absolute best argument I can bring up to help convince them that going to something like Subversion would be a much better solution, in the long run.</p>
|
<p>VSS totally relies on the clients to manage the database. If a client drops connection in the middle of a write over the network at just the wrong time, your file is trashed on the server. Not just the tip, but all the history. Hope you have a good backup. I've been through it. It's bad news.</p>
<p>VSS usage over VPN or other remote connections is abysmal. It's using SMB to transfer the data, and you have to retrieve the file and all of its deltas just to get the tip. Nasty.</p>
<p>I've seen VSS start to act up at 1GB of data. Database errors, etc. MS (somewhere in a FAQ or KB) says that 2GB is really the max safe limit. There are no good management tools (the clients run the asylum), so you don't really get any warning about this.</p>
<p><em>Anything</em> with a server process to provide some level of transactions and integrity control is a superior solution.</p>
|
<p>Even if it ain't broke, there's a potential benefit to migrating from VSS. First and most trivially, you won't have to buy new VSS licenses. Second, there are many examples of deficiencies in the VSS product (some also acknowledged by MS). The learning curve for SVN is at least as low as for VSS, and if you have devs happier with their source control system, they're more likely to use it early and often. That will translate to lots less risk for your company, and that's a good benefit.</p>
| 6,636
|
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<link href="Stylesheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table style="height: 100%; width: 100%;">
<tr>
<td colspan="2" style="height: 100px;">Header</td>
</tr>
<tr>
<td style="width: 180px;">Links</td>
<td>Content</td>
</tr>
<tr>
<td colspan="2" style="height: 25px;">Footer</td>
</tr>
</table>
</body>
</html>
</code></pre>
<p>Stylesheet.css looks as follows:</p>
<pre><code>*
{
margin: 0;
padding: 0;
}
html, body
{
height: 100%;
width: 100%;
}
</code></pre>
<p>Row 1 and 3 above have fixed heights. Row 3 is not filling the remaining space. If i omit the doctype, it works as expected. I need to use this doctype.</p>
|
<p>Please clarify the browser you are trying to fix this in.</p>
<p>You should be using <code><div></code>'s anyway if you want to do things properly ;)</p>
|
<p>I'm no web dev, but isn't height just applicable to block objects? Hence try setting the TR's height, and not the TD's.</p>
| 46,788
|
<p>I am extending the bed of my TronXY X3 FDM RepRap printer.</p>
<p>I am extending the bed from 220 mm x 220 mm to 220 mm x 300 mm. For now, I will keep the existing bed and add and aluminum sheet on top. That leaves 40mm on front and back of the original bed.</p>
<p>Right now I only plan on running PLA; but, I do plan on heating the bed.</p>
<p>How thick does the aluminum sheet need to be?</p>
|
<p>Main factors that control the process of the print bed selection are</p>
<ul>
<li>weight: too thick plate increases inertial force, limiting maximum acceleration/jerk (decreased print speed)</li>
<li>stiffness: too thin plate will warp when heated or bend during calibration (decreased print quality/printer reliability)</li>
</ul>
<p>For table sizes around 400x400mm I would think of 4mm plate, but it still can warp if heated unevenly.</p>
<p>Sometimes it makes sense to use a sandwich-type table: lower level is MDF, cork panel for heat insulation and thin (1.5-2mm) aluminum heated bed on top.</p>
|
<p>I highly recommend aluminium tooling plates. They have a +/- 0.1 mm flatness tolerance on 1 meter. It's alloy 5083 offers a great stability. You can purchase such for example at aluminyumburada, which offers <a href="https://www.aluminyumburada.com/aluminum-cut-to-size" rel="nofollow noreferrer">custom cut piecees.</a>. They have a minimum thickness of 5 mm, though the prices get lower the thicker the piece is.</p>
| 662
|
<p>Is it possible for an Subversion client to break a repository in any way? This could be any sort of destructive disruption, but it must be such that it cannot be recovered from without restoring the repository from a backup.</p>
<p>Obviously, deleting everything and then checking that it is easy to fix simply with a rollback, so I am looking for something more than that.</p>
|
<p>A Subversion client can either talk to a server to access the repository, or it can use a <code>file://</code> URL to access the repository directly. In the first case, the server is responsible for the repository so the client cannot directly "break" it. In the second case, the client is responsible for the repository so bugs in the client can affect the repository.</p>
|
<p>If a client can break the repository in any way that requires a repository restore it's considered a very serious bug by the Subversion folks.</p>
<p>A quick look on their bug-tracker shows that they do occasionally have repository corruption bugs, but in the absence of a bug, it's not possible for a client to completely break the repository.</p>
| 47,741
|
<p>I have a script that slides a div down from behind the menu, when people click on the tab. However its in jquery and I want to use mootools (lots of reasons I wont go into here). However im stuck with mootools 1.1 at present. But for some reason my attempt is not working :(</p>
<p>The html</p>
<pre><code>print("code sample");
<div id="panel">
<form action="">
< form here >
</form>
</div>
<div class="slide">
<p class="sl"><a href="#" class="btn-slide" id="toggle"><span></span></a></p>
</code></pre>
<p>Div id panel holds the form which slides down, div class slide and the P tag is replaced by a tab/button which hangs down via css, clicking on this slides the tab down.</p>
<p>The jquery (which works fine)</p>
<pre><code>print("code sample");
<script type="text/javascript">
$j(document).ready(function(){
$j(".btn-slide").click(function(){
$j("#panel").slideToggle("slow");
$j(this).toggleClass("active"); return false;
});
});
</script>
</code></pre>
<p>My moo attempt</p>
<pre><code>print("code sample");
<script type="text/javascript">
window.addEvent('domready', function(){
var mySlide = new Fx.Slide('panel');
$('toggle').addEvent('click', function(e){
e = new Event(e);
mySlide.toggle();
e.stop();
});
});
</script>
</code></pre>
<p>Like I said above I am restricted to moo 1.1 at present, but if there is a answer that will work with both 1.1 and 1.2 or if its a similar change I would be grateful to hear, as it will be updated at some point.</p>
|
<p>I recommend using UrlRewriter:</p>
<p><a href="http://urlrewriter.net/" rel="nofollow noreferrer">http://urlrewriter.net/</a></p>
<p>This allows you to create all the mappings above that you desire. One thing that you'll have to do (if you're using IIS 6 or earlier) is configure IIS so that all extensions are handled by asp.net. The documentation explains how to do this. Then you create a bunch of rules in your web.config (or separate rewriter.config as I use) in the form of regular expressions to create your mappings.</p>
<p>Incidentally, for the above example, you probably don't need to do anything for the last two rules. IIS will take care of those automatically. For the first rule it will be something like:</p>
<pre><code><rewrite url="^/file$" to="/file.aspx" />
</code></pre>
<p>You could get more clever and write generalized rules so you don't have to write one rule per file.</p>
|
<p>You'll have to add an ASP.NET global.asax or HttpModule that maps the / request to default.aspx.</p>
| 29,176
|
<p>I've got TotroiseSVN installed and have a majority of my repositories checking in and out from C:\subversion\ <em>and a couple checking in and out from a network share (I forgot about this when I originally posted this question)</em>.</p>
<p>This means that I don't have a "subversion" server per-se.</p>
<p>How do I integrate TortoiseSVN and Fogbugz?</p>
<p><em>Edit: inserted italics</em></p>
|
<p>I've been investigating this issue and have managed to get it working. There are a couple of minor problems but they can be worked-around.</p>
<p>There are 3 distinct parts to this problem, as follows:</p>
<ol>
<li><p><strong>The TortoiseSVN part</strong> - getting TortoiseSVN to insert the Bugid and hyperlink in the svn log</p></li>
<li><p><strong>The FogBugz part</strong> - getting FogBugz to insert the SVN info and corresponding links</p></li>
<li><p><strong>The WebSVN part</strong> - ensuring the links from FogBugz actually work</p></li>
</ol>
<p>Instructions for part 1 are in another answer, although it actually does more than required. The stuff about the hooks is actually for part 2, and as is pointed out - it doesn't work "out of the box"</p>
<p><strong>Just to confirm, we are looking at using TortoiseSVN <em>WITHOUT</em> an SVN server (ie. file-based repositories)</strong></p>
<p>I'm accessing the repositories using UNC paths, but it also works for local drives or mapped drives.</p>
<p>All of this works with TortoiseSVN v1.5.3 and SVN Server v1.5.2 (You need to install SVN Server because part 2 needs <code>svnlook.exe</code> which is in the server package. You don't actually configure it to work as an SVN Server) It may even be possible to just copy <code>svnlook.exe</code> from another computer and put it somewhere in your path.</p>
<h1>Part 1 - TortoiseSVN</h1>
<p>Creating the TortoiseSVN properties is all that is required in order to get the links in the SVN log.</p>
<p>Previous instructions work fine, I'll quote them here for convenience:</p>
<blockquote>
<h2>Configure the Properties</h2>
<ol>
<li><p>Right click on the root directory of the checked out project you want to work with.</p></li>
<li><p>Select "TortoiseSVN -> Properties"</p></li>
<li><p>Add five property value pairs by clicking "New..." and inserting the following in "Property Name" and "Property Value" respectively: (make sure you tick "Apply property recursively" for each one)</p>
<pre><code>bugtraq:label BugzID:
bugtraq:message BugzID: %BUGID%
bugtraq:number true
bugtraq:url http://[your fogbugz URL here]/default.asp?%BUGID%
bugtraq:warnifnoissue false
</code></pre></li>
<li><p>Click "OK"</p></li>
</ol>
</blockquote>
<p>As Jeff says, you'll need to do that for each working copy, so follow his instructions for migrating the properties.</p>
<p>That's it. TortoiseSVN will now add a link to the corresponding FogBugz bugID when you commit. If that's all you want, you can stop here.</p>
<h1>Part 2 - FogBugz</h1>
<p>For this to work we need to set up the hook scripts. Basically the batch file is called after each commit, and this in turn calls the VBS script which does the submission to FogBugz. The VBS script actually works fine in this situation so we don't need to modify it.</p>
<p>The problem is that the batch file is written to work as a <em>server</em> hook, but we need a <em>client</em> hook.</p>
<p>SVN server calls the post-commit hook with these parameters:</p>
<pre><code><repository-path> <revision>
</code></pre>
<p>TortoiseSVN calls the post-commit hook with these parameters:</p>
<pre><code><affected-files> <depth> <messagefile> <revision> <error> <working-copy-path>
</code></pre>
<p>So that's why it doesn't work - the parameters are wrong. We need to amend the batch file so it passes the correct parameters to the VBS script.</p>
<p>You'll notice that TSVN doesn't pass the repository path, which is a problem, but it does work in the following circumstances:</p>
<ul>
<li>The repository name and working copy name are the same</li>
<li>You do the commit at the root of the working copy, not a subfolder.</li>
</ul>
<p>I'm going to see if I can fix this problem and will post back here if I do.</p>
<p>Here's my amended batch file which does work (please excuse the excessive comments...)</p>
<p>You'll need to set the hook and repository directories to match your setup.</p>
<pre><code>rem @echo off
rem SubVersion -> FogBugz post-commit hook file
rem Put this into the Hooks directory in your subversion repository
rem along with the logBugDataSVN.vbs file
rem TSVN calls this with args <PATH> <DEPTH> <MESSAGEFILE> <REVISION> <ERROR> <CWD>
rem The ones we're interested in are <REVISION> and <CWD> which are %4 and %6
rem YOU NEED TO EDIT THE LINE WHICH SETS RepoRoot TO POINT AT THE DIRECTORY
rem THAT CONTAINS YOUR REPOSITORIES AND ALSO YOU MUST SET THE HOOKS DIRECTORY
setlocal
rem debugging
rem echo %1 %2 %3 %4 %5 %6 > c:\temp\test.txt
rem Set Hooks directory location (no trailing slash)
set HooksDir=\\myserver\svn\hooks
rem Set Repo Root location (ie. the directory containing all the repos)
rem (no trailing slash)
set RepoRoot=\\myserver\svn
rem Build full repo location
set Repo=%RepoRoot%\%~n6
rem debugging
rem echo %Repo% >> c:\temp\test.txt
rem Grab the last two digits of the revision number
rem and append them to the log of svn changes
rem to avoid simultaneous commit scenarios causing overwrites
set ChangeFileSuffix=%~4
set LogSvnChangeFile=svn%ChangeFileSuffix:~-2,2%.txt
set LogBugDataScript=logBugDataSVN.vbs
set ScriptCommand=cscript
rem Could remove the need for svnlook on the client since TSVN
rem provides as parameters the info we need to call the script.
rem However, it's in a slightly different format than the script is expecting
rem for parsing, therefore we would have to amend the script too, so I won't bother.
rem @echo on
svnlook changed -r %4 %Repo% > %temp%\%LogSvnChangeFile%
svnlook log -r %4 %Repo% | %ScriptCommand% %HooksDir%\%LogBugDataScript% %4 %temp%\%LogSvnChangeFile% %~n6
del %temp%\%LogSvnChangeFile%
endlocal
</code></pre>
<p>I'm going to assume the repositories are at <code>\\myserver\svn\</code> and working copies are all under `C:\Projects\</p>
<ol>
<li><p>Go into your FogBugz account and click Extras -> Configure Source Control Integration</p></li>
<li><p>Download the VBScript file for Subversion (don't bother with the batch file)</p></li>
<li><p>Create a folder to store the hook scripts. I put it in the same folder as my repositories. eg. <code>\\myserver\svn\hooks\</code></p></li>
<li><p>Rename VBscript to remove the <code>.safe</code> at the end of the filename.</p></li>
<li><p>Save my version of the batch file in your hooks directory, as <code>post-commit-tsvn.bat</code></p></li>
<li><p>Right click on any directory.</p></li>
<li><p>Select "TortoiseSVN > Settings" (in the right click menu from the last step)</p></li>
<li><p>Select "Hook Scripts"</p></li>
<li><p>Click "Add" and set the properties as follows:</p>
<ul>
<li><p>Hook Type: Post-Commit Hook</p></li>
<li><p>Working Copy Path: <code>C:\Projects</code> (or whatever your root directory for all of your projects is.)</p></li>
<li><p>Command Line To Execute: <code>\\myserver\svn\hooks\post-commit-tsvn.bat</code> (this needs to point to wherever you put your hooks directory in step 3)</p></li>
<li><p>Tick "Wait for the script to finish"</p></li>
</ul></li>
<li><p>Click OK twice.</p></li>
</ol>
<p>Next time you commit and enter a Bugid, it will be submitted to FogBugz. The links won't work but at least the revision info is there and you can manually look up the log in TortoiseSVN.</p>
<p>NOTE: You'll notice that the repository root is hard-coded into the batch file. As a result, if you check out from repositories that don't have the same root (eg. one on local drive and one on network) then you'll need to use 2 batch files and 2 corresponding entries under Hook Scripts in the TSVN settings. The way to do this would be to have 2 separate Working Copy trees - one for each repository root.</p>
<h1>Part 3 - WebSVN</h1>
<p>Errr, I haven't done this :-)</p>
<p>From reading the WebSVN docs, it seems that WebSVN doesn't actually integrate with the SVN server, it just behaves like any other SVN client but presents a web interface. In theory then it should work fine with a file-based repository. I haven't tried it though.</p>
|
<p>I am not sure I follow you. Do you have the repositories on the network or on your C:\ drive? According to two of your posts, you have both, or neither, or one of them or...</p>
<p>You can not get VisualSVN or Apache to safely serve repositories from a network share. Since you originally said you had the repositories on your C:\ drive, that's what you get advice for. If you have a different setup, you need to tell us about that.</p>
<p>If you have the repositories on your local harddisk, I would install VisualSVN, or integrate it into Apache. VisualSVN can run fine alongside Apache so if you go that route you only have to install it. Your existing repositories can also just be copied into the repository root directory of VisualSVN and you're up and running.</p>
<p>I am unsure why that big post here is labelled as incomplete, as it details the steps necessary to set up a hook script to inform FogBugz about the new revisions linked to the cases, which should be what the <em>incomplete</em> message says it doesn't do. Is that not working?</p>
| 2,568
|
<p>If have a set of classes that all implement an interface. </p>
<pre><code>interface IMyinterface<T>
{
int foo(T Bar);
}
</code></pre>
<p>I want to shove them all in a list and enumerate through them. </p>
<pre><code> List<IMyinterface> list
foreach(IMyinterface in list)
// etc...
</code></pre>
<p>but the compiler wants to know what T is. Can I do this? How can I overcome this issue?</p>
|
<p>There is no IMyinterface type there is only a IMyinterface`1 type which will require a type argument. You could create an IMyinterface type:-</p>
<pre><code>interface IMyinterface { ... }
</code></pre>
<p>then inherit from it</p>
<pre><code>interface IMyinterface<T> : IMyinterface { ... }
</code></pre>
<p>You would need to move any members you would like to use in the foreach loop to the IMyinterface definition.</p>
|
<p>If you plan to invoke a method with T in the signature, the answer is that you cannot. Otherwise you can do as anthonywjones suggests</p>
| 40,118
|
<p>What is the simplest way to programmatically export Excel data to Matlab?</p>
|
<p>If you are running Matlab on Windows with Excel installed, try <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/xlsread.html" rel="nofollow noreferrer">XLSREAD</a>.</p>
|
<p>For a bit of $$$, you can get the MATLAB add-on Excel Link, which provides a nice clean interface for transferring data back and forth between the two programs.</p>
| 24,195
|
<p>In VB6, I used a call to the Windows API, <strong>GetAsyncKeyState</strong>, to determine if the user has hit the ESC key to allow them to exit out of a long running loop.</p>
<pre><code>Declare Function GetAsyncKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
</code></pre>
<p>Is there an equivalent in pure .NET that does require a direct call to the API?</p>
|
<p>You can find the P/Invoke declaration for GetAsyncKeyState from <a href="http://pinvoke.net/default.aspx/user32/GetAsyncKeyState.html" rel="nofollow noreferrer">http://pinvoke.net/default.aspx/user32/GetAsyncKeyState.html</a></p>
<p>Here's the C# signature for example:</p>
<pre><code>[DllImport("user32.dll")]
static extern short GetAsyncKeyState(int vKey);
</code></pre>
|
<p>Depending on your desired use there are a couple of options, including invoking the same method as described above).
From a console app:</p>
<pre><code>bool exitLoop = false;
for(int i=0;i<bigNumber && !exitLoop;i++)
{
// Do Stuff.
if(Console.KeyAvailable)
{
// Read the key and display it (false to hide it)
ConsoleKeyInfo key = Console.ReadKey(true);
if(ConsoleKey.Escape == key.Key)
{
exitLoop=false;
}
}
}
</code></pre>
<p>If you are working on a windows form, every form has a number of key related events you can listen to and handle as necessary (Simplified most of the logic):</p>
<pre><code>public partial class Form1 : Form
{
private bool exitLoop;
public Form1()
{
InitializeComponent();
this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyUp);
}
public void doSomething()
{
// reset our exit flag:
this.exitLoop = false;
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(delegate(object notUsed)
{
while (!exitLoop)
{
// Do something
}
}));
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (Keys.Escape == e.KeyCode)
{
e.Handled = true;
this.exitLoop = true;
}
}
}
</code></pre>
<p>Note that this is <em>very</em> simplified - it doesn't handle any of the usual threading issues or anything like that. As was pointed out in the comments, the original go-round didn't address that problem, I added a quick little ThreadPool call to thread the background work. Also note, that the problem with listening for the key events is that other controls may actually handle them, so you need to make sure that you register for the event on the correct control(s). If a windows form application is the direction you are heading, you can also attempt to inject yourself into the message loop itself... </p>
<pre><code>public override bool PreProcessMessage(ref Message msg)
{
// Handle the message or pass it to the default handler...
base.PreProcessMessage(msg);
}
</code></pre>
| 16,214
|
<p>I am curious to know where the "Don't Fragment" [DF] Bit of the IP Flags is used. As fragmentation is invisible to higher layers and they don't care too.</p>
<p>I am also looking for an example. </p>
<p>Thanks a lot in advance.</p>
|
<p>Fragmentation is not always invisible to all upper layers. Some early (and probably even current) micro-controller TCP/IP stacks did not implement the full capabilities such as fragmentation handling. Use of the flag in that situation would ensure that the packet arrived in its original form instead of a lot of fragments which the other end couldn't handle.</p>
<p>In addition, when using UDP, it's not necessary for all the fragments to arrive at the destination so, preventing fragmentation means the message either arrives or doesn't arrive - there is no possibility that only a bit of the UDP datagram will reach the destination. I can't recall how long the TCP/IP stack held on to unassembled IP packets waiting for missing fragments, but use of the DF flag meant there were no unnecessary resources tied up during that time.</p>
<p>Finally, you can use it for testing behavior of network infrastructure, such as what happens when you get a packet that's bigger than the maximum transmission unit (DF will prevent that packet from being fragmented to 'squeeze through' the hole).</p>
|
<p>Do note that there is no standard way to set DF in C. On Linux, this code works:</p>
<pre><code>result = setsockopt(mysocket, IPPROTO_IP,
IP_MTU_DISCOVER, IP_PMTUDISC_DO, sizeof(int));
</code></pre>
<p>but it does not on FreeBSD 6</p>
<p>Also, Path MTU discovery is extremely unreliable on the real Internet. Too many broken firewalls and middleboxes filter out ICMP "Packet too big" messages (here is a good way to test a candidate network administrator during an interview: ask him/her to stop ping and he/she will probably block completely ICMP.) See RFC 2923: "TCP Problems with Path MTU Discovery"</p>
<p>That's the reason why the IETF now suggest a new way to test the MTU, without relying on Path MTU Discovery: RFC 4821: "Packetization Layer Path MTU Discovery"</p>
| 45,812
|
<p>Which is more efficient?</p>
<pre><code>SELECT theField
FROM theTable
GROUP BY theField
</code></pre>
<p>or</p>
<pre><code>SELECT DISTINCT theField
FROM theTable
</code></pre>
|
<p>In your example, both queries will generate the same execution plan so their performance will be the same. </p>
<p>However, they both have their own purpose. To make your code easier to understand, you should use distinct to <strong>eliminate duplicate rows</strong> and group by to <strong>apply aggregate operators</strong> (sum, count, max, ...).</p>
|
<p>In MySQL, DISTINCT seems a bit faster than GROUP BY if theField is not indexed. DISTINCT only <strong>eliminate duplicate rows</strong> but GROUP BY seems to <strong>sort</strong> them in addition.</p>
| 49,058
|
<p>How do I import a Python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
|
<p>Assuming that both your directories are real Python packages (do have the <code>__init__.py</code> file inside them), here is a safe solution for inclusion of modules relatively to the location of the script.</p>
<p>I assume that you want to do this, because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter.</p>
<pre><code> import os, sys, inspect
# realpath() will make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# Use this if you want to include modules from a subfolder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
# Info:
# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
# __file__ fails if the script is called in different ways on Windows.
# __file__ fails if someone does os.chdir() before.
# sys.argv[0] also fails, because it doesn't not always contains the path.
</code></pre>
<p>As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system.</p>
<p>Warning! I don't really know what is happening when current module is inside an <code>egg</code> file. It probably fails too.</p>
|
<p>Call me overly cautious, but I like to make mine more portable because it's unsafe to assume that files will always be in the same place on every computer. Personally I have the code look up the file path first. I use Linux so mine would look like this:</p>
<pre><code>import os, sys
from subprocess import Popen, PIPE
try:
path = Popen("find / -name 'file' -type f", shell=True, stdout=PIPE).stdout.read().splitlines()[0]
if not sys.path.__contains__(path):
sys.path.append(path)
except IndexError:
raise RuntimeError("You must have FILE to run this program!")
</code></pre>
<p>That is of course unless you plan to package these together. But if that's the case you don't really need two separate files anyway.</p>
| 35,274
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.