input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
How do display functions like sprintf convert numbers to strings? <p>I'm trying to extract the integer and decimal parts of a floating point value, and I seem to be running into some strange rounding problems, due probably to the imprecise way floats are stored. </p>
<p>I have some code like this to extract the fractional part:</p>
<pre><code>double number = 2.01;
int frac = int(floor(number * 100)) % 100;
</code></pre>
<p>However the result here instead of 1 comes out as 0. This seems to be because the original double actually gets stored as:</p>
<pre><code>2.0099999...
</code></pre>
<p>However running sprintf seems to get such a conversion correct:</p>
<pre><code>char num_string[99];
sprintf(num_string,"%f",number);
</code></pre>
<p>How is sprintf getting the correct answer while the above method does not?</p>
| <p><s>> However the result here instead of 1 comes out as one.</p>
<p>What do you mean?</p>
<blockquote>
<p>2.099999...</p>
</blockquote>
<p>Or, more like <code>2.00999...</code></s></p>
<p>As you've noted:</p>
<pre><code>int frac = int(floor(number * 100)) % 100;
</code></pre>
<p>will be:</p>
<pre><code>int frac = int(floor(2.00999... * 100)) % 100;
= int(floor(200.999...)) % 100;
= int(floor(200.999...)) % 100;
= int(200) % 100;
= 200 % 100;
= 0;
</code></pre>
<p>You may be interested in <a href="http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/msun/src/s_floor.c?rev=1.8&content-type=text/x-cvsweb-markup" rel="nofollow">this</a>.</p>
<p>Also, see <code>modf</code> from <code>math.h</code>:</p>
<pre><code>double modf(double x, double *intptr) /* Breaks x into fractional and integer parts. */
</code></pre>
<p>modf() is a better alternative than doing the juggling yourself.</p>
|
How do I handle a varying number of items from a database query? <p>Effectively a duplicate of: <a href="http://stackoverflow.com/questions/576498/how-can-i-display-data-in-table-with-perl">How can I display data in table with Perl</a></p>
<p>The accepted answer there applies here. So do some of the alternatives.</p>
<p><hr></p>
<p>I am trying to run raw database queries from Perl program and display results to the user. Something like <code>select * from table</code>. I want to display the information in a HTML table. The columns in the HTML table correspond with the returned columns. </p>
<p>I am having some issues. I can run <code>describe table</code> query to return the number of columns there are in the table. However, how will I store the information from the returned results into arrays? </p>
<p>So if I am storing results like this:</p>
<pre><code>while (($f1, $t2, $n3, $k4, $d5, $e6) = $sth1->fetchrow_array)
</code></pre>
<p>In this case I only know that there are, say four columns (which I got from describe table). But this number four is dynamic and can change depending on the table name. I can not declare my variables based on this number. Any suggestions?</p>
| <p>Try:</p>
<pre><code>print "<table>\n";
# display HTML header
@cols = @{$sth->{NAMES_uc}};
print "<tr>".join("", map { "<th>${_}</th>" } @cols)."</tr>\n";
# display one HTML table row for each DB row
while (my @row = $sth->fetchrow_array) {
print "<tr>".join("", map { "<td>${_}</td>" } @row)."</tr>\n";
}
print "</table>\n";
</code></pre>
|
Declaring inherited generics with complex type constraints <p>I have an interface with a single generic type parameter:</p>
<pre><code>public interface IDriveable<T> where T : ITransmission { ... }
</code></pre>
<p>I also have a class that has a type parameter that needs to be of that interface type:</p>
<pre><code>public class VehicleFactory<T> where T : /* ??? */
</code></pre>
<p>There is a problem here with this declaration. I can't put "IDriveable", because that has no type parameters and doesn't match the type signature of IDriveable. But I also don't want to put IDriveable<U> either, because then VehicleFactory has to know what <em>kind</em> of IDriveable it's getting. I want VehicleFactory to accept <em>any</em> kind of IDriveable.</p>
<p>The proposed solution a coworker had was to use:</p>
<pre><code>public class VehicleFactory<T, U> where T : IDriveable<U>
</code></pre>
<p>But I don't like this, since it's redundant. I have to say the "U" type twice:</p>
<pre><code>var factory = new VehicleFactory<IDriveable<AllWheelDrive>, AllWheelDrive>();
</code></pre>
<p>What should go in the question marks? </p>
| <p>What is VehicleFactory going to <em>do</em> with T? Does it actually need the constraint in order to work, or is it just for the sake of developer sanity checking?</p>
<p>One common way round this is to declare a non-generic interface (<code>IDriveable</code>) and then make your generic one extend that:</p>
<pre><code>public interface IDriveable {}
public interface IDriveable<T> : IDriveable {}
public class VehicleFactory<T> where T : IDriveable
</code></pre>
<p>If you <em>do</em> want the factory to be able to do things with <code>T</code>, you could put any interface members from <code>IDriveable<T></code> which don't care about <code>T</code> into the nongeneric <code>IDriveable</code>.</p>
|
Get timezone from DateTime <p>Does the .Net DateTime contain information about time zone where it was created? </p>
<p>I have a library parsing DateTime from a format that has "+zz" at the end, and while it parses correctly and adjusts a local time, I need to get what the specific time zone was from the DateTime object. </p>
<p>Is this possible at all? All I can see is DateTime.Kind, which specifies if time is local or UTC.</p>
| <p>DateTime itself contains no real timezone information. It <em>may</em> know if it's UTC or local, but not what local really means.</p>
<p>DateTimeOffset is somewhat better - that's basically a UTC time and an offset. However, that's still not really enough to determine the timezone, as many different timezones can have the same offset at any one point in time. This sounds like it may be good enough for you though, as all you've got to work with when parsing the date/time is the offset. </p>
<p>The support for time zones as of .NET 3.5 is a lot better than it was, but I'd really like to see a standard "ZonedDateTime" or something like that - a UTC time and an actual time zone. It's easy to build your own, but it would be nice to see it in the standard libraries.</p>
<p>EDIT: Nearly four years later, I'd now suggest using <a href="http://noda-time.googlecode.com">Noda Time</a> which has a rather richer set of date/time types. I'm biased though, as the main author of Noda Time :)</p>
|
A standard Unix command-line tool for piping to a socket <p>I have some applications, and standard Unix tools sending their output to named-pipes in Solaris, however named pipes can only be read from the local storage (on Solaris), so I can't access them from over the network or place the pipes on an NFS storage for networked access to their output.</p>
<p>Which got me wondering if there was an analogous way to forward the output of command-line tools directly to sockets, say something like:</p>
<pre><code>mksocket mysocket:12345
vmstat 1 > mysocket 2>&1
</code></pre>
| <p><a href="http://netcat.sourceforge.net/">Netcat</a> is great for this. Here's a <a href="http://www.g-loaded.eu/2006/11/06/netcat-a-couple-of-useful-examples/">page with some common examples</a>.</p>
<p>Usage for your case might look something like this:</p>
<ol>
<li><p>Server listens for a connection, then sends output to it:</p>
<p><code>server$ my_script | nc -l 7777</code></p></li>
<li><p>Remote client connects to <code>server</code> on port 7777, receives data, saves to a log file:</p>
<p><code>client$ nc server 7777 >> /var/log/archive</code></p></li>
</ol>
|
I'd like to scrape the iTunes top X RSS feed and insert into a dB <p>Preferably I'd like to do so with some bash shell scripting, maybe some PHP or PERL and a MySQL db. Thoughts?</p>
| <p>Here is a solution using Perl, with the help of (of course!) a bunch of modules.</p>
<p>It uses SQLite so you can run it easily (the definition of the (simplistic) DB is at the end of the script). Also it uses Perl hashes and simple SQL statements, instead of proper objects and an ORM layer. I found it easier to parse the XML directly instead of using an RSS module (I tried XML::Feed), because you need access to specific tags (name, preview...).</p>
<p>You can use it as a basis to add more features, more fields in the DB, a table for genre... but at least this way you have a basis that you can expand on (and maybe you can then publish the result as open-source).</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig; # to parse the RSS
use DBIx::Simple; # DB interaction made easy
use Getopt::Std; # always need options for a script
use PerlIO::gzip; # itunes sends a gzip-ed file
use LWP::Simple 'getstore'; # to get the RSS
my %opt;
getopts( 'vc:', \%opt);
# could also be an option, but I guess it won't change that much
my @URLs= (
'http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=10/xml',
);
# during debug, it's nice to use a cache of the feed instead of hitting hit every single run
if( $opt{c}) { @URLs= ($opt{c}); }
# I like using SQLite when developping,
# replace with MySQL connect parameters if needed (see DBD::MySQL for the exact syntax)
my @connect= ("dbi:SQLite:dbname=itunes.db","","", { RaiseError => 1, AutoCommit => 0 }) ;
my $NS_PREFIX='im';
# a global, could be passed around, but would make the code a bit more verbose
my $db = DBIx::Simple->connect(@connect) or die "cannot connect to DB: $DBI::errstr";
foreach my $url (@URLs)
{ add_feed( $url); }
$db->disconnect;
warn "done\n" if( $opt{v});
sub add_feed
{ my( $url)= @_;
# itunes sends gziped RSS, so we need to unzip it
my $tempfile= "$0.rss.gz"; # very crude, should use File::Temp instead
getstore($url, $tempfile);
open( my $in_feed, '<:gzip', $tempfile) or die " cannot open tempfile: $!";
XML::Twig->new( twig_handlers => { 'feed/title' => sub { warn "adding feed ", $_->text if $opt{v}; },
entry => \&entry,
},
map_xmlns => { 'http://phobos.apple.com/rss' => $NS_PREFIX },
)
->parse( $in_feed);
close $in_feed;
}
sub entry
{ my( $t, $entry)= @_;
# get the data
my %song= map { $_ => $entry->field( "$NS_PREFIX:$_") } qw( name artist price);
if( my $preview= $entry->first_child( 'link[@title="Preview"]') )
{ $song{preview}= $preview->att( 'href'); }
# $db->begin_work;
# store it
if( ($db->query( 'SELECT count(*) FROM song WHERE name=?', $song{name})->flat)[0])
{ warn " skipping $song{name}, already stored\n" if $opt{v};
}
else
{
warn " adding $song{name}\n" if $opt{v};
if( my $artist_id= ($db->query( 'SELECT id from ARTIST where name=?', $song{artist})->flat)[0])
{ warn " existing artist $song{name} ($artist_id)\n" if $opt{v};
$song{artist}= $artist_id;
}
else
{ warn " creating new artist $song{artist}\n" if $opt{v};
$db->query( 'INSERT INTO artist (name) VALUES (??)', $song{artist});
# should be $db->last_insert_id but that's not available in DBD::SQLite at the moment
$song{artist}= $db->func('last_insert_rowid');
}
$db->query( 'INSERT INTO song ( name, artist, price, preview) VALUES (??)',
@song{qw( name artist price preview)});
$db->commit;
}
$t->purge; # keeps memory usage lower, probably not needed for small RSS files
}
__END__
=head1 NAME
itunes2db - loads itunes RSS feeds to a DB
=head1 OPTIONS
-c <file> uses a cache instead of the list of URLs
-v verbose
=head1 DB schema
create table song ( id INT PRIMARY KEY, name TEXT, artist INT, price TEXT, preview TEXT);
create table artist (id INT PRIMARY KEY, name TEXT);
</code></pre>
|
Algorithms for Big O Analysis <p>What all algorithms do you people find having amazing (tough, strange) complexity analysis in terms of both - Resulting O notation and uniqueness in way they are analyzed?</p>
| <p>I have (quite) a few examples:</p>
<ul>
<li>The <a href="http://en.wikipedia.org/wiki/Disjoint-set_data_structure">union-find</a> data structure, which supports operations in (amortized) inverse Ackermann time. It's particularly nice because the data structure is incredibly easy to code.</li>
<li><a href="http://en.wikipedia.org/wiki/Splay_tree">Splay trees</a>, which are self-balancing binary trees (that is, no extra information is stored other than the BST -- no red/black information. <a href="http://en.wikipedia.org/wiki/Amortized_analysis">Amortized analysis</a> was essentially invented to prove bounds for splay trees; splay trees run in <em>amortized</em> logarithmic time, but worst-case linear time. The proofs are cool.</li>
<li><a href="http://en.wikipedia.org/wiki/Fibonacci_heap">Fibonacci heaps</a>, which perform most of the priority queue operations in amortized constant time, thus improving the runtime of <a href="http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Dijkstra's algorithm</a> and other problems. As with splay trees, there are slick "potential function" proofs.</li>
<li>Bernard Chazelle's algorithm for computing minimum spanning trees in linear times inverse Ackermann time. The algorithm uses <a href="http://en.wikipedia.org/wiki/Soft_heap">soft heaps</a>, a variant of the traditional <a href="http://en.wikipedia.org/wiki/Priority_queue">priority queue</a>, except that some "corruption" might occur and queries might not be answered correctly.</li>
<li>While on the topic of MSTs: an optimal algorithm has been <a href="http://www.eecs.umich.edu/~pettie/papers/jacm-optmsf.pdf">given by Pettie and Ramachandran</a>, but we don't know the running time!</li>
<li>Lots of randomized algorithms have interested analyses. I'll only mention one example: Delaunay triangulation can be computed in expected O(n log n) time by <a href="http://en.wikipedia.org/wiki/Delaunay_triangulation#Incremental">incrementally adding points</a>; the analysis is apparently intricate, though I haven't seen it.</li>
<li>Algorithms that use "bit tricks" can be neat, e.g. <a href="http://www.sice.umkc.edu/~hanyij/research/isortlln.ps">sorting in O(n log log n)</a> time (and linear space) -- that's right, it breaks the O(n log n) barrier by using more than just comparisons.</li>
<li><a href="http://en.wikipedia.org/wiki/Cache-oblivious_algorithm">Cache-oblivious algorithms</a> often have interesting analyses. For example, <a href="http://courses.csail.mit.edu/6.851/spring07/scribe/lec20.pdf">cache-oblivious priority queues</a> (see page 3) use log log n levels of sizes n, n<sup>2/3</sup>, n<sup>4/9</sup>, and so on.</li>
<li>(Static) range-minimum queries on arrays are neat. The <a href="http://www.ics.uci.edu/~eppstein/261/BenFar-LCA-00.pdf">standard proof</a> tests your limits with respect to reduction: range-minimum queries is reduced to least common ancestor in trees, which is in turn reduced to a range-minimum queries in a specific <em>kind</em> of arrays. The final step uses a cute trick, too.</li>
</ul>
|
Alternatives for JCIFS NTLM library <p>Are there any alternatives for JCIFS NTLM library?</p>
| <p>Waffle - <a href="https://github.com/dblock/waffle" rel="nofollow">https://github.com/dblock/waffle</a></p>
<p>Has filters, authenticators, supports spring-security, etc. Windows-only, but doesn't require native DLLs.</p>
|
Hardware Simulation <p>I'm working on a software project intended for recuperating old specific hardware, mostly for non-for-profit organizations and poor schools.</p>
<p>I need a way to simulate old hardware so I can test the application before shipping it out. </p>
<p>How can I do this?</p>
| <p>I'm not sure exactly what the question is asking for. I think you are asking for a way to emulate certain HW? </p>
<p>If that is the case, I've used <a href="http://wiki.qemu.org/Index.html" rel="nofollow">QEMU</a> in the past, and it has worked great. QEMU is an open source machine emulator and virtualizer.</p>
|
How do I design sms service? <p>I want to design a website that can send and receive sms.</p>
<ol>
<li>How should I approach the problem ?</li>
<li>What are the resources available ?</li>
<li>I know php,python what else do I need or are the better options available?</li>
<li>How can experiment using my pc only?[somthing like localhost]</li>
<li>What are some good hosting services for this? [edit this]</li>
<li>[Add more questions you can think of?]</li>
</ol>
| <p>You can take a look at <a href="http://www.kannel.org" rel="nofollow">Kannel</a>. It's so simple to create SMS services using it. Just define a keyword, then put in the URL to which the incoming SMS request will be routed (you'll get the info such as mobile number and SMS text in query string parameters), then whatever output your web script generates (you can use any web scripting/language/platform) will be sent back to the sender.</p>
<p>It's simple to test. You can use your own PC and just use the fakesmsc "SMS center" and just send it HTTP requests. If you have a GSM modem you can use that too, utilising the modem's AT command set.</p>
|
System.IO.FileNotFoundException when loading web service <p>I've a simple, if not primitive, C++/CLI .NET 2.0 class library. It is used in order to wrap some C++ legacy code for the Web Service. The following facts appear to be true:</p>
<ol>
<li>Primitive C# test program calls class library and it works.</li>
<li>If class library does not refer to any modules of our code base, it works as well as part of the web service. That is, I load the web service and invoke the methods and receive proper response.</li>
<li>The same moment I replace the copied and pasted code by the calls from our code base libraries, the Web Service stops to load. I get System.IO.FileNotFoundException message.</li>
</ol>
<p>The problem: I cannot find any place where the file name that couldn't be found is written.</p>
<p>I googled it and gave some permissions to some ASP.NET user on my computer. I copied all the DLLs of our libraries into the same directory where web service is installed. I searched in IIS logs, event logs, etc - no where could I find the name of the module that prevents the web service from coming up. </p>
<p>Any help on the matter would be greatly appreciated.</p>
<p>Boris</p>
| <p>What calls are you replacing? Could it be the original code gracefully handles missing files (which may not even be important) and yours does not?</p>
|
Should I ignore the occasional Invalid viewstate error? <p>Every now and then (once every day or so) we're seeing the following types of errors in our logs for an ASP.NET 3.5 application</p>
<ul>
<li>Invalid viewstate</li>
<li>Invalid postback or callback argument</li>
</ul>
<p>Are these something that "just happens" from time-to-time with an ASP.NET application? Would anyone recommend we spend a lot of time trying to diagnose what's causing the issues?</p>
| <p>Well it depends. Invalid viewstate can happen for a variety of reasons.</p>
<ol>
<li>Viewstate is too big and has not finished rendering before a user causes a postback on the page. The fix is generally to disable all controls that trigger postbacks and enable them client side once the page has finished loading - see <a href="http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx">http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx</a></li>
<li>You are using viewstate MACs (and you should be, for security reasons) but you have not set a machine key and the application pool has recycled generating a new one. Don't forget to set a ViewStateUserKey.</li>
<li>Someone is using an old version of IE on the mac where it truncates hidden form fields. In this case you'll need to move viewstate out of the page into <a href="http://msdn.microsoft.com/en-gb/magazine/cc163577.aspx#S4">session state</a>.</li>
<li>Viewstate MAC issues generally indicate you're on a web farm and have forgotten to set a machine key in web.config. However if you have done this then it is probably someone trying to do bad things (bots posting comments, someone trying to trigger events for disabled controls etc.) The cause of these should be tracked down if only to rule out potential security issues.</li>
</ol>
<p>Whatever you do <strong><em>do not</em></strong> turn off viewstate or event validation.</p>
|
TextField() - how to prevent mouse select <p>How can I prevent mouse selecting (and moving caret) with Editable TextField(),
this one does not seem to fully work when SELECTING text, but it prevents clicking. I want to keep cursor in place where its going.</p>
<pre><code>protected function handleMouseDEvent(evt:MouseEvent):void {
if (evt.type == MouseEvent.MOUSE_DOWN) {
var max : int;
max = this.text.length;
this.setSelection(max, max) // SET CURSOR POSITION
}
}
</code></pre>
| <p>if what you mean is to prevent the TextField for being selected, use:</p>
<pre><code>TextField.selectable = false;
</code></pre>
<p>But if what you mean is to prevent the TextField from blocking object behind it, use:</p>
<pre><code>TextField.mouseEnabled = false;
</code></pre>
|
Preorder tree traversal copy folder <p>We have a database that contains several Trees.
These trees are build using the "Preorder tree traversal" principle. This is a very powerful way of creating trees but it has one big disadvantage, adding multiple nodes at once.</p>
<p>We have to create a copy function in our tree, copying a single (lowest level) node is very easy, you can do this in one call.
But now we want to copy a whole folder at once.
We were wondering if we should do this in .net of with a stored procedure.
We have to make sure that the transaction works, if anything goes wrong all has to be rollbacked because otherweise the tree will get corrupted.</p>
<p>Anyone who can help me with this?
Any info about PTT you can find it here: <a href="http://en.wikipedia.org/wiki/Tree_traversal" rel="nofollow">http://en.wikipedia.org/wiki/Tree_traversal</a></p>
<p>Edit: </p>
<p>some more information is clearly needed.
I have a 2 trees:</p>
<pre><code>Root
Folder 1
Item
Item
Item
Folder 2
Item
Item
Folder 3
Folder 4
Item
Item
Folder 5
Item
Root 2
Folder 6
</code></pre>
<p>I want to be able to copy folder 3 underneith folder 6.
soo the children need to be copied together with all items.
And all the left and rights need to be adjusted properly. If something fails a complete rollback is needed. Hope this is much clearer now.</p>
<p>EDIT2 :</p>
<p>I've written a stored procedure for this.
If anyone wants it just ask i'll get back to this question later this day.
I'll post it if you want.</p>
| <p>Could you not traverse the entire tree and insert it into a new binary tree? If you have multiple data sets that need to be combined you can just traverse each one in any order and have the tree rebuild itself.</p>
<p>Could you give more information on what you mean with folder?</p>
<p>I think this question needs more information before it can be fully answered.</p>
<p>As for making sure the transaction works, test it on a database that is not in production!</p>
|
chrooted Apache+MsSQL on openBSD; Could not determine the server's fully qualified domain name <p>php generates GIFs on the web server using a databases on a second server.
The the page shows 20 GIFs, so there is some load for a short time (multiple connections)</p>
<p><hr /></p>
<p>Some GIFs are loaded but some are not, in <code>/var/www/logs/error_log</code></p>
<pre>
[Mon Feb 23 10:05:56 2009] [error] PHP Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server at 'reading initial communication packet', system error: 0 in /htdocs/.../myImage.php on line 4
[Mon Feb 23 10:05:56 2009] [error] PHP Fatal error: Lost connection to MySQL server at 'reading initial communication packet', system error: 0 in /htdocs/.../myImage.php on line 4</pre>
<p><hr /></p>
<p>in <code>/var/www/logs/error_log</code> on the MySQL server I found:</p>
<pre>[alert] httpd: Could not determine the server's fully qualified domain name, using 127.0.0.1 for ServerName</pre>
<p><hr /></p>
<p>Rebooting the MySQL server "resolves" the problem ... for a few days.</p>
<p>The 2 servers are virtual machines running OpenBSD, chroot'ed Apache and MySQL + phpMyAdmin.
unfortunately in diferent versions (OpenBSD 4.2(web) and 3.9(mysql))</p>
<p>my knowledge in <code>/var/www/conf/httpd.conf</code> and <code>my.cnf</code>(didn't found it) is very limited.<br />
Any ideas ?</p>
| <p>The "Could not determine the server's fully qualified domain name" error can be ignored, that's an internal apache thing.</p>
<p>Per <a href="http://dev.mysql.com/doc/refman/5.0/en/error-lost-connection.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.0/en/error-lost-connection.html</a> and <a href="http://bugs.mysql.com/bug.php?id=28359" rel="nofollow">http://bugs.mysql.com/bug.php?id=28359</a> this sounds like either a slow network, or an overloaded mysql that can't respond to connections fast enough.</p>
<p>Given that rebooting fixes the issue, I'm going to guess that you've got a slow resource leak. Probably something like expensive queries left running on mysql. You should be able to verify this by tracking system load over time.</p>
|
How do I make a DBIx::Class relationship with a fixed join condition? <p>We have a link table that can handle multiple types of object on one side, and I can't work out how to get from one of these objects to the link table using has_many.</p>
<p>Example: link table contains:</p>
<blockquote>
<pre><code>id link_id link_table resource_id
1 1 page 3
2 1 page 5
3 2 page 3
4 1 not_page 1
</code></pre>
</blockquote>
<p>Building the relationship from the resource side is easy enough:</p>
<pre><code>Resource->has_many(links => 'Link', 'resource_id');
</code></pre>
<p>but I haven't been able to get the corresponding relationship from the page side:</p>
<pre><code>Page->has_many(links => 'Link', 'link_id');
</code></pre>
<p>would get the not_page link</p>
<pre><code>Page->has_many(links => 'Link', {'foreign.link_id' => 'self.id', 'foreign.link_table' => 'page'});
</code></pre>
<p>gives an 'Invalid rel cond val page' error (which was not that surprising to me).</p>
<pre><code>Page->has_many(links => 'Link', {'foreign.link_id' => 'self.id', 'foreign.link_table' => '"page"'});
</code></pre>
<p>gives an 'Invalid rel cond val "page"' error. Throwing backslashes in didn't help.</p>
<p><a href="http://search.cpan.org/perldoc?DBIx::Class::Relationship::Base#add_relationship" rel="nofollow">DBIx::Class::Relationship::Base</a> says:</p>
<blockquote>
<p>The condition needs to be an <a href="http://search.cpan.org/perldoc?SQL%3A%3AAbstract" rel="nofollow">SQL::Abstract</a>-style representation of the join between the tables</p>
</blockquote>
<p>and I have tried various different options from there, such as:</p>
<pre><code>Page->has_many(links => 'Link', {'foreign.link_id' => 'self.id', 'foreign.link_table' => {'=', 'page'}});
</code></pre>
<p>but without any success at all.</p>
<p>If I added another field to the page table which always contains the value 'page' I could do</p>
<pre><code>Page->has_many(links => 'Link', {'foreign.link_id' => 'self.id', 'foreign.link_table' => 'self.what_table_am_i'});
</code></pre>
<p>but that's hardly an optimal solution.</p>
<p>Splitting the link table into a separate one for each type may be a possibility, but this is an existing project that is being considered for adaptation to DBIx::Class, and there may be other places where splitting a table into multiple other tables is more hassle than it's worth.</p>
| <p>You should just make a wrapper method that calls the relationship with the required arguments:</p>
<pre><code>Page->has_many(__all_links => 'Link', 'link_id');
sub links {
shift->__all_links({link_table => 'page'});
}
</code></pre>
<p>This would be pretty easy to turn into a DBIx::Class component if you have multiple tables that need to have this kind of join logic.</p>
|
Regex - I only want to match the start tags in regex <p>I am making a regex expression in which I only want to match wrong tags like: <code><p> *some text here, some other tags may be here as well but no ending 'p' tag* </p></code></p>
<pre><code> <P>Affectionately Inscribed </P><P>TO </P><P>HENRY BULLAR, </P><P>(of the western circuit)<P>PREFACE</P>
</code></pre>
<p>In the above same text I want to get the result as <code><P>(of the western circuit)<P></code> and nothing else should be captured. I'm using this but its not working:</p>
<pre><code><P>[^\(</P>\)]*<P>
</code></pre>
<p>Please help.</p>
| <p>Regex is not always a good choice for xml/html type data. In particular, attributes, case-sensitivity, comments, etc all have a big impact.</p>
<p>For xhtml, I'd use <code>XmlDocument</code>/<code>XDocument</code> and an xpath query.</p>
<p>For "non-x" html, I'd look at the <a href="http://www.codeplex.com/htmlagilitypack">HTML Agility Pack</a> and the same.</p>
|
Creating new exception in C++ <p>I have a C++ class and I am trying to run it in Ubuntu:</p>
<pre><code>#ifndef WRONGPARAMETEREXCEPTION_H_
#define WRONGPARAMETEREXCEPTION_H_
#include <iostream>
#include <exception>
#include <string>
using namespace std;
#pragma once
class WrongParameterException: public exception
{
public:
WrongParameterException(char* message): exception(message) {};
virtual ~WrongParameterException() throw() {};
};
#endif
</code></pre>
<p>when I try to compile it, the compiler gives me this error:</p>
<pre><code>WrongParameterException.h: In constructor âWrongParameterException::WrongParameterException(char*)â:
WrongParameterException.h:14: error: no matching function for call to âstd::exception::exception(char*&)â
/usr/include/c++/4.3/exception:59: note: candidates are: std::exception::exception()
/usr/include/c++/4.3/exception:57: note: std::exception::exception(const std::exception&)
</code></pre>
<p>Can anyone tell me what am I doing wrong? I tried changing the message variable to <code>string</code> or <code>const string</code> or <code>const string&</code> but it didn't help.</p>
<p>Here is how I use the new exception that I created from main:</p>
<pre><code>try
{
if ((strToInt1 == -1) || (parameters[1] == NULL) || (strToInt3 == -1) || (parameters[3] != NULL))
{
throw WrongParameterException("Error in the config or commands file");
}
}
catch(WrongParameterException e)
{
log.addMsg(e.what());
}
</code></pre>
| <p>First, <code>#pragma once</code> is the wrong way to go about it, learn about header include guards. <a href="http://stackoverflow.com/a/34884735/13986">Related question on SO</a> explains why using <code>#pragma once</code> is the wrong way to go about it. Wikipedia explains how to use <a href="https://en.wikipedia.org/wiki/Include_guard" rel="nofollow">include guards</a> which serve the same purpose without any of the downsides.</p>
<p>Second, you are calling the constructor of std::exception with a parameter it does not know, in this case a pointer to a character array.</p>
<pre><code>#include <stdexcept>
#include <string>
class WrongParameterException : public std::runtime_error {
public:
WrongParameterException(const std::string& message)
: std::runtime_error(message) { };
};
</code></pre>
<p>Would probably be what you want. For more information on exceptions, check out <a href="http://www.parashift.com/c++-faq-lite/exceptions.html" rel="nofollow" title="Exceptions">C++ FAQ Lite article on Exceptions</a> and the <a href="http://www.cplusplus.com/doc/tutorial/exceptions.html" rel="nofollow">exceptions article</a> at cplusplus.com.</p>
<p>Good luck!</p>
|
class loader <p>I'm having problem with class loaders. All the time. </p>
<p>Sometimes it works, sometimes it doesn't work. </p>
<p>When I started I've tested this works but not from *.jar:</p>
<p>URL url = AcAnalyzer.class.getResource("../stuff/resource");</p>
<p>//and this works even from jar file:</p>
<p>URL url = Acnalyzer.class.getResource("/stuff/resource");</p>
<p>URL url = AcAnalyzer.class.getClassLoader().getResource("stuff/resource");</p>
<p>//But I got into the problem with tomcat..when I need to deploy it into the tomcat I had to do this:</p>
<p>URL url = Thread.currentThread().getContextClassLoader().getResource("something.xml");</p>
<p>where something.xml has to be in WEB-INF/classes/</p>
<p>... url.getFile();</p>
<p>//The problem is that most of the time it has to work within and not within jar at the same time. Now I have test where my class is getting resource, and the jar file is used in some project deployed under the tomcat..and somehow it doesn't want to work anymore: </p>
<p>I'm bit puzzled about class loaders :) .. How to get this resource? And and the same time have working test.</p>
<p>URL url = Thread.currentThread().getContextClassLoader().getResource("com/st/resource");</p>
<pre><code> FileInputStream inputStream = new FileInputStream(url.getFile());
</code></pre>
<p>java.io.FileNotFoundException: file:/home/aaa/.m2/repository/com/st/module-1.1-SNAPSHOT.jar!/com/st/resource (No such file or directory)</p>
<p>thank you for help</p>
| <p>I'm not sure exactly what the question is in the first part, although I'd advise not using "../" in a resource path.</p>
<p>For the second part, if you want to load a resource you shouldn't use FileInputStream - you should use <code>getResourceAsStream()</code> instead of <code>getResource().getFile()</code>. Just load from that <code>InputStream</code> - there won't always be an individual file that you <em>can</em> load with <code>FileInputStream</code>.</p>
<p>EDIT: The two ways of referring to a resource are <code>ClassLoader.getResource</code> and <code>Class.getResource</code> (and the equivalents with the <code>AsStream</code> suffix). The difference between them (the only difference that I'm aware of, although there may be others) is that <code>Class.getResource</code> treats the given path as being relative to the package of the class that you call it on. So</p>
<pre><code>ClassLoader.getResource("foo/bar/baz/test.xml")
</code></pre>
<p>is equivalent to </p>
<pre><code>foo.bar.SomeClass.class.getResource("baz/test.xml");
</code></pre>
<p>As for the difference between <code>Class.getClassLoader()</code> and <code>Thread.getContextClassLoader()</code> I won't claim to have a good understanding - I suggest you ask that as a separate question.</p>
|
ASP.Net TreeView Scrolling the selected node into view <p>Is there a way to scroll the selected node of an ASP.Net TreeView into view after a postback? </p>
<p>In my parrticular scenario the control is repopulated after each postback.</p>
<p>Thanks!</p>
| <p>I figured it out. The TreeView control creates a javascript object on the client. It is named whatever you called the treeview with a '_Data' appended. The object lets you get a reference to the selected node.</p>
<p>The code below uses the ASP.Net Ajax extensions. Just remember to change the TreeView name to whatever you called yours.</p>
<pre><code>var name = myTreeView_Data.selectedNodeID.value;
var selectedNode = $get(name);
if(selectedNode)
{
selectedNode.scrollIntoView(true);
}
</code></pre>
|
MAP file analysis - where's my code size comes from? <p>I am looking for a tool to simplify analysing a linker map file for a large C++ project (VC6). </p>
<p>During maintenance, the binaries grow steadily and I want to figure out where it comes from. I suspect some overzealeous template expansion in a library shared between different DLL's, but jsut browsign the map file doesn't give good clues.</p>
<p>Any suggestions?</p>
| <p><a href="http://www.sikorskiy.net/prj/amap/index.html">This</a> is a wonderful compiler generated map file analysis/explorer/viewer tool. Check if you can explore gcc generated map file.</p>
<p><em>amap : A tool to analyze .MAP files produced by 32-bit Visual Studio compiler and report the amount of memory being used by data and code.
This app can also read and analyze MAP files produced by the Xbox360, Wii, and PS3 compilers.</em> </p>
|
c# equivalent to php associative array? <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/1915347/c-sharp-associative-array">C# associative array</a> </p>
</blockquote>
<p>ive decided to learn c# recently. ive done some php before. i see c# has dictionaries. thats equivalent to an associative array in php right? as far as i can tell the dictionary doesnt maintain insertion order like php associative arrays right? is there some other equivalent i should use if insertion order is important?</p>
<p>thanks</p>
| <p>Dictionary doesn't <em>guarantee</em> to preserve insertion order, so no: you can't rely on that (although it is hard to force it to break this). If insertion order is important, you would need to create a hybrid class, perhaps encapsulating a <code>List<T></code> for the inserted order, and a <code>Dictionary<TKey,T></code> for the indexing.</p>
|
Sql Server Backup Sizes <p>Does anyone have real world experience of backup compression in Sql 2008, I'd like to know how it performs compared to Sql 2005 + winrar. Currently when I back up a I get a 14G file. Using rar shrinks it to <400M, a massive saving. Most of the data is similar, being figures from the stock market so I guess that makes it easy to compress. </p>
| <p>The figures I have seen suggest compression ratios in the range 3 - 4.5 times smaller, which is not as good as the figures you quoted for rar. See <a href="http://sqlcat.com/technicalnotes/archive/2008/04/21/tuning-the-performance-of-backup-compression-in-sql-server-2008.aspx" rel="nofollow">Tuning the Performance of Backup Compression in SQL Server 2008</a>.</p>
<p>On a side note, creating compressed backups is faster.</p>
|
Pair-wise iteration in C# or sliding window enumerator <p>If I have an IEnumerable like:</p>
<pre><code>string[] items = new string[] { "a", "b", "c", "d" };
</code></pre>
<p>I would like to loop thru all the pairs of consecutive items (sliding window of size 2). Which would be </p>
<pre><code>("a","b"), ("b", "c"), ("c", "d")
</code></pre>
<p>My solution was is this </p>
<pre><code> public static IEnumerable<Pair<T, T>> Pairs(IEnumerable<T> enumerable) {
IEnumerator<T> e = enumerable.GetEnumerator(); e.MoveNext();
T current = e.Current;
while ( e.MoveNext() ) {
T next = e.Current;
yield return new Pair<T, T>(current, next);
current = next;
}
}
// used like this :
foreach (Pair<String,String> pair in IterTools<String>.Pairs(items)) {
System.Out.PrintLine("{0}, {1}", pair.First, pair.Second)
}
</code></pre>
<p>When I wrote this code, I wondered if there are already functions in the .NET framework that do the same thing and do it not just for pairs but for any size tuples.
IMHO there should be a nice way to do this kind of sliding window operations.</p>
<p>I use C# 2.0 and I can imagine that with C# 3.0 (w/ LINQ) there are more (and nicer) ways to do this, but I'm primarily interested in C# 2.0 solutions. Though, I will also appreciate C# 3.0 solutions.</p>
| <p>In .NET 4 this becomes even easier:-</p>
<pre><code> var input = new[] { "a", "b", "c", "d", "e", "f" };
var result = input.Zip(input.Skip(1), (a, b) => Tuple.Create(a, b));
</code></pre>
|
DataGridViewComboBoxColumn - type of items in the drop down list <p>I have a DataGridView that has a ComboBox column. I populate this column's list with items of a type <strong>Field</strong>: </p>
<pre><code>DataGridViewComboBoxColumn fieldsColumn = argumentsDataGridView.Columns["field"] as DataGridViewComboBoxColumn;
foreach (Field field in SessionData.Fields)
fieldsColumn.Items.Add(field);
fieldsColumn.DisplayMember = "Name";
</code></pre>
<p>Then after some user's action I put a value in the cell of this column like this: </p>
<pre><code>private void AddArgument(string argumentName, Field field)
{
int index = argumentsDataGridView.Rows.Count;
argumentsDataGridView.Rows.Add(new DataGridViewRow());
DataGridViewRow newRow = argumentsDataGridView.Rows[index];
newRow.Cells["nameArg"].Value = argumentName;
-> newRow.Cells["field"].Value = field;
}
</code></pre>
<p>If I now access the cell's Value, it is of a type <strong>Field</strong>. If I select different item from the combo, the cell's Value becomes a string. How can I handle it? I need items of type <strong>Field</strong>.</p>
| <p>the solution was to create a property <strong>Self</strong> in class <strong>Field</strong>: </p>
<pre><code>public Field Self
{
get { return this; }
}
</code></pre>
<p>and set is as a ValueMember of the combo box column.<br />
I thought that without specifing ValueMember <em>this</em> is a default return value and I was wrong.</p>
|
Running xcodebuild from a forked terminal <p>I'm trying to setup an automated build server for an iPhone application. I'd like to be able to have nightly adhoc beta builds so that testers can follow the development.</p>
<p>I've setted up xcode successfully xcode to perform adhoc builds and I can also launch the build from the command line:</p>
<blockquote>
<p>xcodebuild -configuration AdHoc -sdk iphoneos2.2 clean build</p>
</blockquote>
<p>The problem I'm having is that the following line doesn't work from a forked terminal (using nohup or screen) and failed with the following</p>
<blockquote>
<p>CodeSign error: Code Signing Identity 'iPhone Distribution: XXXXX' does not match any code-signing certificate in your keychain. Once added to the keychain, touch a file or clean the project to continue.</p>
</blockquote>
<p>I've checked my environment variables in my shell and in nohup or screen and didn't found a clue.
I guess my problem is that the forked terminal can't access to the keychain but I have no clue on how to allow it.</p>
<p>Thanks for your help</p>
| <p>I had te error <strong>User interaction is not allowed</strong> and solved it by unlocking the keychain first</p>
<pre><code>security unlock-keychain /Users/yannooo/Library/Keychains/login.keychain
</code></pre>
<p>I've also tried to put my certs in the System's keychain and it was working.
My final solution was to put all my iPhone related certs in a dedicated keychain named iPhone.keychain using the <em>Keychain Access</em> application</p>
<pre><code>security list-keychains -s /Users/yannooo/Library/Keychains/iPhone.keychain
security unlock-keychain -p keychainpassword /Users/yannooo/Library/Keychains/iPhone.keychain
</code></pre>
|
send(), returns Winsock Error 10038 <p><strong>Problem:</strong></p>
<ul>
<li>Call to <strong>send()</strong>, returns Winsock Error <strong>10038</strong> against socket handle</li>
</ul>
<p><strong>Illustration:</strong></p>
<pre><code>acceptedSocket = accept (server, (sockaddr *)&sin, &len);
</code></pre>
<ul>
<li><strong>accept()</strong>, returns <strong>0</strong>
<ul>
<li>A new <strong>thread</strong>, is created for each connection</li>
<li><strong>send()</strong>, (in thread function) returns <strong>10038</strong></li>
</ul></li>
</ul>
<p><strong>Illustration:</strong> - in thread function</p>
<pre><code>//omitted
SOCKET RemoteSocket = (SOCKET) client;
//omitted
send (RemoteSocket, stringToSpend, strlen(stringToSpend), 0)
</code></pre>
<p><strong>Suggestions:</strong></p>
<ul>
<li>Possible, race condition?</li>
<li>Could use I/O completion ports, but not at this stage </li>
</ul>
| <p>accept() returns you a handle to a new connection-specific socket. for server code it's 2+ sockets involved: one is in listen state you are calling accept() for and second is one returned from accept() - it's an incoming connection socket. Following accept() can return socket for second incoming connection etc. if accept() returns 0 it's not an incoming connection - it's an error.</p>
|
How can I make this Python recursive function return a flat list? <p>Look at this simple function</p>
<pre><code>def prime_factors(n):
for i in range(2,n):
if n % i == 0:
return i, prime_factors(n / i)
return n
</code></pre>
<p>Here's the result of <code>prime_factors(120)</code></p>
<pre><code>(2, (2, (2, (3, 5))))
</code></pre>
<p>Instead of nested tuples, I want it to return one flat tuple or list.</p>
<pre><code>(2, 2, 2, 3, 5)
</code></pre>
<p>Is there a simple way to do that?</p>
| <pre><code>def prime_factors(n):
for i in range(2,n):
if n % i == 0:
return [i] + prime_factors(n / i)
return [n]
</code></pre>
|
Why does this integer overflow occur? <p>I've wrapped a dll method that has an integer as an out parameter in a web service.
In testing I was finding that when I was expecting -1 I was getting 65,535 instead. I realised that the dll was using 16 bit integers and I was specifying the standard .NET 32bit integer when referencing the external dll in my code. this was quickly fixed by specifying a 16 bit integer and all is well.</p>
<p>My question is why did this happen? I could understand an overflow occuring if I was trying to fit a 32 bit integer in a 16 bit integer but I am not so sure why this happens the other way round. Clearly my understanding of this type of casting between types is a little lacking so any guidance will be greatly appreciated.</p>
| <p>A 16 bit integer "-1" has all 16 bits set. If you set the bottom 16 bits of a 32 bit integer, the value is 65,535. For an explanation of the internal representation of negative ints, have a look at <a href="http://en.wikipedia.org/wiki/Two_complement" rel="nofollow">this article</a>.</p>
|
JTextPane keeps throwing BadLocation <p>I have a JFrame that contains a JTextPane. The purpose of this JTextPane is to highlight words as I type them, something along the lines of a programmer's text editor. To accomplish this, I extended JTextPane, I implemented the <strong>KeyListener</strong> interface, and I had it setup as a <strong>key listener</strong> to self. The method that does some important work is <strong>keyReleased</strong>. The problem is, I can highlight the first word I type, but after that, I keep getting BadLocation, even though the <strong>start</strong> and the <strong>end</strong> are within document limits. I am posting some of my code snippets :</p>
<pre><code>
// this is my highlight method
private void highlight(int start,int end) throws BadLocationException {
Document doc = getDocument();
Color c = Color.red;
String text = doc.getText(start,end);
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
setCharacterAttributes(aset, true);
setSelectionStart(start);
setSelectionEnd(end);
replaceSelection(text);
}
//this is my keyReleased method
public void keyReleased(KeyEvent arg0) {
char character = arg0.getKeyChar();
if(wordStarted) { // have I started typing a new word ?
if(character == ' ') { // end word
try {
int dot = getCaret().getDot();
highlight(wordStart, dot - 1);
setCaretPosition(dot);
wordStarted = false;
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
}
else {
if(Character.isLetter(character)) {
wordStarted = true;
wordStart = getCaret().getDot() -1;
}
}
}
</code></pre>
I tried to type in : <strong>public static</strong> but only <strong>public</strong> is colored red. I even added some println statements for debugging, and this is the output:
<pre>
this is outputted after writing public
Start param:0
End param:6
Document Length:7
Document START:0
Document END:8
text:public
this is outputted after writing static
Start param:7
End param:13
Document Length:14
Document START:0
Document END:15
text:public static
javax.swing.text.BadLocationException: Invalid location
at javax.swing.text.GapContent.getChars(GapContent.java:189)
at javax.swing.text.GapContent.getString(GapContent.java:167)
at javax.swing.text.AbstractDocument.getText(AbstractDocument.java:774)
at ifirst.visual.CodePanel.highlight(CodePanel.java:49)
at ifirst.visual.CodePanel.keyReleased(CodePanel.java:82)
at java.awt.Component.processKeyEvent(Component.java:6069)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2810)
at java.awt.Component.processEvent(Component.java:5885)
at java.awt.Container.processEvent(Container.java:2105)
at java.awt.Component.dispatchEventImpl(Component.java:4469)
at java.awt.Container.dispatchEventImpl(Container.java:2163)
at java.awt.Component.dispatchEvent(Component.java:4295)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1881)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:742)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1007)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:879)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:706)
at java.awt.Component.dispatchEventImpl(Component.java:4339)
at java.awt.Container.dispatchEventImpl(Container.java:2163)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4295)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:604)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)
</pre>
<p>I am writing this code to get a hang of JTextPane. I am not interested in something like <strong>JTextPane</strong>.</p>
| <p>As you discovered, the<a href="http://java.sun.com/javase/6/docs/api/javax/swing/text/Document.html#getText(int,%20int)">Document.getText()</a> takes a start and <em>length</em>, not a start and <em>end</em> argument. I thought I'd provide an answer and a link to the JavaDoc for others reading your question who might not look in the comments.</p>
|
Filtering DataGridView rows in .Net <p>I have a DataGridView that is displaying a List of objects (not DataSet).
Is there an easy way to set a filter, so the DGV will only display rows that match the filter?</p>
<pre><code>IList<T> log = ...;
dgv.DataSource = log;
</code></pre>
| <p>Do you have LINQ available? If so, one option is:</p>
<pre><code>dgv.DataSource = log.Where(x=>x.IsActive && x.Type == 3).ToList();
</code></pre>
<p>However, new/removed rows won't update the original list (edits to existing rows are fine).</p>
<p>If not LINQ, you can do the same with <code>List<T>.FindAll</code>:</p>
<pre><code>dgv.DataSource = log.FindAll(delegate (SomeType x) {
return x.IsActive && x.Type == 3;});
</code></pre>
<p>There is the <code>IBindingListView.SupportsFiltering</code> / <code>IBindingListView.Filter</code> pair, but none of the standard lists (including <code>BindingList<T></code>) implement this feature.</p>
|
Can file uploads time out in PHP? <p>Hi im quite new to PHP, i have created a form for very large csv files to be uploaded to my server. Some one mentioned to me that the browser can time out due to the uploading file being to big, is this true? and if so, can it be prevented?</p>
<p>Thanks for your help!</p>
| <p>You need a proper value for the following php.ini settings:</p>
<ol>
<li><a href="http://www.php.net/manual/en/info.configuration.php#ini.max-input-time">max_input_time</a> (<strong>not</strong> max_execution_time!)</li>
<li><a href="http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize">upload_max_filesize</a></li>
<li><a href="http://www.php.net/manual/en/ini.core.php#ini.post-max-size">post_max_size</a></li>
</ol>
<p>and maybe</p>
<ol>
<li><a href="http://www.php.net/manual/en/ini.core.php#ini.memory-limit">memory_limit</a></li>
</ol>
|
Easiest way to create a scrollable area using wxPython? <p>Okay, so I want to display a series of windows within windows and have the whole lot scrollable. I've been hunting through <a href="http://docs.wxwidgets.org/stable/wx_wxscrolledwindow.html#wxscrolledwindow" rel="nofollow">the wxWidgets documentation</a> and a load of examples from various sources on t'internet. Most of those seem to imply that a wx.ScrolledWindow should work if I just pass it a nested group of sizers(?):</p>
<blockquote>
<p>The most automatic and newest way is to simply let sizers determine the scrolling area.This is now the default when you set an interior sizer into a wxScrolledWindow with wxWindow::SetSizer. The scrolling area will be set to the size requested by the sizer and the scrollbars will be assigned for each orientation according to the need for them and the scrolling increment set by wxScrolledWindow::SetScrollRate.</p>
</blockquote>
<p>...but all the example's I've seen seem to use the older methods listed as ways to achieve scrolling. I've got something basic working, but as soon as you start scrolling you lose the child windows:</p>
<pre><code>import wx
class MyCustomWindow(wx.Window):
def __init__(self, parent):
wx.Window.__init__(self, parent)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.SetSize((50,50))
def OnPaint(self, event):
dc = wx.BufferedPaintDC(self)
dc.SetPen(wx.Pen('blue', 2))
dc.SetBrush(wx.Brush('blue'))
(width, height)=self.GetSizeTuple()
dc.DrawRoundedRectangle(0, 0,width, height, 8)
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.scrolling_window = wx.ScrolledWindow( self )
self.scrolling_window.SetScrollRate(1,1)
self.scrolling_window.EnableScrolling(True,True)
self.sizer_container = wx.BoxSizer( wx.VERTICAL )
self.sizer = wx.BoxSizer( wx.HORIZONTAL )
self.sizer_container.Add(self.sizer,1,wx.CENTER,wx.EXPAND)
self.child_windows = []
for i in range(0,50):
wind = MyCustomWindow(self.scrolling_window)
self.sizer.Add(wind, 0, wx.CENTER|wx.ALL, 5)
self.child_windows.append(wind)
self.scrolling_window.SetSizer(self.sizer_container)
def OnSize(self, event):
self.scrolling_window.SetSize(self.GetClientSize())
if __name__=='__main__':
app = wx.PySimpleApp()
f = TestFrame()
f.Show()
app.MainLoop()
</code></pre>
| <p>Oops.. turns out I was creating my child windows badly:</p>
<pre><code>wind = MyCustomWindow(self)
</code></pre>
<p>should be:</p>
<pre><code>wind = MyCustomWindow(self.scrolling_window)
</code></pre>
<p>..which meant the child windows were waiting for the top-level window (the frame) to be re-drawn instead of listening to the scroll window. Changing that makes it all work wonderfully :)</p>
|
Capture stdout in log4j/log4net <p>I have a library that writes to stdout in Java. I would like to capture this output in a log using log4j. (I didn't write this library, so I have no control over the code inside the library).</p>
<p>Is there an easy way to do this? Is System.setOut the right approach? What do I pass to System.setOut?</p>
<p>Also, how would you do this in .NET/C#?</p>
| <p>One solution is to subclass <code>OutputStream</code>. You only have to implement <code>write( int b )</code>. Then create a <code>PrintStream</code> with your <code>OutputStream</code> in the constructor.</p>
<p>It could look like :</p>
<pre><code>public class L4JOS extends OutputStream {
logger = Logger.getLogger( "std.out" );
private int lineEnd = (int)'\n';
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
public void write( int b ) throws IOException {
baos.write( b );
if ( b == lineEnd ) {
logger.info( baos.toString() );
baos.reset();
}
}
}
</code></pre>
<p>If it is multi threaded then you have more work. And make sure that the appender does not go to System.out.</p>
|
Common Lisp equivalent to C enums <p>I'm trying to learn some Lisp (Common Lisp) lately, and I wonder if there is a way to give constant numbers a name just like you can do in C via enums. </p>
<p>I don't need the full featureset of enums. In the end I just want to have fast <em>and</em> readable code.</p>
<p>I've tried globals and little functions, but that always came with a degration in performance. Just plugging the numbers into the code was always faster.</p>
| <p>The normal way to do enumerations in Lisp is to use symbols. Symbols get interned (replaced with pointers to their entries in a symbol table) so they are as fast as integers and as readable as enumerated constants in other languages.</p>
<p>So where in C you might write:</p>
<pre>
enum {
apple,
orange,
banana,
};
</pre>
<p>In Lisp you can just use <code>'apple</code>, <code>'orange</code> and <code>'banana</code> directly.</p>
<p>If you need an enumerated <em>type</em>, then you can define one with <a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/mac_deftype.html"><code>deftype</code></a>:</p>
<pre>(deftype fruit () '(member apple orange banana))</pre>
<p>and then you can use the type <code>fruit</code> in <code>declare</code>, <code>typep</code>, <code>typecase</code> and so on, <del>and you can write generic functions that specialize on that type</del>.</p>
|
Reading private keys from oracle wallet <p>We use Oracle wallet for scripting Oracle releases.</p>
<p>Using mkstore I can add or delete private keys to Oracle wallet.</p>
<p>Either using Java or C#, I want to read the private key sitting inside the Oracle wallet.</p>
<p>Could someone share the sample code how to do that.</p>
<p>This post explains how to open a wallet using Java, but it does not read the private key.
<a href="http://blog.mikesidoti.com/2007/04/opening-oracles-wallet.html" rel="nofollow">http://blog.mikesidoti.com/2007/04/opening-oracles-wallet.html</a></p>
| <p>Isn't the point of the wallet to prevent anything from reading the private key?</p>
|
URL query string convention for multiple sort <p>I have a RESTful web application that supports multiple sort fields on a collection of items. Is there a common convention for encoding these sort fields into the query string of a URL? I'm considering a pattern like the following: </p>
<pre><code>http://myapp.com/books?sort=author:asc,datepublished:desc&count=12
</code></pre>
<p>This would sort the collection of books by author and then by date published.</p>
<p>Basically, I need a convenient way for the name-value pairs in my query string to have name-value pairs of their own. I'll need to do something similar to the above example for filter parameters, too.</p>
<p>Does Rails or ASP.NET MVC have a pattern for this? Are there other frameworks that have established ways for dealing with this issue? I'd rather use a familiar format than roll my own.</p>
<p>I'd also prefer a format that uses as little URL percent-encoding as possible. </p>
| <p>I've done this before using the standard SQL sorting syntax. There are numerous parsing functions and techniques out there.</p>
<pre><code>http://myapp.com/books?sort=author asc,datepublished desc&count=12
</code></pre>
<p>which would be encoded to </p>
<pre><code>http://myapp.com/books?sort=author+asc,datepublished+desc&count=12
</code></pre>
|
Sending Dates over RMI between machines in different regions <p>I'm having a problem sending java.util.Date objects over RMI, to and from machines in different timezones. </p>
<p>For example, a client in Germany will send a date object to a server in the UK.</p>
<ol>
<li>User enters a date string e.g. 20090220.</li>
<li>Client app in Germany converts it to date using SimpleDateFormat("yyyyMMdd") to give: Fri Feb 20 00:00:00 CET 2009</li>
<li>Server in UK receives Date over RMI as: Thu Feb 19 23:00:00 GMT 2009</li>
<li>Server stores Date into a UK Oracle Database DATE column</li>
</ol>
<p>What is the best way to get around this issue of incorrect dates?
I could send the date string across and have the Server convert it to a Date, but I want to reduce the amount of work that the Server has to do.</p>
<p>Here is a stand-alone test program showing date serialisation:</p>
<pre><code>import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class SerializationTest {
public static void main(String[] args) throws Exception {
final String yyyyMMdd = "20090220";
final Date date = new SimpleDateFormat("yyyyMMdd").parse(yyyyMMdd);
if (args.length != 1) {
System.out.println("Usage SerializationTest S|D");
}
boolean serialise = false;
if (args[0].equals("S")) {
serialise = true;
}
else if (args[0].equals("D")) {
serialise = false;
}
String filename = "date.ser";
if (serialise) {
// write the object to file
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream outputStream = new ObjectOutputStream(bos);
outputStream.writeObject(date);
outputStream.flush();
outputStream.close();
System.out.println("Serialised: " + date);
}
else {
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream inputStream = new ObjectInputStream(bis);
Date outDate = (Date) inputStream.readObject();
inputStream.close();
// print the object
System.out.println(outDate);
}
}
}
</code></pre>
| <p>I fail to see what your problem is here, those dates look correct to me- they're just being formatted to the locale in use. If you want the date entered by the user to be in GMT, specify the locale on the SimpleDateFormat constructor</p>
|
Are all these SQL joins logically equivalent? <p>I'm just wondering if all of the following joins are logically equivalent, and if not, why not?</p>
<pre><code>SELECT t1.x, t2.y from t1, t2 where t1.a=t2.a and t1.b=t2.b and t1.c = t2.c;
SELECT t1.x, t2.y from t1 join t2 on t1.a=t2.a where t1.b=t2.b and t1.c = t2.c;
SELECT t1.x, t2.y from t1 join t2 on t1.a=t2.a and t1.b=t2.b where t1.c = t2.c;
SELECT t1.x, t2.y from t1 join t2 on t1.a=t2.a and t1.b=t2.b and t1.c = t2.c;
</code></pre>
<p>I guess my real question is: does combining "where" with "on" doing something different from just having multiple conditions ANDed together with "on"?</p>
<p>I work with MySQL, in case that makes a difference.</p>
| <p>They are logically equivalent and should produce the same result. However, the last one is to be preferred as it states more correctly the semantics of the query - i.e. "join tables t1 and t2".</p>
<p>The WHERE clause should be used for "filtering" results of the join - e.g.</p>
<pre><code>... WHERE t2.some_col > 10
</code></pre>
<p>Also, as Constantin has said in another answer, the 4 queries would be different if the join was an OUTER join.</p>
|
Selecting an object on a WPF Canvas? <p>I have a WPF Canvas with some Ellipse objects on it (displayed as circles). Each circle is from a collection class instance which is actually a custom hole pattern class. Each pattern has a certain number of circles, and each circle then gets added to the canvas using an iteration over the collection using the code below.</p>
<p>So, the canvas is populated with a bunch of circles and each circle belongs to a certain pattern instance. You can see a screenshot here: <a href="http://twitpic.com/1f2ci/full" rel="nofollow">http://twitpic.com/1f2ci/full</a></p>
<p>Now I want to add the ability to click on a circle on the canvas, and be able to determine the collection it belongs to, so that I can then do some more work on the selected pattern to which that circle belongs.</p>
<pre><code>public void DrawHoles()
{
// Iterate over each HolePattern in the HolePatterns collection...
foreach (HolePattern HolePattern in HolePatterns)
{
// Now iterate over each Hole in the HoleList of the current HolePattern...
// This code adds the HoleEntity, HoleDecorator, and HoleLabel to the canvas
foreach (Hole Hole in HolePattern.HoleList)
{
Hole.CanvasX = SketchX0 + (Hole.AbsX * _ZoomScale);
Hole.CanvasY = SketchY0 - (Hole.AbsY * _ZoomScale);
canvas1.Children.Add(Hole.HoleEntity);
}
}
}
</code></pre>
| <p>All <code>FrameworkElements</code> have a <code>Tag</code> property which is of type object that can be used to hold arbitrary information. You could assign the <code>HolePattern</code> to the <code>Tag</code> property and easily use that later to get the associated collection.</p>
<p>i.e.:</p>
<pre><code>...
Hole.HoleEntity.Tag = HolePattern as object;
canvas1.Children.Add(Hole.HoleEntity);
</code></pre>
<p>later on in the click event:</p>
<pre><code>event(object sender,....)
{
Ellipse e = sender as Ellipse;
HolePattern hp = e.Tag as HolePattern;
...
}
</code></pre>
|
How to output the code itself? <p>How many ways are there to let the code output itself? </p>
<p>For example, write the code below,</p>
<pre><code>public class Test
{
public static void main(String[] args)
{
// some code
}
}
</code></pre>
<p>to output itself</p>
<pre><code>public class Test
{
public static void main(String[] args)
{
// some code
}
}
</code></pre>
<p>(Any programming language is accepted)</p>
<p>EDIT
This question has been answered in the historical posts,
search "quine" or check out <a href="http://stackoverflow.com/search?q=quine">http://stackoverflow.com/search?q=quine</a></p>
| <p>This is called a programming quine, and has been extensively discussed on SO:</p>
<p><a href="http://stackoverflow.com/search?q=quine">http://stackoverflow.com/search?q=quine</a></p>
<p>Also see</p>
<p><a href="http://en.wikipedia.org/wiki/Quine_(computing)" rel="nofollow">http://en.wikipedia.org/wiki/Quine_(computing)</a></p>
<p><a href="http://www.nyx.net/~gthompso/quine.htm" rel="nofollow">http://www.nyx.net/~gthompso/quine.htm</a></p>
<p><a href="http://www.madore.org/~david/computers/quine.html" rel="nofollow">http://www.madore.org/~david/computers/quine.html</a></p>
|
How trustworthy is javascript's random implementation in various browsers? <p>I would like to do some experimenting with javascript and encryption and I got curious as to how unpredictable the implementation of the random function is. Has anyone done any hard tests?</p>
<p>Clearly browsers have the ability to generate strong randomness (for ssl). The questions is do they give javascript access to the same strength.</p>
| <p>Generally, the random function is not cryptographically strong, for that you need to make sure you are using a cryptographic pseudo-random-number generator.</p>
<p>Generic random functions generally don't use cryptographically strong generation methods because they take longer than simple ones, (eg. Yarrow is more complicated than Mersenne Twister) and require careful management of the entropy pool, which is not a guarantee that Mozilla, cstdlib, etc. want to make to you.</p>
<p>If you need access to cryptographically strong random number generators, I'd look into getting access to the underlying SSL implementation (which a given browser may or may not allow access to).</p>
|
AuiNotebook, where did the event happend <p>How can I find out from which AuiNotebook page an event occurred?</p>
<p>EDIT: Sorry about that. Here are a code example. How do I find the notebook page
from witch the mouse was clicked in?</p>
<pre><code>#!/usr/bin/python
#12_aui_notebook1.py
import wx
import wx.lib.inspection
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.nb = wx.aui.AuiNotebook(self)
self.new_panel('Pane 1')
self.new_panel('Pane 2')
self.new_panel('Pane 3')
def new_panel(self, nm):
pnl = wx.Panel(self)
self.nb.AddPage(pnl, nm)
self.sizer = wx.BoxSizer()
self.sizer.Add(self.nb, 1, wx.EXPAND)
self.SetSizer(self.sizer)
pnl.Bind(wx.EVT_LEFT_DOWN, self.click)
def click(self, event):
print 'Mouse click'
#How can I find out from witch page this click came from?
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, '12_aui_notebook1.py')
frame.Show()
self.SetTopWindow(frame)
return 1
if __name__ == "__main__":
app = MyApp(0)
# wx.lib.inspection.InspectionTool().Show()
app.MainLoop()
</code></pre>
<p>Oerjan Pettersen</p>
| <p>For a mouse click you can assume the current selected page is the one that got the click. I added a few lines to your code. See comments</p>
<pre><code>def new_panel(self, nm):
pnl = wx.Panel(self)
# just to debug, I added a string attribute to the panel
# don't you love dynamic languages? :)
pnl.identifierTag = nm
self.nb.AddPage(pnl, nm)
self.sizer = wx.BoxSizer()
self.sizer.Add(self.nb, 1, wx.EXPAND)
self.SetSizer(self.sizer)
pnl.Bind(wx.EVT_LEFT_DOWN, self.click)
def click(self, event):
print 'Mouse click'
# get the current selected page
page = self.nb.GetPage(self.nb.GetSelection())
# notice that it is the panel that you created in new_panel
print page.identifierTag
</code></pre>
|
Starting external process from ASP.NET <p>I need to start an external process from my web application. This means using <em>System.Diagnostics.ProcessStartInfo</em> to call out and execute a console app (exe). But I then need to somehow <strong><em>make sure nothing went wrong</em></strong> during it's execution <strong>and know when the application completed</strong> its work. </p>
<p><strong>What's the best way to both catch all possible errors and find out when it's completed?</strong></p>
| <p>It's not so hard with the Process class. Though, the prior poster was correct - you need to be concerned about permissions. </p>
<pre><code>private string RunProcess(string cmd)
{
System.Diagnostics.Process p;
p= new System.Diagnostics.Process();
if (cmd== null || cmd=="") {
return "no command given.";
}
string[] args= cmd.Split(new char[]{' '});
if (args== null || args.Length==0 || args[0].Length==0) {
return "no command provided.";
}
p.StartInfo.FileName= args[0];
if (args.Length>1) {
int startPoint= cmd.IndexOf(' ');
string s= cmd.Substring(startPoint, cmd.Length-startPoint);
p.StartInfo.Arguments= s;
}
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
// must have the readToEnd BEFORE the WaitForExit(), to avoid a deadlock condition
string output= p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}
</code></pre>
|
Use of return keyword in code block <p>What is the difference between saying:</p>
<pre><code>if (abc == "a")
{
// do something here...
return;
}
</code></pre>
<p>and the same as above, but without the return keyword?</p>
<p>I am a C# coder and I know that the return keyword followed by a type or variable returns that item, but in the above context, return seems to be just to exit the code block but does it make any functional or performance change on the code?</p>
<p>Thanks</p>
| <p>"return" exits from the <em>function</em>, not just the enclosing code block. So if your code block was in the context of a function, like so (I don't know C# so I'm using Java syntax):</p>
<pre><code>int thisIsAFunction(int a) {
if (abc == "a")
{
// do something here...
return 1;
}
// do something else here...
}
</code></pre>
<p>if <code>abc == "a"</code> then the "do something else here" will not run. But if you removed the return statement inside the <code>if</code> block, then it would run.</p>
|
I need platform-independent version of CharToOem. Does Boost have any? <p>I need to convert string to support multi-language messaging in my client-server app.<br>
Can I find it in boost? </p>
| <p>For platform-independent codepage conversions you can use <a href="http://www.gnu.org/software/libiconv/" rel="nofollow">libiconv</a> library.
Anyway, why bother using codepages at all? Use unicode.</p>
|
What is the best way to expose a WCF service so that it can be easily consumed from Java/CXF? <p>We've written a WCF service to be used by a Java shop, who is using CXF to generate the adapters. We're not that familiar with Java, but have exposed the service using basicHttpBinding, SSL, and basic authentication. Integration tests show that a .NET client can consume the service just fine. However, the Java shop is having trouble consuming the service. Specifically, they getthe following JAXB error: Two declarations cause a collision in the ObjectFactory class. This is usually caused if 2 operations have the same name and namespace when CXF attempts to create adapter classes. </p>
<p>We can't find any type or operation names that should cause any sort of collision. We have made sure that all custom types specify a namespace, and tempuri.org is not specified anywhere in the WSDL. The Java shop suspects the error is because the generated WSDL contains <xsd:import elements. </p>
<p>So, my questions: </p>
<ul>
<li>Is there any better way than CXF for the Java shop consume the WCF service? Project Tango looks interesting, but I don't know enough to tell them to consider using it. Is CXF a defacto standard in Java?</li>
<li>BasicHttpBinding/SSL/Basic Auth are MS recommended for interop scenarios, but the client still seems to have interop problems. Should we consider other bindings or settings to make this easier to consume?</li>
<li>Is there a way to configure WCF to always output a single WDSL with no schema imports?</li>
</ul>
| <p>The "Two declarations cause a collision in the ObjectFactory class" error message usually has nothing to do with imports. That's a JAXB error message that is usually caused by having multiple elements or similar that cause the generated field names to be the same. For example, if you have elements like:</p>
<p><element name="Foo" .../>
and
<element name="foo" .../></p>
<p>That can cause that error. Another is using thing like hyphens and underscores and such that are usually eliminated+capped:
<element name="doFoo" .../>
and
<element name="do_foo" .../></p>
<p>With 2.1.4, you can TRY running the wsdl2java with the -autoNameResolution flag. That SOMETIMES helps with this, but not always. Unfortunately, the information that JAXB gives in these cases is nearly worthless and lots of times it's just trial and error to find the conflicting types. :-(</p>
|
indexes in mysql SELECT AS or using Views <p>I'm in over my head with a big mysql query (mysql 5.0), and i'm hoping somebody here can help. </p>
<p>Earlier I asked how to get distinct values from a joined query
<a href="http://stackoverflow.com/questions/508707/mysql-count-only-for-distinct-values-in-joined-query">http://stackoverflow.com/questions/508707/mysql-count-only-for-distinct-values-in-joined-query</a></p>
<p>The response I got worked (using a subquery with join as)</p>
<pre>
select *
from media m
inner join
( select uid
from users_tbl
limit 0,30) map
on map.uid = m.uid
inner join users_tbl u
on u.uid = m.uid
</pre>
<p>unfortunately, my query has grown more unruly, and though I have it running, joining into a derived table is taking too long because there is no indexes available to the derived query. </p>
<p>my query now looks like this</p>
<pre>
SELECT mdate.bid, mdate.fid, mdate.date, mdate.time, mdate.title, mdate.name,
mdate.address, mdate.rank, mdate.city, mdate.state, mdate.lat, mdate.`long`,
ext.link,
ext.source, ext.pre, meta, mdate.img
FROM ext
RIGHT OUTER JOIN (
SELECT media.bid,
media.date, media.time, media.title, users.name, users.img, users.rank, media.address,
media.city, media.state, media.lat, media.`long`,
GROUP_CONCAT(tags.tagname SEPARATOR ' | ') AS meta
FROM media
JOIN users ON media.bid = users.bid
LEFT JOIN tags ON users.bid=tags.bid
WHERE `long` BETWEEN -122.52224684058 AND -121.79760915942
AND lat BETWEEN 37.07500915942 AND 37.79964684058
AND date = '2009-02-23'
GROUP BY media.bid, media.date
ORDER BY media.date, users.rank DESC
LIMIT 0, 30
) mdate ON (mdate.bid = ext.bid AND mdate.date = ext.date)
</pre>
<p>phew!</p>
<p>SO, as you can see, if I understand my problem correctly, i have two derivative tables without indexes (and i don't deny that I may have screwed up the Join statements somehow, but I kept messing with different types, is this ended up giving me the result I wanted). </p>
<p>What's the best way to create a query similar to this which will allow me to take advantage of the indexes?
Dare I say, I actually have one more table to add into the mix at a later date. </p>
<p>Currently, my query is taking .8 seconds to complete, but I'm sure if I could take advantage of the indexes, this could be significantly faster. </p>
| <p>Starting fresh:</p>
<p>Question - why are you grouping by both media.bid and media.date? Can a bid have records for more than one date?</p>
<p>Here's a simpler version to try:</p>
<blockquote>
<pre><code>SELECT
mdate.bid,
mdate.fid,
mdate.date,
mdate.time,
mdate.title,
mdate.name,
mdate.address,
mdate.rank,
mdate.city,
mdate.state,
mdate.lat,
mdate.`long`,
ext.link,
ext.source,
ext.pre,
meta,
mdate.img,
( SELECT GROUP_CONCAT(tags.tagname SEPARATOR ' | ')
FROM tags
WHERE ext.bid = tags.bid
ORDER BY tags.bid GROUP BY tags.bid
) AS meta
FROM
ext
LEFT JOIN
media ON ext.bid = media.bid AND ext.date = media.date
JOIN
users ON ext.bid = users.bid
WHERE
`long` BETWEEN -122.52224684058 AND -121.79760915942
AND lat BETWEEN 37.07500915942 AND 37.79964684058
AND ext.date = '2009-02-23'
AND users.userid IN
(
SELECT userid FROM users ORDER BY rank DESC LIMIT 30
)
ORDER BY
media.date,
users.rank DESC
LIMIT 0, 30
</code></pre>
</blockquote>
|
Vi substitution command <p>Using vi, how do I substitute the current line number somewhere into the current line? For example, if the cursor is on line 10, I would like to put the number 10 somewhere on that line.</p>
| <p>You want to physically insert the line number, not just display it in the margin? If so -</p>
<pre><code>:s/$/\=line(".")/
</code></pre>
<p>This will append it the the end of the line. Replace $ with ^ to prepend to the line.</p>
|
How to Prevent SQL Injection in Oracle SQLPlus? <p>Obviously if I am using JDBC/ODBC, I can use bind variables and prepared statements to prevent SQL injection. However, when data is passed to batch processes that end up invoking Oracle SQLPlus, is there a way to prevent SQL injection? For example:</p>
<p>query.sql:</p>
<pre><code>select '&1' from dual;
exit;
</code></pre>
<p>If I call this script from SQLPlus thusly:</p>
<pre><code>$ sqlplus SCOTT/TIGER @query.sql "x','y"
</code></pre>
<p>I will get the following output:</p>
<pre><code>old 1: select '&1' from dual
new 1: select 'x','y' from dual
' '
- -
x y
</code></pre>
<p>As you can see, SQLPlus command line parameters are using simple macro substitution. Is there an alternative method that I am missing? Otherwise, how do I prevent this from being exploitable?</p>
| <p>If people have sql*plus access to your database and you have the user id and password of a privileged user out here in a script for them to read, then you've just dropped your pants to them anyway. SQL injection is the least of your worries.</p>
|
Plesk alternative for windows <p>I'm searching for a free alternative to Plesk for my windows server 2003. Anybody knows an alternative.</p>
| <p>As far as I know there aren't any. Plesk bought Helm it's only major competitor in the Windows space. The only "ok" free panel I know is ISPConfig but it's only for Linux.</p>
<p>Our company is also searching for an alternative to Plesk, for Windows hosting.</p>
<p>Edit 25 Oct 2010: DotNetPanel renamed to WebsitePanel appears to be open source:
<a href="http://sourceforge.net/projects/websitepanel/" rel="nofollow">http://sourceforge.net/projects/websitepanel/</a></p>
|
formatting long numbers as strings in python <p>What is an easy way in Python to format integers into strings representing thousands with K, and millions with M, and leaving just couple digits after comma?</p>
<p>I'd like to show 7436313 as 7.44M, and 2345 as 2,34K.</p>
<p>Is there some % string formatting operator available for that? Or that could be done only by actually dividing by 1000 in a loop and constructing result string step by step?</p>
| <p>I don't think there's a built-in function that does that. You'll have to roll your own, e.g.:</p>
<pre><code>def human_format(num):
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
# add more suffixes if you need them
return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
print('the answer is %s' % human_format(7436313)) # prints 'the answer is 7.44M'
</code></pre>
|
How do you see the client-side URL in ColdFusion? <p>Let's say, on a ColdFusion site, that the user has navigated to
<a href="http://www.example.com/sub1/" rel="nofollow">http://www.example.com/sub1/</a></p>
<p>The server-side code typically used to tell you what URL the user is at, looks like:
<a href="http://#cgi.server_name##cgi.script_name#?#cgi.query_string#" rel="nofollow">http://#cgi.server_name##cgi.script_name#?#cgi.query_string#</a></p>
<p>however, "cgi.script_name" automatically includes the default cfm file for that folder- eg, that code, when parsed and expanded, is going to show us "http://www.example.com/sub1/index.cfm"</p>
<p>So, whether the user is visiting sub1/index.cfm or sub1/, the "cgi.script_name" var is going to include that "index.cfm".</p>
<p>The question is, how does one figure out which URL the user actually visited? This question is mostly for SEO-purposes- It's often preferable to 301 redirect "/index.cfm" to "/" to make sure there's only one URL for any piece of content- Since this is mostly for the benefit of spiders, javascript isn't an appropriate solution in this case. Also, assume one does not have access to isapi_rewrite or mod_rewrite- The question is how to achieve this within ColdFusion, specifically.</p>
| <p>I suppose this won't be possible. </p>
<p>If the client requests "GET /", it will be translated by the web server to "GET /{whatever-default-file-exists-fist}" before ColdFusion even gets invoked. (This is necessary for the web server to know that ColdFusion has to be invoked in the first place!)</p>
<p>From ColdFusion's (or any application server's) perspective, the client requested "GET /index.cfm", and that's what you see in <code>#CGI#</code>.</p>
<p>As you've pointed out yourself, it would be possible to make a distinction by using a URL-rewriting tool. Since you specifically excluded that path, I can only say that you're out of luck here.</p>
|
HOW? Controller return nothing/current view <p>SHORT:<br>
How do I make a controller return the current view or just simply do nothing?</p>
<p>LONG:<br>
I have a partial view where i've created an imageslider.
It contains a link which sends a request to a controller to get the next image (using ajax).
The controller fetches the next image, stores it in ViewData and sends back a partial view (the one above).
<br><br>
Now, what I do today is that when the controller reaches the last image it re-return the very same image (by refetching it), but still creates a new view, that is, the client/browser re-parses the "same" data.
<br>
This seems somewhat non-optimal.<br><br>
What I'd like to do is that when controller reaches the last image it should simply do nothing.<br>
If I return null then the view is updated with empty contents.<br>
I want the view/client/browser to retain whatever it has and the controller to simply do nothing.</p>
<pre><code> [AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetNextImage(...)
{
if(Request.IsAjaxRequest())
{
if(CURRENT_IMAGE != LAST_IMAGE)
{
Image image = GetNextImage(...);
var partialViewResult = new PartialViewResult();
partialViewResult.ViewName = "ImageSlide";
partialViewResult.ViewData.Model = image;
return partialViewResult;
}
else
{
// DO NOTHING, HOW?
}
}
return RedirectToAction("Error", "Home");
}
</code></pre>
| <p>You can return an EmptyResult if you want it to do nothing...</p>
<pre><code>return new EmptyResult();
</code></pre>
<p>If you're using the AjaxHelper you can avoid the update by supplying an unsuccessful status code (e.g. 404 or whatever is most appropriate), that'll stop it replacing your div as the javascript in MicrosoftMvcAjax.js explicitly checks for a successful response before updating any elements:-</p>
<pre><code>this.ControllerContext.HttpContext.Response.StatusCode = 404;
return new EmptyResult();
</code></pre>
<p>Ultimately the best way to avoid it is to design the partial view so it avoids the problem in the first place (like you mention yourself).</p>
|
Load Testing with AB ... fake failed requests (length) <p>To do some load testing, for my own curiosity, on my server I ran:</p>
<pre><code>ab -kc 50 -t 200 http://localhost/index.php
</code></pre>
<p>This opens up 50 keep-alive connections for 200 seconds and just slams my server with requests for index.php</p>
<p>In my results, I get:</p>
<pre><code>Concurrency Level: 50
Time taken for tests: 200.007 seconds
Complete requests: 33106
Failed requests: 32951
(Connect: 0, Receive: 0, Length: 32951, Exceptions: 0)
Write errors: 0
Keep-Alive requests: 0
Total transferred: 1948268960 bytes
HTML transferred: 1938001392 bytes
Requests per second: 165.52 [#/sec] (mean)
Time per request: 302.071 [ms] (mean)
Time per request: 6.041 [ms] (mean, across all concurrent requests)
Transfer rate: 9512.69 [Kbytes/sec] received
</code></pre>
<p>Note the 32951 "failed" requests. I cannot figure this out.</p>
<p>As the test was running, I was able to access my web site from my home computer perfectly, albeit page load times at the bottom of the page were reported as .5 instead of the usual .02. However I never once had a failed request.</p>
<p>So why is AB reporting that half of the connections fail? And what does "Length: " mean in that context?</p>
<p>Thanks</p>
| <p>Nevermind. The "length failure" merely indicates that about half the time the length of the response was different.</p>
<p>Since the contents are dynamic, it's probably the session identifier or something like that.</p>
|
Loading/Using Resource Dictionaries from a WinForms hosted WPF control <p>I have a Windows Forms application that needs to host a WPF control at runtime. I have the basic hosting and interaction complete (using an ElementHost control) and everything works fine until I try to do something that requires the WPF control to make use of some custom resource dictionaries that are defined. (The WPF control and all of it's resource dictionaries are all defined in the same WPF Control Library DLL.)</p>
<p>As soon as that happens, I get a bunch of errors that look like this:</p>
<pre><code>System.Windows.ResourceDictionary Warning: 9 : Resource not found; ResourceKey='DocumentHeaderInterestStyle'
</code></pre>
<p>I have found one <a href="http://www.drwpf.com/blog/Home/tabid/36/EntryID/10/Default.aspx" rel="nofollow">reference</a> (<strong>link appears dead due to archiving</strong>, <a href="http://drwpf.com/blog/2007/10/05/managing-application-resources-when-wpf-is-hosted/" rel="nofollow">this</a> <em>might</em> be the same article that was originally referenced). that talks about this, but it seems like the article is approaching things more from the WPF side, but I don't really want to have to make changes to the WPF control as everything works in a stand-alone WPF application.</p>
<p>If the only way to accomplish this is to make changes on the WPF side, I can get those changes made (I'm not responsible for the WPF control library but the person that is also works for the same company so it's not a problem other than getting his time to make the changes.) but I'm hoping for something I can do on the WinForms side to get this working.</p>
<p>The WPF control library has a resource dictionary file named "Default.xaml" defined in the project with the following properties:</p>
<p>Build Action: Page
Copy to Output Directory: Do not copy
Custom Tool: MSBuild:Compile</p>
<p>The stand-alone WPF application has the following entry in it's App.xaml file:</p>
<pre><code> <ResourceDictionary x:Uid="ResourceDictionary_1">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary x:Uid="ResourceDictionary_2" Source="/SmartClient.Infrastructure;component/Themes\Default.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</code></pre>
<p>It seems like the control library should already know how to get its resources. Using the Resources.MergedDictionaries.Add() seems like it should work, but where do I get the instance of the existing dictionary?</p>
| <p>Assuming you know what resources you need (sounds like you do), you should just be able to "inject" them yourself. Something like:</p>
<pre><code>var wpfControl = new ...;
wpfControl.Resources.Add(...);
elementHost.Child = wpfControl;
</code></pre>
<p>In your question you mention that there are existing resource dictionaries in the control library. If so, you can just do this:</p>
<pre><code>var wpfControl = new ...;
wpfControl.Resources.MergedDictionaries.Add(/* instance of existing dictionary */);
elementHost.Child = wpfControl;
</code></pre>
|
How to put the content of a ByteBuffer into an OutputStream? <p>I need to put the contents of a <code>java.nio.ByteBuffer</code> into an <code>java.io.OutputStream</code>. (wish I had a <code>Channel</code> instead but I don't) What's the best way to do this?</p>
<p>I can't use the ByteBuffer's <code>array()</code> method since it can be a read-only buffer.</p>
<p>I also may be interspersing writes to the OutputStream between using this ByteBuffer and having a regular array of <code>byte[]</code> which I can with use <code>OutputStream.write()</code> directly.</p>
| <p>Look at <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/channels/Channels.html#newChannel%28java.io.OutputStream%29">Channels.newChannel(OutputStream)</a>. It will give you a channel given an OutputStream. With the WritableByteChannel adapter you can provide the ByteBuffer which will write it to the OutputStream.</p>
<pre><code>public void writeBuffer(ByteBuffer buffer, OutputStream stream) {
WritableByteChannel channel = Channels.newChannel(stream);
channel.write(buffer);
}
</code></pre>
<p>This should do the trick!</p>
|
HTTPS causes Joomla to revert back to old Domain when creating links <p>I have moved the website BradPPresents.com to BradP.com. <strong>URLS ARE NOT SAFE FOR WORK</strong></p>
<p>The website links properly on HTTP but as soon as it uses HTTPS the links revert back to BradPPresents.com. </p>
<p>I assumed this was a Joomla! configuration.php file but it has already been changed to BradP.com. </p>
<p>Also, all instances that I can find of BradPPresents.com have been changed to BradP.com in the MySQL database.</p>
<p>Does anyone have any ideas?
Much appreciated,
Nick</p>
| <p>To others: Before your curiosity gets the best of you and you decide to check this guy's site, please be aware that may be not suitable for work at some places. Update: I don't have privilege to edit the URLs statement that was added to the question, so I'll just update here: The site is not an adult site in the classic sense, but one of those on how to get girls. Still, some of the pix on the front page are a bit racy, so if you're at work, I still recommend staying away.</p>
<p>Check your server software's configuration. It may be pointing port 443 (https) to a different default directory than port 80 (http). If so, you'll need to change the default directory for port 443 to match that of port 80.</p>
<p>If you're using Apache, I expect there are files named httpd.conf and ssl.conf somewhere, possibly in separate directories. (Most likely these directories will be at the same level or one will be a sub-directory of the other. Possible starting points are /etc/httpd/ and /usr/local/apache2/. These directories are usually named conf and conf.d.) Both files probably have entries for DocumentRoot (although the one in ssl.conf may be commented out with a "#"). If neither is commented out and they don't match, change the one in ssl.conf. See the <a href="http://httpd.apache.org" rel="nofollow">Apache</a> web site for more detail.</p>
<p>I've only used Apache, so I can't help with other servers.</p>
<p>And you probably know this, but I should mention it for completeness: Don't forget to make back up copies of your existing configuration files before you edit them! That way, if your changes don't work, you can go back to what you have.</p>
<p>Edit: I missed that this was Joomla, which I've never used. So, I'm not sure if this will be useful or not.</p>
|
Wrapping objects to extend/add functionality while working around isinstance <p>In Python, I've seen the recommendation to use holding or wrapping to extend the functionality of an object or class, rather than inheritance. In particular, I think that Alex Martelli spoke about this in his <a href="http://www.lecturefox.com/blog/python-design-patterns-by-alex-martelli" rel="nofollow">Python Design Patterns</a> talk. I've seen this pattern used in libraries for dependency injection, like <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>.</p>
<p>One problem that I've run into is that when I have to interface with code that uses the
<a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577848#577848">isinstance anti-pattern</a>, this pattern fails because the holding/wrapping object fails the <code>isinstance</code> test. How can I set up the holding/wrapping object to get around unnecessary type checking? Can this be done generically? In some sense, I need something for class instances analogous to signature-preserving function decorators (e.g., <a href="http://wiki.python.org/moin/PythonDecoratorLibrary" rel="nofollow">simple_decorator</a> or Michele Simionato's <a href="http://pypi.python.org/pypi/decorator" rel="nofollow">decorator</a>).</p>
<p>A qualification: I'm not asserting that all <code>isinstance</code> usage is inappropriate; several answers make good points about this. That said, it should be recognized that <code>isinstance</code> usage poses significant limitations on object interactions---it forces <em>inheritance</em> to be the source of polymorphism, rather than <em>behavior</em>.</p>
<p>There seems to be some confusion about exactly how/why this is a problem, so let me provide a simple example (broadly lifted from <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>). Let's say we have a class Foo, as well as a FooFactory. For the sake of the example, assume we want to be able to instantiate Foo objects that log every function call, or don't---think AOP. Further, we want to do this without modifying the Foo class/source in any way (e.g., we may actually be implementing a generic factory that can add logging ability to any class instance on the fly). A first stab at this might be:</p>
<pre><code>class Foo(object):
def bar():
print 'We\'re out of Red Leicester.'
class LogWrapped(object):
def __init__(self, wrapped):
self.wrapped = wrapped
def __getattr__(self, name):
attr = getattr(self.wrapped, name)
if not callable(attr):
return attr
else:
def fun(*args, **kwargs):
print 'Calling ', name
attr(*args, **kwargs)
print 'Called ', name
return fun
class FooFactory(object):
def get_foo(with_logging = False):
if not with_logging:
return Foo()
else:
return LogWrapped(Foo())
foo_fact = FooFactory()
my_foo = foo_fact.get_foo(True)
isinstance(my_foo, Foo) # False!
</code></pre>
<p>There are may reasons why you might want to do things exactly this way (use decorators instead, etc.) but keep in mind:</p>
<ul>
<li>We don't want to touch the Foo class. Assume we're writing framework code that could be used by clients we don't know about yet.</li>
<li>The point is to return an object that is essentially a Foo, but with added functionality. It should appear to be a Foo---as much as possible---to any other client code expecting a Foo. Hence the desire to work around <code>isinstance</code>.</li>
<li>Yes, I know that I don't need the factory class (preemptively defending myself here). </li>
</ul>
| <p>If the library code you depend on uses <code>isinstance</code> and relies on inheritance why not follow this route? If you cannot change the library then it is probably best to stay consistend with it.</p>
<p>I also think that there are legitimate uses for <code>isinstance</code>, and with the introduction of <a href="http://www.python.org/dev/peps/pep-3119/" rel="nofollow">abstract base classes</a> in 2.6 this has been officially acknowledged. There are situations where <code>isinstance</code> really is the right solution, as opposed to duck typing with <code>hasattr</code> or using exceptions.</p>
<p>Some dirty options if for some reason you really don't want to use inheritance:</p>
<ul>
<li>You could modify only the class instances by using instance methods. With <code>new.instancemethod</code> you create the wrapper methods for your instance, which then calls the original method defined in the original class. This seems to be the only option which neither modifies the original class nor defines new classes.</li>
</ul>
<p>If you can modify the class at runtime there are many options:</p>
<ul>
<li><p>Use a runtime mixin, i.e. just add a class to the <code>__base__</code> attribute of your class. But this is more used for adding specific functionality, not for indiscriminate wrapping where you don't know what need to be wrapped.</p></li>
<li><p>The options in Dave's answer (class decorators in Python >= 2.6 or Metaclasses).</p></li>
</ul>
<p>Edit: For your specific example I guess only the first option works. But I would still consider the alternative of creating a <code>LogFoo</code> or chosing an altogether different solution for something specific like logging.</p>
|
Where can I find some websites with VB.NET tutorials? <p>I am looking for a website similar to W3Schools that teaches the basics for VB.NET 2008.</p>
<p>If none exist I would just like some good tutorials to get me started. I did some basic VB.NET a couple of years ago but I need to refresh myself, any ideas? </p>
| <p>You can find visual basic tutorials in MSDN: go to the <a href="http://msdn.microsoft.com/en-gb/vbasic/default.aspx" rel="nofollow">Visual Basic Developer Center</a> for a start.</p>
|
How can I enforce a constraint only if a column is not null in Postgresql? <p>I would like a solution to enforce a constraint only if a column is not null. I can't seem to find a way to do this in the documentation.</p>
<pre><code>create table mytable(
table_identifier_a INTEGER,
table_identifier_b INTEGER,
table_value1,...)
</code></pre>
<p>Do to the nature of the data, I will have identifier b and a value when the table is created. After we receive additional data, I will be able to populate identifier a. At this point I would like to ensure a <code>unique key of (identifier_a, value1)</code> but only if identifier_a exists.</p>
<p>Hopefully that makes sense, Any one have any ideas?</p>
| <p>Ummm. Unique constraints don't prevent multiple NULL values.</p>
<pre><code>CREATE TABLE mytable (
table_identifier_a INTEGER NULL,
table_identifier_b INTEGER NOT NULL,
table_value1 INTEGER NOT NULL,
UNIQUE(table_identifier_a, table_identifier_b)
);
</code></pre>
<p>Note that we can insert muliple NULLs into it, even when identifier_b
matches:</p>
<pre><code>test=# INSERT INTO mytable values(NULL, 1, 2);
INSERT 0 1
test=# INSERT INTO mytable values(NULL, 1, 2);
INSERT 0 1
test=# select * from mytable;
table_identifier_a | table_identifier_b | table_value1
--------------------+--------------------+--------------
| 1 | 2
| 1 | 2
(2 rows)
</code></pre>
<p>But we can't create duplicate (a,b) pairs:</p>
<pre><code>test=# update mytable set table_identifier_a = 3;
ERROR: duplicate key value violates unique constraint "mytable_table_identifier_a_key"
</code></pre>
<p>Of course, you do have an issue: Your table has no primary key. You
probably have a data model problem. But you didn't provide enough
details to fix that.</p>
|
Suggestions for automating web application (work flow not testing) <p>A customer has a legacy web application which is used mainly to capture information. The application has no other interfaces available e.g. web services, APIâs. </p>
<p>Typical workflow:</p>
<ul>
<li>First form: Select âAction Typeâ of âPaymentâ via radio button. Select âEnterâ</li>
<li>Second form: Select âPayment Typeâ of âFineâ via radio button. Select âEnterâ</li>
<li>Third form: Select âFine Typeâ of âParkingâ via radio button. Select âEnterâ.</li>
<li>Fourth form: Enter parking fine number. Select âEnterâ.</li>
</ul>
<p>Back end system looks up the amount for this parking fine number.</p>
<ul>
<li>Fifth form: Display summary of details. Select âEnterâ. Pop-up âConfirm you wish to pay fine amount of xx.xx via credit cardâ. Select âOKâ.</li>
<li>Sixth form: Enter credit card details. Select âEnterâ.</li>
<li>Seventh form: Confirmation.</li>
</ul>
<p>For various reasons, the customer wants to provide these details via a file. So we would read a record and plug-in the details into the relevant fields as above.</p>
<p>We could capture a work flow via something like Selenium but we would need someway of modifying the âscriptsâ since the details are different for each record in the file.</p>
<p>We could perhaps send a series of HTTP Posts?</p>
<p>The solution must run in all browsers and the customer doesnât want to have to install plug-ins etc, on all user PCâs.</p>
<p>No restriction of how to deliver this e.g. we could use Java, C# (preferred) or anything else.</p>
<p>Any suggestions or advice from anyone who has done something like this?</p>
| <p>You will want to do this <em>without</em> a browser, using HTTP POST requests. <strong>A scripting language such as Perl, Python etc. would be a good choice</strong> in terms of simplicity - in this case the actual code would probably take no more than 30-so lines.</p>
<p>You would essentially have to:</p>
<ol>
<li>potentially issue one initial (setup) POST (username+password) to simulate a human agent logging in</li>
</ol>
<p>then,</p>
<ol>
<li>read a set of parameters from the input file</li>
<li>issue a first POST with the first form's subset of parameters (e.g. action type)</li>
<li>read applicable <code><input type="hidden" name="..." value="..."></code> tags from the POST reply, if any</li>
<li>issue a second POST with the second form's subset of parameters (e.g. payment type), as well as any <code>name=value</code> pairs read from the POST reply in the step immediately above</li>
<li>read applicable <code><input type="hidden" name="..." value="..."></code> tags from the POST reply, if any</li>
<li>issue a third POST with the third form's subset of parameters (e.g. fine type), as well as any <code>name=value</code> pairs read from the POST reply in the step immediately above</li>
<li>etc.</li>
<li>repeat for the next set of parameters from your input file</li>
</ol>
<p>You may also have to instruct your HTTP library not to throw cookies away, if not configured as such by default/already.</p>
|
Python ORM that auto-generates/updates tables and uses SQLite? <p>I am doing some prototyping for a new desktop app i am writing in Python, and i want to use SQLite and an ORM to store data.</p>
<p>My question is, are there any ORM libraries that support auto-generating/updating the database schema and work with SQLite?</p>
| <p><a href="http://www.sqlalchemy.org/">SQLAlchemy</a> is a great choice in the Python ORM space that supports SQLite.</p>
|
Why is $Id$ sometimes not expanded in SVN? <p>I'm working on a project in which we're actively using the <code>$Id$</code> string generated by subversion to write the version number in the documentation. For example, we parse this string</p>
<pre><code>$Id: filename 999 2009-02-23 22:51:29Z author $
</code></pre>
<p>and print "999" in the documentation titlepage.</p>
<p>But every now and then, after a commit, the information is removed and we're left with just</p>
<pre><code>$Id$
</code></pre>
<p>This obviously breaks things a little. Does anyone know why it might be happening?</p>
<p><hr /></p>
<p>Okay, the obvious answer was correct; <code>svn:keywords</code> weren't set for that file any more. But I swear they used to be! Any idea how/why <code>svn:keywords</code> would have been cleared from a file without anyone noticing/doing anything on purpose?</p>
| <p>The svn:keywords property may not be properly set on that file. You need to set it to (at least) 'Id':</p>
<pre><code>svn ps svn:keywords 'Id' filename.txt
</code></pre>
|
Cannot get Adobe AIR's ApplicationUpdaterUI() to work <p>Here is my problem - I'm trying to write a self-updating application, but I keep getting an error saying that runtime.air.update.ApplicationUpdaterUI() does not return a constructor.</p>
<p>Here's the relevant section of the code; there are other javascript files being included, but I don't think that any of them would be actively breaking AIR itself.</p>
<pre><code><html>
<head>
<script type="text/javascript" src="./js/AIRAliases.js"></script>
<script type="text/javascript" src="./js/jquery-1.3.1.js"></script>
<script src="ApplicationUpdater_UI.swf" type="application/x-shockwave-flash"></script>
<script>
$(document).ready( function() {
var appUpdater = new runtime.air.update.ApplicationUpdaterUI(); // line 64 in this example
}
</script>
</head>
<body> ... stuff ... </body>
</html>
</code></pre>
<p>And the error that I get when I test it is</p>
<pre>
TypeError: Value is not a constructor. Cannot be used with new.
at app:/index3.html : 64
at app:/js/jquery-1.3.1.js : 2912
at app:/js/jquery-1.3.1.js : 686
at app:/js/jquery-1.3.1.js : 2916
at app:/js/jquery-1.3.1.js : 2936
</pre>
| <p>Verify the path in that script tag for the SWF, I'm guessing you do not have the reference to the ApplicationUpdater_UI.swf correct. </p>
<p>Air is basically complaining that it cannot find a runtime.air.update.ApplicationUpdaterUI() method to call anywhere, which likely means it can't find the SWF (or I suppose it's possible the SWF is corrupted).</p>
|
Performance problems on iPhone using simple graphics <p>We're working on a couple simple games and we have some performance problems that we keep running into, and I was curious if it was a code issue or a "we're using the wrong objects" issue.</p>
<p>Our games are basically simple ones that work as follows:</p>
<p>We have a custom view that we load, and a custom object that is our game engine. The view has a timer that fires like such:</p>
<pre><code>[NSTimer scheduledTimerWithTimeInterval:1.0 / 30.0 target:self selector:@selector(animationTimerMethod) userinfo:nil repeats:YES];
</code></pre>
<p>and in our timer method, we have the following:</p>
<pre><code>- (void)animationTimerMethod:(NSTimer*)timer
{
if([gameEngine doGameLoop]) //only redraw if we need to
[self setNeedsDisplay];
}
</code></pre>
<p>Our drawing code is very simple, we're just drawing a couple of images on the screen, using code similar to the following:</p>
<pre><code>- (void)drawRect:(CGRect)rect
{
CGGraphicsContext ctx = UIGraphicsGetCurrentContext();
CGContextDrawImage(ctx, someRect, someImage);
}
</code></pre>
<p>The main problem we have is responsiveness to touch. Our code will not get a response in the touchesBegan method many times. Is this just a limitation of the Core Graphics library? Should we be using OpenGL? Are there other ways to do simple animations (not even objects moving on screen, just 6 or so frames of animation for an object in the same place) that would be more responsive?</p>
<p>Thanks so much!</p>
| <p>There are definitely ways to speed this up. Manually redrawing the images every frame means you are redrawing textures you could be reusing. You could reuse them either by moving to OpenGL, or moving the images into a CALayer and then just repositioning the layer instead of redrawing the image.</p>
<p>If you do not want to move to OpenGL you would probably also see a significant performance win by moving to CAAnimation instead of having your code calculate each frame, but that might require significant changes to your engine.</p>
<p>Also, if you can avoid avoid alpha compositing it is a big speed up.</p>
|
svn access to a https repository: username / password always being prompted for <p>I just moved my svn repository to a new server.
Previously I was accessing my repository via <em>svn://oldserver/yyy/zzz</em>
Now I want to access it via <em>https://newserver:8443/svn/yyy/zzz</em></p>
<p>I used <strong>switch --relocate</strong> to repoint my source tree and this seemed to work well.</p>
<p>When I try to update the source I use:</p>
<p><strong>svn.exe update zzz --username myusername --password mypassword --non-interactive</strong></p>
<p>When I do it still asks me for the username and password (which if I re-enter works OK).</p>
<p>No matter what I do I can't get it to accept the username and password parameters.</p>
<p>Can anyone please help me out here?</p>
<p>Thanks in advance for your help.</p>
<p>Mark</p>
| <p>I'm not really a SVN god, but I assume you got the checkout working? What happens if you just type</p>
<pre><code>svn.exe update zzz
</code></pre>
<p>in the root directory of your project?</p>
|
Can Firebug set breakpoints in external JavaScript files? <p>Is there any way in <a href="http://www.getfirebug.com/" rel="nofollow">Firebug</a> to set a breakpoint in an external .js file that a page links to so that it can be stepped through?</p>
<p>(I suspect I've found a bug in jQuery and I want to be able to step through jQuery as it's handling events to see what it's doing.)</p>
| <p>Not sure if I understand the question, but I don't think Firebug treats external javascript any differently than internal one. Just go to the "script" tab, select the .js file in the drop down list and set your breakpoint.</p>
|
Skipping certain files/classes when using asdoc <p>For some reasons, <strong>asdoc</strong> seems to be only good at 'excluding' classes but not 'skipping', which means all the files will always be walked through and examine for errors.</p>
<p>Is there a way to make <strong>asdoc</strong> really 'skip' some certain files? So it can bypass some already known problematic files and still generate the necessary docs gracefully.</p>
<p>Thanks.</p>
| <p>We haven't found a way of having asdoc <em>skip</em> files, but we have got it working by only providing a whitelist of what files we do want parsed. You could easily write a script that would find all the *.as files and compare them to a 'deny' list and pass those all into asdoc.</p>
<p>Newer versions of asdoc support exclude-sources - see <a href="http://bugs.adobe.com/jira/browse/SDK-16545?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel" rel="nofollow">here</a>. More <a href="http://www.adobeforums.com/webx/.59b703a1" rel="nofollow">here</a>.</p>
|
"Good" Database Record Comparison tool? <p>I am a system administrator for a company that supports a CRM CMS (Salesforce).</p>
<p>I don't like the built-in functionality so I generally manage data through CSV/XLS files for uploading and downloading, because I can write better queries and the like. One of my tasks is uploading Contacts and Accounts. Because of a lack of unique Identifiers and misspellings, I'm encountering duplicates in uploaded records.</p>
<ul>
<li>When uploading contacts, I try to match by email, phone number and/or lastname/firstname</li>
<li>With companies I am generally limited to just the name of the account, with numerous possible abbreviations and misspellings</li>
</ul>
<p>I'm looking for a better method to check for duplicates with the following constraints:</p>
<blockquote>
<p>Given a list of names, emails or phone numbers (all stored as text fields), do a comparison check between two tables looking for the best match out of the second table. Preferably between multiple fields, but even if it's just one, it will greatly assist my endeavor.</p>
</blockquote>
<p>The size of the dataset is about 17,000 records on the longest table. Values are generally entered about 50 at a time. My limitations are the hardware I have and no budgetary discretion. My programming ability is pretty basic, but I can learn and have Eclipse & Visual Studio on the system. </p>
<p>Does anyone have a suggestion as how I can either solve this problem programmatically, or with a third party tool?</p>
| <p>The two db comparison tools I have used are xSQL and Redgate SQL Compare.</p>
<p>I prefer redgate for its ease of use but it is pretty pricey. </p>
<p>xSQL is a little complicated to get the hang of at first but is quite powerful, it also does a much better job of scripting schema and data than SQL server does. its also a lot cheaper.</p>
<p>Actually looking at your question a little closer it seems that you want a bit of intelligence in your comparisons, it that case since you have Visual Studio installed already I would say you have the tools already to do some pretty in depth comparrisons, just need to do a bit of coding.</p>
|
How must I declare the regex for Perl's split? <p>I came across this Perl construct today:</p>
<pre><code>@foo = split("\n", $bar);
</code></pre>
<p>That works well for splitting a large string into an array of lines for UNIX-type line endings, but leaves a trailing \r for Windows. So I changed it to:</p>
<pre><code>@foo = split("\r?\n", $bar);
</code></pre>
<p>Which splits the string by lines and doesn't leave a trailing \r (tested under ActivePerl 5.8). Then it was pointed out to me that this should probably be:</p>
<pre><code>@foo = split(/\r?\n/, $bar);
</code></pre>
<p>So why does the second variant work at all? The double quotes mean that the contents are evaluated, which is why the \r and \n are actually treated as CR and LF, but the ? is treated as a regex metacharacter rather than a literal question mark.</p>
<p>Are the slashes around the regular expression just optional for split()? Is it just assumed that the first parameter to the function will be a regex?</p>
| <p>The slashes are just the standard delimiters for a regular expression (you can use others), and they evaluate special characters and escape sequences just like double quotes.</p>
<p><em>EDIT</em>: I shot too fast, as Manni explained in the comment. I'll try a longer explanation:</p>
<p>Usually, matching regexes in Perl start with m, and the regex body is then enclosed in some delimiter. The standard delimiter for matching regexes is the slash, and you can omit the leading <code>m</code> if you use slashes as delimiter:</p>
<pre><code>m/\r?\n/
m"\r?\n"
m$\r?\n$
/\r?\n/
</code></pre>
<p>These all do the same, and they are called "regex literals". If you use single quotes, escape sequences don't get evaluated.</p>
<p>At this point, it seems strange that your first attempt, with the regex in double quotes but without the leading <code>m</code>, worked at all, but, as <a href="http://stackoverflow.com/questions/580050/how-must-i-declare-regex-for-perls-split/580323#580323">Arnshea</a> explained, <code>split</code> is a special case in that it accepts the regex not only as a literal, but also as a string.</p>
|
Convert Collection to List <p>I am using <code>TreeBidiMap</code> from the <code>Apache Collections</code> library. I want to sort this on the values which are <code>doubles</code>.</p>
<p>My method is to retrieve a <code>Collection</code> of the values using:<br>
<code>Collection coll = themap.values();</code><br>
Which naturally works fine.<br>
<strong>Main Question:</strong> I now want to know how I can convert/cast (not sure which is correct) <code>coll</code> into a <code>List</code> so it can be sorted? </p>
<p>I then intend to iterate over the sorted <code>List</code> object, which should be in order and get the appropriate keys from the <code>TreeBidiMap</code> (<code>themap</code>) using <code>themap.getKey(iterator.next())</code> where the iterator will be over the list of <code>doubles</code>.</p>
| <pre><code>List list = new ArrayList(coll);
Collections.sort(list);
</code></pre>
<p>As Erel Segal Halevi says below, if coll is already a list, you can skip step one. But that would depend on the internals of TreeBidiMap.</p>
<pre><code>List list;
if (coll instanceof List)
list = (List)coll;
else
list = new ArrayList(coll);
</code></pre>
|
Avoiding dynamic_cast/RTTI <p>I was recently working on a piece of C++ code for a side project (the <a href="https://sourceforge.net/projects/cpp-markdown/"><code>cpp-markdown</code> library</a>, for the curious), and ran into a coding question that I'd like some opinions on.</p>
<p><code>cpp-markdown</code> has a base class called <code>Token</code>, which has a number of subclasses. Two of the main subclasses are <code>Container</code> (which holds collections of other <code>Token</code>s) and <code>TextHolder</code> (used as a base class for <code>Token</code>s that contain text, of course).</p>
<p>Most of the processing is handled via virtual functions, but some of it was better handled in a single function. For that, I ended up using <code>dynamic_cast</code> to down-cast the pointer from a <code>Token*</code> to one of its subclasses, so I could call functions that are specific to the subclass and its child classes. There's no chance the casting would fail, because the code is able to tell when such a thing is needed via virtual functions (such as <code>isUnmatchedOpenMarker</code>).</p>
<p>There are two other ways I could see to handle this:</p>
<ol>
<li><p>Create <em>all</em> of the functions that I want to call as virtual functions of <code>Token</code>, and just leave them with an empty body for every subclass except the one(s) that need to handle them, or...</p></li>
<li><p>Create a virtual function in <code>Token</code> that would return the properly-typed pointer to <code>this</code> when it's called on certain subtypes, and a null pointer if called on anything else. Basically an extension of the virtual function system I'm already using there.</p></li>
</ol>
<p>The second method seems better than both the existing one and the first one, to me. But I'd like to know other experienced C++ developers' views on it. Or whether I'm worrying too much about trivialities. :-)</p>
| <p>#1 pollutes the class namespace and vtable for objects that don't need it. Ok when you have a handful of methods that will generally be implemented, but plain ugly when only needed for a single derived class.</p>
<p>#2 is just <code>dynamic_cast<></code> in a polka-dot dress and lipstick. Doesn't make client code any simpler, and tangles up the entire hierarchy, requiring the base and each derived class to be semi-aware of <em>every other</em> derived class.</p>
<p>Just use <code>dynamic_cast<></code>. That's what it's there for.</p>
|
Binary Trees in C <p>I'm trying to insert nodes into a tree in order. My function works fine... when there's only three nodes.</p>
<p>I have this code:</p>
<pre><code>typedef struct _Tnode Tnode;
struct _Tnode {
char* data;
Tnode* left;
Tnode* right;
};
</code></pre>
<p>Along with this:</p>
<pre><code>Tnode* add_tnode(Tnode* current_node, char* value) {
Tnode* ret_value;
if(current_node == NULL) {
current_node = (Tnode*) malloc(sizeof(Tnode));
if(current_node != NULL) {
(current_node)->data = value;
(current_node)->left = NULL;
(current_node)->right = NULL;
ret_value = current_node; }
else
printf("no memory");
}
else {
if(strcmp(current_node->data,value)) { //left for less than
ret_value = add_tnode((current_node->left), value);
current_node -> left = (Tnode*) malloc(sizeof(Tnode));
(current_node -> left) -> data = value;
}
else if(strcmp(current_node->data,value) > 0) {
ret_value = add_tnode((current_node -> right), value);
current_node -> right = (Tnode*) malloc(sizeof(Tnode));
(current_node -> right) -> data = value;
}
else {
printf("duplicate\n");
ret_value = current_node;
}
}
return ret_value;
</code></pre>
<p>}</p>
<p>I know what's wrong here, I just don't know how to fix it. This just overwrites the two nodes attached to the root node. i.e.</p>
<pre><code> |root_node|
/ \
|node_2| |node_3|
</code></pre>
<p>I can't add a node four. It just overwrites node 2 or 3 depending on the input. After debugging and a little research, I'm not quite sure where to go from here...</p>
<p>If anyone can help, I'd really appreciate it.</p>
| <p>This would appear to just be a school project.</p>
<p>Where to begin.</p>
<p>1) You are clobbering left/right all the way down the tree. I'm not sure why you would expect them to be preserved since:
a) You always write to these nodes.
b) The only time you return an existing node is on a strcmp match.</p>
<p>2) You really need to check strcmp < 0 on your first compare.</p>
<p>3) For a non-balanced tree, there's no reason to use recursion - you can just use a loop until you get to a leaf and then hook the leaf. If you really want recursion...</p>
<p>4) Recursive... Return NULL in all cases except when you create a node (ie: the first part where you have current == NULL).</p>
<p>5) In the left/right, store the return value in a temp local Node*. Only if the return value is not NULL should you assign left/right.</p>
<p>Even this doesn't feel right to me, but if I started from scratch it just wouldn't look like this at all. :) We won't even get into the memory leaks/crashes you probably will end up with by just pushing 'char *' values around all willy nilly.</p>
|
How to close the File after it is read from backward? <p>I asked a question about "How to read a text file reversely with iterator in C#" sometime ago. <a href="http://stackoverflow.com/questions/452902/how-to-read-a-text-file-reversely-with-iterator-in-c">Please see the link</a></p>
<p>Jon Skeet was very kind to provide a solution for me. But I still have a question how to close the data file when it is read? It seemed that Jon used a delegate to handle the iterator, which was very interesting. But How I can call something like "file.Close()" to release it when the file was processed?</p>
<p>Thanks,</p>
| <p>It was just a very regrettable oversight.</p>
<p>The answer is - as normal - to use <code>try</code>/<code>finally</code> or a <code>using</code> statement. That way the file will be closed even if an exception is thrown, and even if the caller doesn't iterate all the way back to the start of the file.</p>
<p>However, it <em>does</em> rely on the caller calling <code>Dispose</code> on the <code>IEnumerator<T></code>. Fortunately that's handled automatically by a <code>foreach</code> loop in C#, but if you ever use <code>GetEnumerator()</code>/<code>MoveNext()</code>/<code>Current</code> explicitly, you should be careful and write code like this:</p>
<pre><code>using (IEnumerator<string> iterator = foo.GetEnumerator())
{
while (iterator.MoveNext())
{
string bar = iterator.Current;
// etc
}
}
</code></pre>
<p>Fortunately there aren't very many times when you need to do this :)</p>
<p>I've got more details as to how all of this works under the covers in my <a href="http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx" rel="nofollow">iterator implementation article</a> which you may find useful.</p>
|
Oracle query to get book-name? <pre><code>table name:id
col1:owner-name
col2:book-id1
col3:book-id2
table name:book-name
col1:id
col2:name
</code></pre>
<p>Can anyone get me a query to get following result
owner-name,book1-name,book2-name using above 2 table</p>
| <pre><code>SELECT id.owner-name, b1.name "book1-name", b2.name "book2-name"
FROM id
LEFT JOIN book-name "b1" ON b1.id = id.book-id1
LEFT JOIN book-name "b2" ON b2.id = id.book-id2
</code></pre>
|
What exactly does this url mean? <p>I am using different analytics tags in one of our web applications. Most of them call a javascript code for tracking.</p>
<p>Some tags have url of gif image with querystrings. </p>
<p>Example : <a href="http://www.google-analytics.com/__utm.gif?utmwv=45.542" rel="nofollow">http://www.google-analytics.com/__utm.gif?utmwv=45.542</a></p>
<p>What exactly does this url do? How do they get the values from querystring?</p>
<p>Update: (After reading some answers) I know every browser will load the gif which is 1x1 pixel. But how are they getting the values from query string? in the above case how can they retrieve the value of utmwv? Any code samples ? </p>
| <p>Basically, you write a script in your preferred language, and map that script to <em>yourtrackingscript.gif</em>. ..jpg, png even.</p>
<p>Have done this in asp.net using a http handler.</p>
<p>The script reads the querystring like any other dynamic page (aspnet, asp, php, anything really), then writes it to a db or log file, or does whatever else you want to do with it.</p>
<p>Then set the content-type header appropriately e.g "image/gif", and send back a 1 pixel image, or any other sized image you like. </p>
<p>For just a 1 pixel image, I have opened up a 1 pixel spacer.gif type image in a hex editor, and hard coded it as a byte array to send out as the response, will save a little IO overhead if it gets hit a lot, alernatively, you can read a file from disk or DB and send that back instead.</p>
<p>This is a commonly used trick in email newsletters to track open rates etc.<br />
Often the hardest bit about it is when you don't have enough rights to map the url to the script on a shared machine, but you can develop it as a normal script/program, then get the mapping sorted out once you have it working. </p>
<p>Most modern browsers will respond to a an aspx or php (.etc...) url as an image if it sends the right headers, it's older browsers, browser nanny plugins, and email clients that are the most pernickety about it.</p>
|
Will HTML be replaced by any new technology? <p>I see various frameworks being launched that promise Rich Ui and better User experience as they call it. Silverlight, Flash, Yahoo's new framework etc etc.</p>
<p>Does this mean that over a period of time these frameworks will replace the existing HTML, JAVASCRIPT CSS based web applications?</p>
<p>Wouldn't it be same as opening an application inside a browser window?</p>
| <p>HTML won't be replaced as a standard any time soon. It's too wide spread a technology, and the amount of re-education required among people working with webapps and websites to switch technology completely would be massive and very costly.</p>
<p>HTML will however, like any other technology, evolve. Look at HTML today compared to 10 years ago, it's the same language in the basics but the way we use it, and add-on technologies have changed it quite a lot. Even a high tech, premium site made 10 years ago will look feeble with todays standards.</p>
<p>So, while HTML will like stay "the same" (i.e. follow the natural evolution of a standard), the technology behind the site (php, .NET, JAVA etc.) will probably be more likely to change.</p>
|
How to keep process from exiting when a pthread exits? <p>I am writing a server program in C wherein every time a client connects, I create a new pthread to handle the client's requests.</p>
<p>When all of the threads exit, however, then my program exits, as though a call to exit() has been made. This is a problem - how can I overcome it?</p>
<p>Lets say the server is running, and 2 clients connect. Once those clients disconnect - and thus both threads exit - then my server process exits. What I want is for my server to keep accept()ing socket requests. Ususally this works when I use fork() and accept(). What am I doing wrong such that the parent process is terminating rather than looping infinitely?</p>
<p>Code looks basically like this:</p>
<pre><code>void *talker( void *d ) {
int fd;
char buf[] = "Hello client";
fd = (int)d;
while( 1 ) {
write( fd, buf, strlen( buf )+1 );
sleep(4);
}
}
int main( int argc, char *argv[] ) {
pthread_t thread[50];
int sockfd;
struct sockaddr_in client_addr;
int i = 0;
int s1;
/* ... other declarations */
if (initialize_server_socket(portno, &sockfd) < 0) {
fprintf(stderr, "Could not initialize socket\n");
exit(-1);
}
while( 1 ) {
s1 = accept( sockfd, (struct sockaddr *)&client_addr, &n );
pthread_create( &(thread[i++]), NULL, talker, (void *)s1 );
}
return(0);
}
</code></pre>
<p>Also: this is the same project from a question I already asked (linked below)... though after spending too much time trying to use select() and IPC unsuccessfully, I figured I'd give threads a whirl because of the simplicity of shared address space.</p>
<p><a href="http://stackoverflow.com/questions/575602/using-pipes-in-c-for-parent-child-ipc-makes-program-block">http://stackoverflow.com/questions/575602/using-pipes-in-c-for-parent-child-ipc-makes-program-block</a></p>
<p>Also, much of this code was taken from here: <a href="http://www.s5h.net/2006/06/27/pthread-socket-server-in-c/" rel="nofollow">http://www.s5h.net/2006/06/27/pthread-socket-server-in-c/</a></p>
| <p>If you debug it in gdb you'll see that you're getting a SIGPIPE, which your program doesn't handle. You can either install a SIGPIPE handler or ignore SIGPIPE.</p>
<p>The reason is that your thread is writing to a socket (pipe) that has been closed (by the client), which raises a SIGPIPE. You should check the return value of <code>write()</code> after ignoring SIGPIPE:</p>
<pre><code>signal(SIGPIPE, SIG_IGN);
</code></pre>
<p>or handle SIGPIPE. It has nothing to do with 2 clients connecting, if you wait for 4 seconds after the client disconnects, you'll get a SIGPIPE (in your case).</p>
|
adding classpath in linux <pre><code>export CLASSPATH=.;../somejar.jar;../mysql-connector-java-5.1.6-bin.jar
java -Xmx500m folder.subfolder../dit1/some.xml
cd ..
</code></pre>
<p>is the above statement for setting the classpath to already existing classpath in linux is correct or not</p>
| <p>I don't like setting CLASSPATH. CLASSPATH is a global variable and as such it is evil: </p>
<ul>
<li>If you modify it in one script, suddenly some java programs will stop working. </li>
<li>If you put there the libraries for all the things which you run, and it gets cluttered.</li>
<li>You get conflicts if two different applications use different versions of the same library.</li>
<li>There is no performance gain as libraries in the CLASSPATH are not shared - just their name is shared.</li>
<li>If you put the dot (.) or any other relative path in the CLASSPATH that means a different thing in each place - that will cause confusion, for sure.</li>
</ul>
<p>Therefore the preferred way is to set the classpath per each run of the jvm, for example:</p>
<pre><code>java -Xmx500m -cp ".:../somejar.jar:../mysql-connector-java-5.1.6-bin.jar" "folder.subfolder../dit1/some.xml
</code></pre>
<p>If it gets long the standard procedure is to wrap it in a bash or batch script to save typing. </p>
|
New to Unit Testing <p>I would like to know how to implement unit testing in an existing (quite large) application using visual studio 2008 (.net 2.0).</p>
<p>I understand that developing unit tests for the existing/legacy code is not realistic but I would like to have tests for code moving forward.</p>
<p>I have found plenty of examples on how to write tests for code but nothing on how to set it up from scratch on an existing project, and how to integrate it into the development cycle.</p>
| <p>Simple approach:</p>
<ul>
<li>Pick one of unit test frameworks (Nunit, MbUnit, Xunit, VS unit test framework, ...)</li>
<li>Add project for unit tests in your solution (for example UnitTests). </li>
<li>Start writing tests.</li>
</ul>
<p>For easier organization, create at least one namespace for each project in solution, for example UnitTest.Project1, UnitTests.Project2, ... Depending on size of projects, add more levels to namespace. </p>
<p>This way test project is part of solution. If you use some continuous integration tool, then tests can be automatically executed on each commit to source code repository.</p>
<p><strong>Edit:</strong><br />
Regarding comment on MS Unit Test Framework problem with creating unit tests, there is know problem: <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=357452" rel="nofollow">"Create unit test" wizard does not work</a>. It looks that there are unsupported types of projects that prevent unit test wizard from working correctly. I just tried with one solution that have one F# and several C# projects. I added unit testing project and tried to add tests. Test wizard had problems until I unloaded F# project. Then everything worked fine. </p>
|
Can we run a C#/WPF application on Mac OS X? <p>I sell a C#/WPF application (targeting .net 3.0 at the moment) and people keep asking me for a Mac version.</p>
<p>The application is a time tracking application with a good GUI, there isn't that much business logic in a time tracking application so most of the application is GUI - rewriting just the GUI is equivalent to rewriting the entire application</p>
<p>I don't have the resources to rewrite the application or maintain two different code bases, so I need a way to run the same code on a Mac (I know I'll have to debug and modify the code, what I mean is I can support only one code base, I can't split the project into different Mac and Windows projects - I just don't have the time to work on two projects). </p>
<p>Porting the application to a cross-platform UI library, to a different programing language or to Silverlight are all not relevant - it will take too much time and I think I'll get more sales by investing this time in new features.</p>
<p>Does anyone know of a tool that can run or port C#/WPF to the Mac?</p>
| <p>There's absolutely no way you can run full-fledged WPF app on Mac. I'm not even sure if this is possible in Parallels. The best thing you can do is to use Silverlight, which was previously named "WPF/E" and does run on Macintosh.</p>
|
checking for scrollbars <p>Is there a way to check for scrollbars? What I need is a way to see if the user has written too much text in an iframe (using punyMCE). If the user has gone beyond the allowed number of lines (which will cause scrollbars to appear), I want to tell the user that the maximum number of lines has been entered.</p>
<p>Now there is a second problem. I can't seem to get key-events to fire from inside the punyMCE frame. Which means there is no way for me to do the check... Any suggestions?
I tried this:</p>
<pre><code>frame = frames['eventTxt_f'].document.getElementsByTagName('body')[0];
frame.onkeydown = function() {
alert("keydown");
}
</code></pre>
| <p>A simpler way would probably be to compare the clientHeight of the contents of the iframe with the outer height of the iframe. Something like this:</p>
<pre><code>if (window.frames[0].innerHeight < window.frames[0].document.documentElement.clientHeight)
alert('too much!');
</code></pre>
<p>(tested quickly with the <a href="http://www.moxieforge.net/examples/punymce/examples/simple.html" rel="nofollow">PunyMCE Simple Example</a> with FF3)</p>
|
SharePoint development environment setup <p>i need to setup a development environment for writing Share Point Web Parts. What do I exactly need?</p>
<p>My development machine is a Windows XP Prof. with Visual Studio 2008 Prof. If found <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=05E0DD12-8394-402B-8936-A07FE8AFAFFD"> Windows Share Point Services 3.0: Software Development Kit (SDK)</a> and <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=7bf65b28-06e2-4e87-9bad-086e32185e68"> Windows Share Point Services 3.0: Tools Visual Studio 2008 Extensions, Version 1.2</a>. But i cannot install it ob Windows XP because Share Point Services 3.0 are required to be installed locally. I can not imagine that it is really necessary to install Visual Studio at a Server Operating System.</p>
<p>Is there any other way to setup a clean development environment under Windows XP and using a dedicated Windows Server for running Share Point Services?</p>
| <p>I highly recommend using a VM. SharePoint is big. It requires multiple servers and lots of services. Basically its guaranteed to slow down any workstation you install it on. Other benefits of using a VM to develop:</p>
<ul>
<li>Undo disks</li>
<li>Moving your dev environment from workstation to workstation</li>
<li>easy back-ups</li>
</ul>
<p>This is a pretty comprehensive guide to building a full featured SharePoint VM:
<a href="http://www.pptspaces.com/sharepointreporterblog/Lists/Posts/Post.aspx?List=7537e639%2Db4e5%2D48b6%2D97c0%2Da75e44ee9be3&ID=28&Source=http%3A%2F%2Fwww%2Epptspaces%2Ecom%2Fsharepointreporterblog%2FLists%2FPosts%2FAllPosts%2Easpx" rel="nofollow">http://www.pptspaces.com/sharepointreporterblog/Lists/Posts/Post.aspx?List=7537e639%2Db4e5%2D48b6%2D97c0%2Da75e44ee9be3&ID=28&Source=http%3A%2F%2Fwww%2Epptspaces%2Ecom%2Fsharepointreporterblog%2FLists%2FPosts%2FAllPosts%2Easpx</a></p>
<p>Although, if you are going to be doing a lot of SharePoint development I would build a parent VM with the OS, SharePoint, and database. Then create a child VM (<a href="http://www.andrewconnell.com/blog/articles/UseVirtualPCsDifferencingDisksToYourAdvantage.aspx" rel="nofollow">differential disk</a>) with dev tools (VS 2008, Office 2007, SharePoint Designer). That way, you can always roll back to a clean SharePoint environment if you need to.</p>
<p>Furthermore, I think the best way to do serious solution development is to spend the time and learn how to build your own solution files, and rolling your own features. <a href="http://nant.sourceforge.net" rel="nofollow">NANT</a> can be used to great effect for this. The existing crop of automated tools have limitations that you will inevitably run up against if you are doing anything a bit complicated. </p>
<p>Learning all of the moving parts of solution development is a bit daunting, but once you do it gives you a MUCH better picture of what SharePoint is doing under the covers.</p>
|
How do I stop 401 responses from TFS 2008 <p>Whenever a web request is made by Visual Studio to TFS, Fiddler will show a 401 Unauthorized error. Visual Studio will then try again with a proper Authorization Negotiate header in place with which TFS will respond with the proper data and a 200 status code.</p>
<p>How can I get the correct headers to be sent the first time to stop the 401?</p>
| <p>This is how the process of Windows Integrated Authentication (NTLM) works. NTLM is a connection based authentication mechanism and actually involves 3 calls to establish the authenticated session. </p>
<p>The TFS API then goes to extra-ordinary lengths to make sure that this handshake is done in the most efficient way possible. It will keep the authenticated connection open for a period of time to avoid this hand-shake where possible. It will also do the initial authentication using a HTTP payload with minimal content and then send the real message if the message you were going to send is over a certain length. It does a bunch of other tricks as well to optimise the connection to TFS.</p>
<p>Basically, I would just leave it alone as it works well.</p>
|
Using MS Sync Framework to synchronize two SQL CE Dbs <p>I'm just working into the Microsoft Sync Framework. It looks quite easy to sync a local SQL CE 3.5 Database with a remote SQL Server 2008 using the SqlSyncAdapterBuilder and SqlServerChangeTracking.</p>
<p>Unfortunately, syncing two SQL CE 3.5 Databases doesn't look that easy...<br />
The documentation is very sparse, and I don't realy know how to get started here.</p>
<p>My concrete scenario looks like the following:</p>
<ul>
<li>I have one central SQL Server 2008.</li>
<li>Multiple clients are connected to this server (some of them only partially). </li>
<li>Those (partially connected) clients are using multiple applications (maybe running concurrently) working on the same data base.</li>
</ul>
<p>Syncing the clients with the central server should be no problem. Syncing the multiple applications on an offline-client is where I've thought of using multiple SQL CE databases (one as a server, and one for every application-instance). I'd really appriciate being able to use the same conflict-resolution mechanisms when syncing the clients with the server and also when syncing multiple applications on the client. Installing a SQL Server 2008 Express on every client is a no-go.</p>
<p>Does anyone have some experience with syncing two SQL CE databases?</p>
| <p><a href="http://msdn.microsoft.com/en-us/library/bb902854%28SQL.105%29.aspx">Sync Framework 2.0</a> allows synchronization between SQL Server Compact Edition databases.</p>
<blockquote>
<p>SqlCeSyncProvider is used to
synchronize SQL Server Compact
databases.</p>
<p>This provider can be used to
synchronize with a central server but
also has the ability to synchronize
with other clients, which is not
possible with SqlCeClientSyncProvider.
This ability enables developers to
target new scenarios such as a
collaboration scenario in which teams
of people need to synchronize among
each another in the absence of a
connection to a central server.</p>
</blockquote>
|
Create XPathDocument from XmlElement <p>I'm using a webservice which returns an <code>XmlElement</code> object to my C# program. I would like to read information from the <code>XmlElement</code> using Xpath. What is the best way to create an <code>XPathDocument</code> from the <code>XmlElement</code>?</p>
| <p>If you have an <code>XmlElement</code>, can you not just use <code>SelectNodes()</code> / <code>SelectSingleNode()</code>?</p>
<p>Also, all <code>XmlNode</code>s are <code>IXPathNavigable</code>, allowing you to get a navigator.</p>
<p>Finally, you can use <code>new XmlNodeReader(element)</code>, and use this to create an <code>XPathDocument</code> using the overload that accepts an <code>XmlReader</code>.</p>
|
How to use INNER JOIN in the scenario? <p>I have 2 tables:</p>
<p>'Users' Table</p>
<pre>
id username
---- --------
0001 user1
0002 user2
0003 user3
0004 user4
</pre>
<p>'Friends' Table</p>
<pre>
user_id friend_id friend
------- --------- ------
0001 0004 1
0002 0004 1
0005 0004 0
</pre>
<p>How do I display all user4 friends' name? if in friends table, friend column, 1 indicates they are friend, 0 indicate they are still not friend.</p>
<p>I use INNER JOIN, which looks like this:</p>
<pre><code>SELECT users.username
FROM `users`
INNER JOIN `friends` ON users.id = friends.friend_id
WHERE friends.user_id = 0004
AND friend = 1;
</code></pre>
<p>But what I get is:</p>
<p>user4 and user4 instead of user1 and user2</p>
<p>Can help me?</p>
| <pre><code>SELECT u.username
FROM Friends f, Users u
WHERE f.user_id = u.id
AND f.friend = 1
AND f.friend_id = '0004'
</code></pre>
|
What is a working copy and what does "switching" do for me in Tortoise SVN? <p>I have a software app and I've hit an important milestone, version 2.0.</p>
<p>I decided I want to tag this version as "Version-2.0" so I have named this snapshot. I also created a "Version-2.0" branch in case I need to fix anything and merge it back into my trunk.</p>
<p>After reading through the Tortoise SVN help file, it informs me that I can switch my "working copy" to a newly created branch.</p>
<p>What does this mean? </p>
<p>Presently, I have:</p>
<blockquote>
<p>/Project/Trunk/<br>
/Project/Tags/<br>
/Project/Branches/</p>
</blockquote>
<p>All checked out. So what would be the point of "switching"? Currently, I just go to my /trunk folder and do my work. And when I made my tag and branch, it created folders in my /Tags/ and /Branches/ folder after I did an update.</p>
<p>Why wouldn't I just go to /Branches/Experiemental-v3.0/ and do my work there if I wanted to?</p>
<p><strong>Can someone explain the concept of "Working Copy" and "Switching" to me? What am I missing? Do people generally not have the whole repository checked out, is that it?</strong></p>
| <p>A working copy is the copy you have checked out to your working area. It doesn't matter if it is a branch or from the trunk. It's what you are working on.</p>
<p>You can switch between branches (or more correctly copies) of the same parent with svn switch. This will basically say, what's different between the current working copy and the branch I am switch to. It then performs an update on your current working copy to the revision of branch you switch to.</p>
<p>So working copy is your checkout, however it was obtained.</p>
<p>Switching is just changing the branch your working copy commits to. Think of it like changing the pointer in the repository where your commits will go. With the aid of acquiring any differences from the branch to your work area.</p>
|
Dropdown list <p>I want people to choose from a dropdown list,and their choice takes them to a page they have chosen.</p>
| <p>In aspx</p>
<pre><code><asp:DropDown ID="MyDropDown" runat="server" AutoPostBack="true" OnSelectedIndexChanged="RedirectUser">
<asp:ListItem Value="/MyPage.aspx" Text="MyPage"/>
</asp:DropDown>
</code></pre>
<p>In code behind</p>
<pre><code>protected void RedirectUser(object sender, EventArgs e)
{
Response.Redirect(MyDropDown.SelectedValue);
}
</code></pre>
<p>Okay read the "question" again and you didn't specify ASP.NET but nevermind, more details in the question would have helped</p>
|
Control a service from another application in Vista <p>I'm wondering if it's possible to create a windows service in .NET and then create another windows.forms process that connects to the service and passes parameters, modifies and views its datastructures and connected database, etc.</p>
<p>I believe that in Vista this is only possible with the use of sockets, and not with a ServiceController class. Can anyone direct me to examples or tutorials on how to do this, please?</p>
<p>Thanks!</p>
| <p>I'm not aware of a <code>ServiceController</code> limitation, but then: I rarely use Vista ;-p</p>
<p>Rather than raw sockets... one option is to have the service act as a WCF host, via <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" rel="nofollow"><code>ServiceHost</code></a>. Your app would be a WCF client, (proxy generated via <code>svcutil.exe</code> or via the IDE). This would make it painless to talk to, The only question would be which channel to use - perhaps named pipes, since that is machine specific.</p>
|
Need key code for Alt-Ctrl-Del <p>I need the key code for <kbd>Alt</kbd>+<kbd>Ctrl</kbd>+<kbd>Del</kbd> in c#,
for example </p>
<pre><code>const int KEYEVENTF_KEYUP = 0x2;
const int KEYEVENTF_KEYDOWN = 0x0;
keybd_event(0x11, 0, KEYEVENTF_KEYDOWN, 0);
keybd_event(0x41, 0, KEYEVENTF_KEYDOWN, 0);
keybd_event(0x11, 0, KEYEVENTF_KEYUP, 0);
keybd_event(0x41, 0, KEYEVENTF_KEYUP, 0);
</code></pre>
<p>this is the code for <kbd>ctrl</kbd>+<kbd>a</kbd>.</p>
| <p>You cannot capture <kbd>Alt</kbd>+<kbd>Ctrl</kbd>+<kbd>Del</kbd>. It's captured by the operating system and is <strong>very</strong> secure.</p>
<p>Even programs like VMWare have to emulate it with <kbd>Alt</kbd>+<kbd>Ctrl</kbd>+<kbd>Ins</kbd> since Windows protects it so well, and for good reason. If you could subvert it, Windows login security would be useless.</p>
|
Select COUNT(*) of subquery without running it twice <p>I've got a procedure to return a result set which is limited by page number and some other stuff. As an OUTPUT parameter I need to return a total amount of selected rows according to the parameters except the page number. So I have something like that:</p>
<pre><code>WITH SelectedItems AS
(SELECT Id, Row1, Row2, ROW_NUMBER() OVER (ORDER BY Row1) AS Position
FROM Items
WHERE Row2 = @Row2)
SELECT Id, Row1, Row2
FROM SelectedItems
WHERE Position BETWEEN @From AND @To
</code></pre>
<p>And then I need to set the OUTPUT parameter to the number of rows in the innerquery. I can just copy the query and count it, but this query could returns thousands of rows (and will be more in the future), so I am looking for method to do that with a good performance. I was thinking about table variables, is it a good idea? Or any other suggestions?</p>
<p>To be more specific, it's the Microsoft SQL Server 2008.</p>
<p>Thank you, Jan</p>
| <p>You can count the total rows as a separate column in your main query using COUNT(*). Like this:</p>
<pre><code>WITH SelectedItems AS
(SELECT Id, Row1, Row2, ROW_NUMBER() OVER (ORDER BY Row1) AS Position,
COUNT(*) OVER () AS TotalRows
FROM Items
WHERE Row2 = @Row2)
SELECT Id, Row1, Row2
FROM SelectedItems
WHERE Position BETWEEN @From AND @To
</code></pre>
<p>This will return the count in your result set rather than in a output parameter, but that should fit your requirements. Otherwise, combine with a temp table:</p>
<pre><code>DECLARE @tmp TABLE (Id int, RowNum int, TotalRows int);
WITH SelectedItems AS
(SELECT Id, Row1, Row2, ROW_NUMBER() OVER (ORDER BY Row1) AS Position,
COUNT(*) OVER () AS TotalRows
FROM Items
WHERE Row2 = @Row2)
INSERT @tmp
SELECT Id, Row1, Row2
FROM SelectedItems
WHERE Position BETWEEN @From AND @To
SELECT TOP 1 @TotalRows = TotalRows FROM @tmp
SELECT * FROM @tmp
</code></pre>
<p>You will find using a temp table for just your paged result will not use much memory (depending on your page size of course) and you're only keeping it live for a short period of time. Selecting the full result set from the temp table and selecting the TotalRows will only take a tiny bit longer.</p>
<p>This will be much faster than running a totally separate query, which in my test (repeating the WITH) doubled the execution time.</p>
|
Static context in enum definition <p>The syntax sugar provided by Java's <code>enum</code> facility can sometimes be a little confusing. Consider this example, which does not compile:</p>
<pre><code>public enum TestEnum {
FOO("foo") {
public void foo() {
helper(); // <- compiler error
}
};
String name;
TestEnum(String name) {
this.name = name;
}
public abstract void foo();
private void helper(){
// do stuff (using this.name, so must not be static)
}
}
</code></pre>
<p>Can anyone explain why the compiler says </p>
<blockquote>
<p>Non-static method 'helper()' cannot be referenced from a static context</p>
</blockquote>
<p>How exactly is this context static?</p>
<p>You can make this compile by changing the call to <strong><code>this.</code></strong><code>helper()</code> (here is one confusing point: if we really are in a "static context" like the compiler suggests, how can "<code>this</code>" work?) or by increasing the visibility of <code>helper()</code> to default level. Which would you prefer? Also, feel free to suggest a better question title :-)</p>
<p><strong>Edit</strong>: I found <a href="http://74.125.77.132/search?q=cache:yTkD6C3gZTEJ:x86.sun.com/thread.jspa%3FmessageID%3D3780246" rel="nofollow">some discussion about this</a> - but no real answers. My colleague thinks the fact that that <code>this.helper()</code> works is actually a compiler bug. And indeed with newer Java versions it seems <em>not</em> to work (although <code>super.helper()</code> does): "cannot find symbol helper()". (Although there's something odd going on: after trying with different Java versions I can't get <code>this.helper()</code> to compile again with any of them...)</p>
| <p>The error message is misleading, just make <code>helper</code> protected and it will work. </p>
<pre><code>protected void helper(){
// can be called from subclasses (such as FOO) since it is not private
}
</code></pre>
|
The use of undefined variables in if-statements <p>This snippet results in a JavaScript runtime error: (<code>foo</code> is not defined)</p>
<pre><code>if (foo) {
// ...
}
</code></pre>
<p>I have to define <code>foo</code> first, like so:</p>
<pre><code>var foo = foo || null // or undefined, 0, etc.
</code></pre>
<p>... And only then can I do:</p>
<pre><code>if (foo) {
// ...
}
</code></pre>
<p>Why is that?
<br />
<br />
<br />
<strong>Update:</strong></p>
<p>This was somewhat of a brainfart on my side of things: 'fcourse you can't access a variable which is not allocated.</p>
<p>Fun stuff that you can do a typeof() on an undefined variable thou. I'm gonna accept <a href="http://stackoverflow.com/users/66841/miccet">miccet</a>'s answer since I think it's the most elegant solution.</p>
| <p>I sense you are asking because you are aware that javascript seems to allow undefined variables in some situations (ie no runtime errors) and not in others.</p>
<p>The reasoning is as follows: javascript <em>always</em> throws an error on checking undefined variables, but <em>never</em> throws an error on checking undefined <em>properties</em>, as long as you only use one level of indirection.</p>
<p>Example:</p>
<pre><code>// throws runtime error
if(foo) {
// ...
}
// does not throw runtime error
if(window.foo) {
// ...
}
// does not throw runtime error
var obj = {};
if(obj.foo) {
// ...
}
// throws runtime error
if(obj.foo.bar) { // going two levels deep, but foo is undefined
// ...
}
</code></pre>
<p>Hope that clears it up a bit.</p>
|
Do any functions fire when going "back" to a view with a UINavigation <p>I know its probably a really simple thing, but I need to reload some data if some changes have been made from a subview and then the master view is returned to.</p>
| <p>Have a look at implementing</p>
<pre><code>- (void)viewDidAppear:(BOOL)animated
</code></pre>
<p>or</p>
<pre><code>- (void)viewWillAppear:(BOOL)animated
</code></pre>
<p>But note there can be a problem that needs to be taken care of for UINavigationControllers <a href="http://davidebenini.it/2009/01/03/viewwillappear-not-being-called-inside-a-uinavigationcontroller/" rel="nofollow">Link>></a></p>
|
How can I create a temp file with a specific extension with .NET? <p>I need to generate a unique temporary file with a .csv extension.</p>
<p>What I do right now is </p>
<pre><code>string filename = System.IO.Path.GetTempFileName().Replace(".tmp", ".csv");
</code></pre>
<p>However, this doesn't guarantee that my .csv file will be unique.</p>
<p>I know the chances I ever got a collision are very low (especially if you consider that I don't delete the .tmp files), but this code doesn't looks good to me.</p>
<p>Of course I could manually generate random file names until I eventually find a unique one (which shouldn't be a problem), but I'm curious to know if others have found a nice way to deal with this problem.</p>
| <p>Guaranteed to be (statistically) unique:</p>
<pre><code>string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";
</code></pre>
<p>(To quote from the wiki article on the probabilty of a collision:</p>
<blockquote>
<p>...one's annual risk of being hit by a
meteorite is estimated to be one
chance in 17 billion [19], that means
the probability is about 0.00000000006
(6 Ã 10â11), equivalent to the odds of
creating a few tens of trillions of
UUIDs in a year and having one
duplicate. In other words, only after
generating 1 billion UUIDs every
second for the next 100 years, the
probability of creating just one
duplicate would be about 50%. The
probability of one duplicate would be
about 50% if every person on earth
owns 600 million UUIDs</p>
</blockquote>
<p>EDIT: Please also see JaredPar's comments.</p>
|
How can I get started creating a Java web service? <p>I want to create a simple <code>hello world</code> java web service.</p>
<p>What tools I need to get started?</p>
<p>What do I need to know to get started deploying this in Tomcat?</p>
| <p>There are plenty of <a href="http://www.google.com/search?q=tomcat%2Baxis%2Btutorial" rel="nofollow">Tomcat + axis tutorials</a>. For example, <a href="http://tomcat-configure.blogspot.com/2009/01/tomcat-axis-tutorial.html" rel="nofollow">this blog post</a> seems to do a reasonable job.</p>
|
SharePoint Webpart deserialize error <p>I am getting a random web part error, it works one refresh and then not the next:</p>
<blockquote>
<p><strong>Web Part Error</strong>: One of the properties of the web part has an
incorrect format. Windows SharePoint
services cannot deserialize the Web
Part. Check the format of the
properties and try again.</p>
</blockquote>
<p>The web parts have been on the site for a long time, and I have checked Micorsoft Support, <a href="http://support.microsoft.com/kb/826786" rel="nofollow">http://support.microsoft.com/kb/826786</a> . And it is not a permision error becuase it has been this way for a long time. The only thing changed in regards to webparts was going into Site settings > Web Parts > New and selected some webparts that were not in the list and I think I also Checked the ones that are having this random error and clicked "Populae Gallery". Any body have a clue?</p>
| <p>This could also be because of insufficient disk space on the server where SharePoint is hosted. <a href="http://www.sharepointblogs.com/vipul/archive/2006/09/25/webpart-error-due-to-space-crunch.aspx" rel="nofollow">http://www.sharepointblogs.com/vipul/archive/2006/09/25/webpart-error-due-to-space-crunch.aspx</a> Check the available disk space.</p>
<p>Hope this helps.</p>
|
what is minimum flash player revision working with FLEX 3 <p>My page has currently this set up - what is minimum REVISION I can configure here:</p>
<pre><code>// Major version of Flash required
var requiredMajorVersion = 9;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Minor version of Flash required
var requiredRevision = 124;
</code></pre>
<p>For example my MacOSX ibook machine does not start this page at all, it just says "you are trying to install flash palyer on unsupported OS"</p>
<p>So I really like to keep version requirement as minimum as possible.</p>
| <p>See <a href="http://www.adobe.com/products/flex/systemreqs/" rel="nofollow">this</a>. It looks like its best to have 9.0.124.0. Which means you will need to upgrade your Macbook flash player.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.