instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>The <a href="http://en.wikipedia.org/wiki/Law_Of_Demeter" rel="noreferrer">wikipedia article</a> about <a href="http://c2.com/cgi/wiki?LawOfDemeter" rel="noreferrer">Law of Demeter</a> says:</p>
<blockquote>
<p>The law can be stated simply as "use only one dot".</p>
</blockquote>
<p>However a <a href="http://weblogs.asp.net/jgalloway/archive/2006/12/06/a-simple-example-of-a-fluent-interface.aspx" rel="noreferrer">simple example</a> of a <a href="http://en.wikipedia.org/wiki/Fluent_interface" rel="noreferrer">fluent interface</a> may look like this:</p>
<pre><code>static void Main(string[] args)
{
new ZRLabs.Yael.Pipeline("cat.jpg")
.Rotate(90)
.Watermark("Monkey")
.RoundCorners(100, Color.Bisque)
.Save("test.png");
}
</code></pre>
<p>So does this goes together?</p>
|
<p>Well, the short definition of the law shortens it too much. The real "law" (in reality advice on good API design) basically says: Only access objects you created yourself, or were passed to you as an argument. Do not access objects indirectly through other objects. Methods of fluent interfaces often return the object itself, so they don't violate the law, if you use the object again. Other methods create objects for you, so there's no violation either.</p>
<p>Also note that the "law" is only a best practices advice for "classical" APIs. Fluent interfaces are a completely different approach to API design and can't be evaluated with the Law of Demeter.</p>
|
<p>There's no problem with your example. After all, you're rotating, watermarking, etc... always the same image. I believe you're talking to a Pipeline object all the while, so as long as your code only depends on the class of the Pipeline, you're not violating LoD.</p>
| 9,312
|
<h2>Syntax</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218129#2218129">Shorthand for the ready-event</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218135#2218135">Line breaks and chainability</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389474#389474">Nesting filters</a> by Nathan Long</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/552831#552831">Cache a collection and execute commands on the same line</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1519474#1519474">Contains selector</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2750689#2750689">Defining properties at element creation</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/3967325#3967325">Access jQuery functions as you would an array</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/182666#182666">The noConflict function - Freeing up the $ variable</a> by Oli</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382853#382853">Isolate the $ variable in noConflict mode</a> by nickf</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218120#2218120">No-conflict mode</a> by roosteronacid</li>
</ul>
<h2>Data Storage</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382834#382834">The data function - bind data to elements</a> by TenebrousX</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/5410587#5410587">HTML5 data attributes support, on steroids!</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/504776#504776">The jQuery metadata plug-in</a> by Filip Dupanović</li>
</ul>
<h2>Optimization</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1019899#1019899">Optimize performance of complex selectors</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/504732#504732">The context parameter</a> by lupefiasco</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389793#389793">Save and reuse searches</a> by Nathan Long</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382922#382922">Creating an HTML Element and keeping a reference, Checking if an element exists, Writing your own selectors</a> by Andreas Grech</li>
</ul>
<h2>Miscellaneous</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389906#389906">Check the index of an element in a collection</a> by redsquare</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/892617#892617">Live event handlers</a> by TM</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/696385#696385">Replace anonymous functions with named functions</a> by ken</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/191139#191139">Microsoft AJAX framework and jQuery bridge</a> by Slace</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/922865#922865">jQuery tutorials</a> by egyamado</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/998547#998547">Remove elements from a collection and preserve chainability</a> by roosteronacid</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/191061#191061">Declare $this at the beginning of anonymous functions</a> by Ben</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1771311#1771311">FireBug lite, Hotbox plug-in, tell when an image has been loaded and Google CDN</a> by Colour Blend</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/182715#182715">Judicious use of third-party jQuery scripts</a> by harriyott</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1584927#1584927">The each function</a> by Jan Zich</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1235178#1235178">Form Extensions plug-in</a> by Chris S</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2750689#2750689">Asynchronous each function</a> by OneNerd</li>
<li><a href="https://stackoverflow.com/questions/182630/jquery-tips-and-tricks/4962433#4962433">The jQuery template plug-in: implementing complex logic using render-functions</a> by roosteronacid</li>
</ul>
|
<p><strong>Creating an HTML Element and keeping a reference</strong></p>
<pre><code>var newDiv = $("<div />");
newDiv.attr("id", "myNewDiv").appendTo("body");
/* Now whenever I want to append the new div I created,
I can just reference it from the "newDiv" variable */
</code></pre>
<p><br />
<strong>Checking if an element exists</strong></p>
<pre><code>if ($("#someDiv").length)
{
// It exists...
}
</code></pre>
<p><br />
<strong>Writing your own selectors</strong></p>
<pre><code>$.extend($.expr[":"], {
over100pixels: function (e)
{
return $(e).height() > 100;
}
});
$(".box:over100pixels").click(function ()
{
alert("The element you clicked is over 100 pixels height");
});
</code></pre>
|
<p><strong>No-conflict mode</strong></p>
<pre><code>jQuery.noConflict();
</code></pre>
<blockquote>
<p>"Run this function to give control of the <code>$</code> variable back to whichever library first implemented it. This helps to make sure that jQuery doesn't conflict with the <code>$</code> object of other libraries.</p>
<p>By using this function, you will only be able to access jQuery using the <code>jQuery</code> variable. For example, where you used to do <code>$("div p")</code>, you now must do <code>jQuery("div p")</code>".</p>
</blockquote>
| 22,073
|
<p>Please one library per answer so that people can vote for the individually.</p>
|
<p><a href="http://code.google.com/p/calendardateselect/" rel="nofollow noreferrer">Calendar Date Select</a></p>
|
<p><a href="http://developer.yahoo.com/yui/calendar/" rel="nofollow noreferrer">Yahoo! UI Library: Calendar</a></p>
<blockquote>
<p>"The Calendar component is a UI control
that enables users to choose one or
more dates from a graphical calendar
presented in a single month or multi
month interface. Calendars are
generated entirely via script and can
be navigated without any page
refreshes."</p>
<p>"You'll find the Calendar Control to be
a useful and easy-to-implement
enhancement to any date-selection
interaction; you may also find that
the Calendar's foundation classes are
a good place to start for more complex
interfaces that visually organize
date-tagged information (like
appointments, photos, events, etc.)."</p>
</blockquote>
| 25,440
|
<p>I am using a Flashforge Creator Dual Extrusion 3D Printer with RepG (<a href="http://replicat.org/" rel="nofollow noreferrer">ReplicatorG</a>), and tonight a print completely detached from the build plate.</p>
<p>I reset everything and watched it closely. It is a simple abs print at 230/110 degrees.</p>
<p>A few seconds after start of print, I noticed that the print bed temp had dropped to 109... and kept dropping.</p>
<p>This is new behavior. I haven't started to troubleshoot yet. I am looking for suggestions on how to troubleshoot the issue.</p>
<p><strong>Edit 1:</strong></p>
<p>Tonight RepG would not connect to the printer. I reseated the USB cord
and now it does.</p>
<p>The test print is ABS at 230/110 from this open scad.</p>
<pre><code>difference()
{
cylinder(d = 10, h = 2);
cylinder(d = 9, h = 2);
}
</code></pre>
<p>Pᴀᴜʟsᴛᴇʀ2/Oscar
Once the print starts the print bed begins cooling. It is cooling before
any filament is laid down.</p>
<p><strong>Edit 2:</strong></p>
<p>Examination of the gcode shows the root cause. It does contain</p>
<pre><code>M104 S230 T1 (set extruder temperature)
</code></pre>
<p>It does not contain a </p>
<pre><code>M109 S110 (set build plate temperature)
</code></pre>
<p>When I manually add the M109 to the gcode file, the model prints normally, and the build plate temperature holds for the duration of the print. </p>
<p>The drop in temperature last week is due to the fact that I tend to preheat the printer before actually starting the print. Since there was no M109 the bed plate cooled to ambient temperature.</p>
<p>There isn't a hardware issue here. Most likely it is a Rep G configuration error of some sort.</p>
<p><strong>Edit 3:</strong></p>
<p>I resolved the issue by a fresh install of the latest Rep G. I rebuilt the profiles from scratch with G Code to set the correct bed temp. Thank you for your suggestions.</p>
|
<p>Check your slicer settings. Some slicers allow the temperature to change at a specified layer. You may have programmed the slic3r to turn off the bed after the first (or maybe zeroth) layer.</p>
<p>You call also examine the G-code for M140, M144, and M190 commands.</p>
<p>Of course, the usual intermittent electric connections, power supply failures, etc. should be checked, but don't overlook the possibility that it is working exactly as you are asking it to work. </p>
|
<p>Preheating the bed is a commonly used approach to shorten the time to print. I'll explain; it actually does not shorten the physical print time itself, but before you start a print there is always stuff to do like inserting the SD-card or loading the model in the print server, while you do that, the bed will be heating, so time gained.</p>
<p>When you load a model it apparently resets the temperatures, so preheating will only have an effect when you also actually set the bed temperature in the G-code file. This means that either your G-code file has some codes that influence the temperature, the connector is loose or loading a print over the program you use must reset the bed temperature, there aren't any other options.</p>
<p>To comment on your G-code, M109 is used to set the extruder temperature and wait till it is reached, M190 is used to set the bed temperature and wait till it is reached. Usually M190 is used to set the bed temperature before the first layer is being printed; the printer waits until the temperature is reached before the printer continues to the next command (usually the heating of the hotend). If you have selected a different temperature for the rest of the print you will find the M140 G-code command prior to printing the second layer.</p>
<p>I have tested on my Prusa i3 clone running a Marlin fork to print a model with all references to M190 and M140 removed. I pre-heated to 70 °C (for PETG) and loaded the model in OctoPrint print server and commenced the print. The printer retained the bed value and did not drop.</p>
<p>Basically, it is needed to take a closer look at your G-code file. The answer must be in there. If there is nothing to find in the G-code file and electronic connections are fine, the answer must be found in ReplicatorG, this might send reset signals prior to sending the print, but that sounds really strange.</p>
| 973
|
<p>How do I accomplish text wrapping of table fields in SSRS Report, and proper landscaping when rendering the report to PDF format?</p>
|
<p>Setting the CanGrow property to True will allow wrapping, and the text box will get as big as it needs to vertically to contain all the characters in its value.</p>
<p>To ensure the proper landscaping of PDF exports, set the PageSize of the report object accordingly (setting Width=11" x Height=8.5" will make a landscape PDF).</p>
|
<p>To ensure line breaks are inserted correctly, use</p>
<pre><code>=Replace(Fields!MyField.Value, vbLf, Environment.NewLine)
</code></pre>
<p>Set CanGrow = True.</p>
| 39,276
|
<p>I'm working on a project that currently has zero users but we would like to scale up to potentially hundreds. Currently we are running on a MySQL database with AMFPHP interacting with Flex. We used Flex because of its robust graphic features (important to this project) and because the initial developer (not me) already knew ActionScript. We are currently using AIR but might switch to web-based Flash at some point.</p>
<p>My questions are:</p>
<ol>
<li>Is Flex a good tool for a project like this?</li>
<li>What are the main limitations of Flex that we might encounter?</li>
<li>What are other development platforms we might want to consider?</li>
</ol>
<p>Thanks.
- Dave</p>
|
<p>Short answer, Yes. There are already many prime-time Apps using Flex as their UI development platform. If you go to the Adobe site they showcase quite a few.</p>
<p>Speaking personally, I chose Flex for two reasons, first was that, although you probably can do much of what Flex does in HTML or with an appropriate toolkit, Flex is designed for attractive and compelling user experience and has available all of Flash. Plus the development environment and available widgets make it easy and fun to program. I don't want to spark a religious war about HTML vs. Flex, so I'll leave that there - it works for me and my application and customers.</p>
<p>Second, and more important, was that it balances the processing load more towards the client which means my server architecture can be optimised just for serving the content and persisting the data. Most of my business logic has migrated across to the client. Having spent many years in classical architectures I think this is a huge step forward, but I can already her a chorus of disagreement about that too.</p>
<p>My word of caution about Flex comes from needing to adopt the right architecture for your client code. It is pretty easy to create a huge and badly performing app with Flex if you get that wrong. Make everything event driven and apparently asynchronous and you should be OK ('apparently' because the Flash player is single threaded). And that is downside 1, the single threaded Flash player sometimes causes issues.</p>
<p>Downside 2 is perhaps more serious and that is locked down desktops in corporate environments. Quite often your target audience won't have administrative rights to their computer and will have either the wrong flash player or none at all. This is particularly true in public sector organisations and the military, so if you are heading there I would test carefully the presence of Flash amongst your users.</p>
<p>Other than that I heartily recommend Flex. It's also a great thing to have on your CV!</p>
<p>HTH</p>
|
<p>Flex + AIR is probably as good a tool as Visual Basic was; it may be a better tool for having a much more flexible programming language and having free development tools, but keep the limitations in mind....</p>
<p>The main limitation I've seen from working with it is documentation. There seems to be not enough documentation, not good enough documentation, and not enough high-visibility work on it in the community. (This is coming from years in .NET; I've been constantly upset with how little MSDN says about methods but generally able to deal with it by finding the most useful blog posts.)</p>
<p>Other possible development platforms would depend very heavily on the specifics of the project. Web-based platforms bog down in deep, stateful interactions with data sets (even with nice AJAX libraries), whereas maintaining client-side installations of any thick client program (say, Flex + AIR) might be overkill if it's just a few CRUD forms.</p>
| 40,859
|
<p>I'm one of the people involved in the <a href="http://testanything.org/wiki/index.php/TAP_at_IETF:_Notes" rel="noreferrer">Test Anything Protocol (TAP) IETF group</a> (if interested, feel free to join the mailing list). Many programming languages are starting to adopt TAP as their primary testing protocol and they want more from it than what we currently offer. As a result, we'd like to get feedback from people who have a background in xUnit, TestNG or any other testing framework/methodology.</p>
<p>Basically, aside from a simple pass/fail, what information do you need from a test harness? Just to give you some examples:</p>
<ul>
<li>Filename and line number (if applicable) </li>
<li>Start and end time</li>
<li>Diagnostic output such as the difference between what you got and what you expected.</li>
</ul>
<p>And so on ...</p>
|
<p>It must be very, very easy to write a test, and equally easy to run them. That, to me, is the single most important feature of a testing harness. If someone has to fire up a GUI or jump through a bunch of hoops to write a test, they won't use it.</p>
|
<p>I use TAP as output protocol for a set of simple C++ test methods, and have seen the following shortcomings:</p>
<ul>
<li>test steps cannot be put into groups (there's only the grouping into several test scripts; but for running all tests in our software, I need at least one more level of grouping, so that a single test step would be identified by like "DB connection" -> "Reconnection Test" -> "test step #3")</li>
<li>seeing differences between expected and actual output is useful; I either print the diff to stderr (as comment) or actually launch a graphical diff tool</li>
<li>the protocol and tools must be really language-independent. For example, so far I only know of the Perl "prove" tool for running tests, which is limited to running Perl scripts</li>
</ul>
<p>In the end, the test output must be suitable as basis for easily generating an HTML report file which lists succeeded tests very concisely, gives detailed output for failed tests, and makes it possible to quickly jump into the IDE to the failing test line.</p>
| 11,699
|
<p>I have a TSqlDataSet which has a blob field, I need to get the data of this blob field in the BeforeUpdateRecord event of the provider and execute an update command, I've tried this:</p>
<pre><code>Cmd := TSQLQuery.Create(nil);
try
Cmd.SQLConnection := SQLConnection;
Cmd.CommandText := 'UPDATE MYTABLE SET IMAGE = :PIMAGE WHERE ID = :PID';
Cmd.Params.CreateParam(ftBlob, 'PIMAGE ', ptInput).Value := DeltaDS.FieldByName('IMAGE').NewValue; //blob field
Cmd.Params.CreateParam(ftString, 'PID', ptInput).Value := DeltaDS.FieldByName('ID').NewValue;
Cmd.ExecSQL;
finally
Cmd.Free;
end;
</code></pre>
<p>When I execute that I get an EDatabaseError with message: 'No value for parameter PIMAGE.</p>
<p>What am I missing?</p>
|
<p>Answering my own question, the correct way to do it is the following:</p>
<pre><code>const
SQL = 'UPDATE MYTABLE SET IMAGE = :PIMAGE WHERE ID = :PID;';
var
Params: TParams;
begin
Params := TParams.Create(nil);
try
Params.CreateParam(ftBlob, 'PIMAGE', ptInput).AsBlob := DeltaDS.FieldByName('IMAGE').NewValue;
Params.CreateParam(ftString, 'PID', ptInput).Value := DeltaDS.FieldByName('ID').NewValue;
SQLConnection.Execute(SQL, Params);
finally
Params.Free;
end;
end;
</code></pre>
|
<p>Have you tried testing with another driver (e.g. ODBC)? It's possible that the error is not in your code. This approach (changing data providers/drivers) has helped me with some confusing problems that turned out not to be mine.</p>
| 42,215
|
<p>I'm looking at ways to deploy a Ruby on Rails app (running on JRuby) to a Tomcat instance for testing.</p>
<p>The tomcat instance is running on a Solaris server that I can SSH to. I've looked at using Capistrano, but there doesn't seem to be a lot out there about using it to deploy to Tomcat, or even about running it under JRuby, and I keep hitting bugs in Capistrano due to the Windows/JRuby environment my PC is running (yeah, it's corporate - not my choice, but I've got to live with it).</p>
<p>I'm using warble to build the .war file, and the app deploys and runs fine once I manually copy it up and deploy it. I'm wanting something easier and more automated to actually get it there.</p>
<p>Anyone done this before? Documentation on the web seems pretty thin.</p>
|
<p>I am running a Rails project using JRuby and deploying to a Tomcat server. I have chosen to deploy with Capistrano because it automates just about everything. I had to make a few minor modifications to Capistrano's deployment lifecycle in order to get it to run on Tomcat:</p>
<p>Step 1: I created a warble task to be run on the server after Capistrano updates the code:</p>
<pre><code>desc "Run the warble command to deploy the site"
namespace(:deploy) do
task :warble do
run ". ~/.profile;cd #{release_path};warble"
end
end
</code></pre>
<p>And hooked it into Capistrano lifecycle using:</p>
<pre><code>after 'deploy:update_code', 'deploy:warble'
</code></pre>
<p>My Tomcat server has a symlink pointing to the <code>#{release_path}/tmp/war</code> directory created by warble. If you don't like this, you can easily modify the warble task to move the war file into the Tomcat directory instead.</p>
<p>Step 2: I overrode the <code>deploy:start</code> and <code>deploy:stop</code> tasks so that they kick off the Tomcat server instead of a Mongrel server:</p>
<pre><code>desc "Starts the Tomcat Server"
namespace(:deploy) do
task :start do
sudo "#{tomcat_home}/bin/startup.sh"
end
end
desc "Shutdown the Tomcat Server"
namespace(:deploy) do
task :stop do
sudo "#{tomcat_home}/bin/shutdown.sh"
end
end
</code></pre>
<p>I run Capistrano tasks using MRI rather than the JRuby interpreter.</p>
|
<p>There's a few Capistrano recipes for deploying to Tomcat -- I built one into a gem called <a href="http://rubygems.org/gems/capistrano-tomcat" rel="nofollow">capistrano-tomcat</a>. It takes a WAR you've built (probably with <a href="http://caldersphere.rubyforge.org/warbler/" rel="nofollow">Warbler</a>) and deploys and starts a Tomcat instance on a remote server.</p>
<p>The source is up on Github: <a href="http://github.com/rhunter/capistrano-tomcat" rel="nofollow">http://github.com/rhunter/capistrano-tomcat</a></p>
| 17,782
|
<p>I'm documenting the procedure for a full redeploy on my development server. Small staff, using Basic authentication (over SSL, of course) with an htpasswd file backend.</p>
<p>Is it safe to transfer the .htpasswd file as-is?</p>
<p>The Operating Systems will potentially differ, but the software on top (ie. Apache) will be the same.</p>
|
<p>It's safe to transfer the htpasswd file no matter what architectures you are on. It is a text file. The only case in which you might need to do some conversions is to deal with line endings if you were moving between Unix and Windows, but between Linux/Unix boxes, no problems.</p>
|
<p>If you use the same apache version you shouldn't have any problems just copying the .htpasswd files: They just contain the hashes that people's passwords are being compared with and the hashing is always the same (or it wouldn't work on any machine ;))</p>
| 32,963
|
<p>What function can I use in Excel VBA to slice an array?</p>
|
<blockquote>
<p><strong>Application.WorksheetFunction.Index(array, row, column)</strong></p>
</blockquote>
<p>If you specify a zero value for row or column, then you'll get the entire column or row that is specified.</p>
<p>Example:</p>
<blockquote>
<p>Application.WorksheetFunction.Index(array, 0, 3)</p>
</blockquote>
<p>This will give you the entire 3rd column.</p>
<p>If you specify both row and column as non-zero, then you'll get only the specific element.
There is no easy way to get a smaller slice than a complete row or column.</p>
<p><strong>Limitation</strong>: There is a limit to the array size that <code>WorksheetFunction.Index</code> can handle if you're using a newer version of Excel. If <code>array</code> has more than 65,536 rows or 65,536 columns, then it throws a "Type mismatch" error. If this is an issue for you, then see <a href="https://stackoverflow.com/a/24843721/119775">this more complicated answer</a> which is not subject to the same limitation.</p>
<p>Here's the function I wrote to do all my 1D and 2D slicing:</p>
<pre><code>Public Function GetArraySlice2D(Sarray As Variant, Stype As String, Sindex As Integer, Sstart As Integer, Sfinish As Integer) As Variant
' this function returns a slice of an array, Stype is either row or column
' Sstart is beginning of slice, Sfinish is end of slice (Sfinish = 0 means entire
' row or column is taken), Sindex is the row or column to be sliced
' (NOTE: 1 is always the first row or first column)
' an Sindex value of 0 means that the array is one dimensional 3/20/09 ljr
Dim vtemp() As Variant
Dim i As Integer
On Err GoTo ErrHandler
Select Case Sindex
Case 0
If Sfinish - Sstart = UBound(Sarray) - LBound(Sarray) Then
vtemp = Sarray
Else
ReDim vtemp(1 To Sfinish - Sstart + 1)
For i = 1 To Sfinish - Sstart + 1
vtemp(i) = Sarray(i + Sstart - 1)
Next i
End If
Case Else
Select Case Stype
Case "row"
If Sfinish = 0 Or (Sstart = LBound(Sarray, 2) And Sfinish = UBound(Sarray, 2)) Then
vtemp = Application.WorksheetFunction.Index(Sarray, Sindex, 0)
Else
ReDim vtemp(1 To Sfinish - Sstart + 1)
For i = 1 To Sfinish - Sstart + 1
vtemp(i) = Sarray(Sindex, i + Sstart - 1)
Next i
End If
Case "column"
If Sfinish = 0 Or (Sstart = LBound(Sarray, 1) And Sfinish = UBound(Sarray, 1)) Then
vtemp = Application.WorksheetFunction.Index(Sarray, 0, Sindex)
Else
ReDim vtemp(1 To Sfinish - Sstart + 1)
For i = 1 To Sfinish - Sstart + 1
vtemp(i) = Sarray(i + Sstart - 1, Sindex)
Next i
End If
End Select
End Select
GetArraySlice2D = vtemp
Exit Function
ErrHandler:
Dim M As Integer
M = MsgBox("Bad Array Input", vbOKOnly, "GetArraySlice2D")
End Function
</code></pre>
|
<p>You can use a combination of the Rows, Columns, Offset and Resize properties to get a subset of a range.</p>
<p>For example if you have a range that is 5 columns by 3 rows:</p>
<pre><code>Set rng = Range("A1:E3")
</code></pre>
<p>You can get any subset by appropriately combining the above properties. For example, if you want to get the rightmost 3 cells on the second row (i.e. "C2:E2" in the above example), you could do something like:</p>
<pre><code> Set rngSubset = rng.Rows(2).Offset(0, rng.Columns.Count - 3).Resize(1, 3)
</code></pre>
<p>You could then wrap this up in a VBA function.</p>
| 21,120
|
<p>I have the following XML document:</p>
<pre><code><projects>
<project>
<name>Shockwave</name>
<language>Ruby</language>
<owner>Brian May</owner>
<state>New</state>
<startDate>31/10/2008 0:00:00</startDate>
</project>
<project>
<name>Other</name>
<language>Erlang</language>
<owner>Takashi Miike</owner>
<state> Canceled </state>
<startDate>07/11/2008 0:00:00</startDate>
</project>
...
</code></pre>
<p>And I'd like to get this from the transformation (XSLT) result:</p>
<pre><code>Shockwave,Ruby,Brian May,New,31/10/2008 0:00:00
Other,Erlang,Takashi Miike,Cancelled,07/11/2008 0:00:00
</code></pre>
<p>Does anyone know the XSLT to achieve this? I'm using .net in case that matters.</p>
|
<p>Found an XML transform stylesheet <a href="https://web.archive.org/web/20160624174014/http://wenzlaff.de/xmltocsv.html" rel="nofollow noreferrer">here</a> (wayback machine link, site itself is in german)</p>
<p>The stylesheet added here could be helpful:</p>
<pre><code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>
<xsl:strip-space elements="*" />
<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>", </xsl:if>
<xsl:if test="position() = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>&#xD;</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.</p>
|
<p>This <code>CsvEscape</code> function is XSLT 1.0 and escapes column values <code>,</code>, <code>"</code>, and newlines like <a href="https://www.rfc-editor.org/rfc/rfc4180" rel="nofollow noreferrer">RFC 4180</a> or Excel. It makes use of the fact that you can recursively call XSLT templates:</p>
<ul>
<li>The template <code>EscapeQuotes</code> replaces all double quotes with 2 double quotes, recursively from the start of the string.</li>
<li>The template <code>CsvEscape</code> checks if the text contains a comma or double quote, and if so surrounds the whole string with a pair of double quotes and calls <code>EscapeQuotes</code> for the string.</li>
</ul>
<p>Example usage: <code>xsltproc xmltocsv.xslt file.xml > file.csv</code></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:template name="EscapeQuotes">
<xsl:param name="value"/>
<xsl:choose>
<xsl:when test="contains($value,'&quot;')">
<xsl:value-of select="substring-before($value,'&quot;')"/>
<xsl:text>&quot;&quot;</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="substring-after($value,'&quot;')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$value"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="CsvEscape">
<xsl:param name="value"/>
<xsl:choose>
<xsl:when test="contains($value,',')">
<xsl:text>&quot;</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="$value"/>
</xsl:call-template>
<xsl:text>&quot;</xsl:text>
</xsl:when>
<xsl:when test="contains($value,'&#xA;')">
<xsl:text>&quot;</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="$value"/>
</xsl:call-template>
<xsl:text>&quot;</xsl:text>
</xsl:when>
<xsl:when test="contains($value,'&quot;')">
<xsl:text>&quot;</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="$value"/>
</xsl:call-template>
<xsl:text>&quot;</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$value"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="/">
<xsl:text>project,name,language,owner,state,startDate</xsl:text>
<xsl:text>&#xA;</xsl:text>
<xsl:for-each select="projects/project">
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(name)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(language)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(owner)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(state)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(startDate)"/></xsl:call-template>
<xsl:text>&#xA;</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code></pre>
| 47,694
|
<p>About 2 years ago I dropped windows from my home PC and switched 100% to linux (fedora, then ubuntu) - The missus wasn't too happy but she got used to it and learned a thing or two. Then about 6 months ago I got myself a shiny new Macbook and since moving to OSX have never looked back; Unfortunately I've not been successful in getting my employer to buy me one for work (and I can't be carrying mine back and forth) so I have to "put up" with windows.</p>
<p>I started out with windows over 8 years ago so I have a really good understanding of how it works and have done my fair share of Win32/MFC/.NET development.</p>
<p>My question is; Who else has to use a windows box at work (and have a mac at home) And how do you cope - what windows apps/configurations do they use that let them work in a similar fashion to OSX? - I was just thinking how cool it would be if I could get some sort of keymapping app that re-mapped my windows keys to the OSX variants (Apple+W, Apple+Q, Apple+Left, Apple+Right, etc etc).</p>
<p>I miss expose (TopDesk is nice but not free)...
I miss the simplicity of finder...
I miss the nice smooth dialogs and windows and shadows (YzShadow can juuuuust cope)
I miss the underlying unix framework (I run andLinux at work)
I miss OSX :(</p>
<p>Unfortunately 90% of our clients use IE so windows is a must; They also can't justify the expense of a mac for a developer; Especially a Mac Pro :-p</p>
<p>Ah well.</p>
|
<p>Operating System is just a tool, if you are building cross platform applications (or web applications[it depends only your target web browser]) and you can use whatever operating system you like , you can install windows xp in virtual machine on your osx for using IE for example, <strong>but</strong> if your company forces you to login on their domain controller, using outlook for email and task management that project manager assigns to you, this is different story. As you mentioned multiple operating systems at work and home, personally I use Linux at home but I use Windows at work because in my day to day job I write a lot of C# .NET code but at home I spend time by programming with open source technologies and I use it because I've used Linux since October 2001. So try to get used to it.</p>
|
<p>As a software developer I pretty much live in my text editor and shell. In the jobs where I've been forced to use windows I install emacs and cygwin and I'm off to the races. </p>
<p>I don't focus on the periphery -- control panels, window managers, etc -- I focus on what I really use 90+% of the time and don't sweat the rest. </p>
| 28,384
|
<p>I've written a small hello world test app in Silverlight which i want to host on a Linux/Apache2 server. I want the data to come from MySQL (or some other linux compatible db) so that I can databind to things in the db.</p>
<p>I've managed to get it working by using the <a href="http://www.mysql.com/products/connector/net/" rel="nofollow noreferrer">MySQL Connector/.NET</a>:</p>
<pre><code>MySqlConnection conn = new MySqlConnection("Server=the.server.com;Database=theDb;User=myUser;Password=myPassword;");
conn.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM test;", conn);
using (MySqlDataReader reader = command.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
sb.AppendLine(reader.GetString("myColumn"));
}
this.txtResults.Text = sb.ToString();
}
</code></pre>
<p>This works fine if I give the published ClickOnce app full trust (or at least SocketPermission) and <strong>run it locally</strong>. </p>
<p>I want this to run on the server and I can't get it to work, always ending up with permission exception (SocketPermission is not allowed).</p>
<p>The database is hosted on the same server as the silverlight app if that makes any difference.</p>
<p><strong>EDIT</strong>
Ok, I now understand why it's a bad idea to have db credentials in the client app (obviously). How do people do this then? How do you secure the proxy web service so that it relays data to and from the client/db in a secure way? Are there any examples out there on the web?</p>
<p>Surely, I cannot be the first person who'd like to use a database to power a silverlight application?</p>
|
<p>The easiest way to do what you want (having read through your edits now :)) will be to expose services that can be consumed. The pattern that Microsoft is REALLY pushing right now is to expose WCF services, but the truth is that your Silverlight client can use WCF to consume a lot of different types of services.</p>
<p>What may be easiest for you to do right now would be to use a .NET service on a web server or maybe a PHP REST service, and then point your Silverlight app at that service. By doing so, you're protecting your database not only from people snooping through it, but more importantly, you're restricting what people can do to your database. If your data is supposed to be read-only, and your service's contract only allows reading operations, you're set. Alternatively, your service may negotiate sessions with credentials, again, set up through WCF.</p>
<p>WCF can be a client-only, server-only, or client-server connector platform. What you choose will affect the code you write, but it's all going to be independent of your database. Your code can be structured such that it's a one-to-one mapping to your database table, or it can be far more abstract (you can set up classes that represent full logical views if you choose).</p>
|
<p>You can get data from MySQL by using Web Services.</p>
<p>Walkthrough:</p>
<p>Step 1: Create Web Services</p>
<p>Step 2: Add Service Reference to Silverlight</p>
<p><hr />
<b>Step 1: Create Web Services</b></p>
<p>Add a new Silverlight project.</p>
<p><img src="https://i.stack.imgur.com/ccdis.png" alt="Add a new Silverlight project"></p>
<p>Create a new Web Service. Right click on the web project > Add > New Item</p>
<p><img src="https://i.stack.imgur.com/mlYL2.png" alt="Create a new Web Service"></p>
<p>Select "Web Service".</p>
<p><img src="https://i.stack.imgur.com/dZyyu.png" alt="enter image description here"></p>
<p>Initial code of a new Web Service.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
namespace SilverlightApplication1.Web
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
</code></pre>
<p>In order for the Web Service able to connect to MySQL, we need to add a reference of MySql.Data.DLL into the web project and add the Using statement at top of the Web Service class:</p>
<pre><code>using MySql.Data.MySqlClient;
</code></pre>
<p><strong>HelloWorld()</strong> is an initial sample method created by Visual Studio. You may want to delete it as it is not needed. I'm going to create 2 simple method to demonstrate how Web Services are used to communicate between SilverLight and MySQL.</p>
<p>First method: <strong>ExecuteScalar()</strong></p>
<p>This method is simple. Get a single object from MySQL.</p>
<pre><code>public string ExecuteScalar(string sql)
{
try
{
string result = "";
using (MySqlConnection conn = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sql;
result = cmd.ExecuteScalar() + "";
conn.Close();
}
}
return result;
}
catch (Exception ex)
{
return ex.Message;
}
}
</code></pre>
<p>Second method: <strong>ExecuteNonQuery()</strong></p>
<p>For single SQL execution. Example of SQL type: INSERT, UPDATE, DELETE.</p>
<pre><code>public string ExecuteNonQuery(string sql)
{
try
{
long i = 0;
using (MySqlConnection conn = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sql;
i = cmd.ExecuteNonQuery();
conn.Close();
}
}
return i + " row(s) affected by the last command, no resultset returned.";
}
catch (Exception ex)
{
return ex.Message;
}
}
</code></pre>
<p>This is how the Web Service looks like after adding the two methods above:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using MySql.Data.MySqlClient;
namespace SilverlightApplication1.Web
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService
{
string constr = "server=localhost;user=root;pwd=1234;database=test;";
[WebMethod]
public string ExecuteScalar(string sql)
{
try
{
string result = "";
using (MySqlConnection conn = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sql;
result = cmd.ExecuteScalar() + "";
conn.Close();
}
}
return result;
}
catch (Exception ex)
{
return ex.Message;
}
}
[WebMethod]
public string ExecuteNonQuery(string sql)
{
try
{
long i = 0;
using (MySqlConnection conn = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sql;
i = cmd.ExecuteNonQuery();
conn.Close();
}
}
return i + " row(s) affected by the last command, no resultset returned.";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}
</code></pre>
<p>You will notice that an attribute of <strong>[WebMethod]</strong> is added to the methods.</p>
<p>Rebuild the project and let the Web Service be ready for next step.</p>
<p><img src="https://i.stack.imgur.com/sQbIk.png" alt="Rebuild the project"></p>
<p><em>Web Service Access Permission</em></p>
<p>Please note that, by default, Web Service only allow those Silverlight that is hosted at the same domain with the Web Service to access. If the Silverlight application is hosted on another website/domain, Web Service will deny the communication. Therefore we have to configure the permission for the Web Service to be accessed by Silverlight which is hosted at different domain.</p>
<p>You have to create two additional files: <em>clientaccesspolicy.xml</em> and <em>crossdomain.xml</em>.</p>
<p>These files has to be put at the root of the domain where the Web Services are hosted.</p>
<p>Example: <code><a href="http://www.mywebsite.com/clientaccesspolicy.xml" rel="nofollow noreferrer">http://www.mywebsite.com/clientaccesspolicy.xml</a></code> and <code><a href="http://www.mywebsite.com/crossdomain.xml" rel="nofollow noreferrer">http://www.mywebsite.com/crossdomain.xml</a></code></p>
<p><em>clientaccesspolicy.xml</em></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="SOAPAction">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
</code></pre>
<p>If you only want to allow the Web Service to be accessed by specific domain (example: www.myanotherwebsite.com), you can add it within . Example:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="SOAPAction">
<domain uri="http://www.myanotherwebsite.com"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
</code></pre>
<p><em>crossdomain.xml</em></p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE cross-domain-policy SYSTEM
"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>
</cross-domain-policy>
</code></pre>
<p>To understand more about this, please read: <a href="http://msdn.microsoft.com/en-us/library/cc197955%28v=vs.95%29.aspx" rel="nofollow noreferrer">Making a Service Available Across Domain Boundaries (MSDN)</a></p>
<hr />
<p><strong>Step 2: Add Service Reference to Silverlight</strong></p>
<p>Add a Service Reference to Silverlight.</p>
<p><img src="https://i.stack.imgur.com/Ezrkn.png" alt="Add a Service Reference to Silverlight"></p>
<p>Type the address of the Web Service and press [Go].</p>
<p>Example of address: <a href="http://www.mywebsite.com/MyCoolWebService.asmx" rel="nofollow noreferrer">http://www.mywebsite.com/MyCoolWebService.asmx</a></p>
<p>Change the Namespace to your favor, and press [OK].</p>
<p><img src="https://i.stack.imgur.com/wPGCl.png" alt="Web Service Browser"></p>
<p>Visual Studio will analyze the Web Service, do the data binding and create a class.</p>
<p>Before continue coding, let's us see what methods that we can use in the new created class. Right click the new class and select [View in Object Browser].</p>
<p><img src="https://i.stack.imgur.com/3VECS.png" alt="View in Object Browser"></p>
<p>The class that we are going to use is WebService1SoapClient (in this example). The naming is based on the Service name. If we name our service class as MyCoolWebService, then MyCoolWebServiceSoapClient will be chosen as the name of the class in Silverlight. At the right panel, two methods and two events are highlighted. Those are the methods used to call the Web Services.</p>
<p><img src="https://i.stack.imgur.com/RoH50.png" alt="Object of WebService1SoapClient"></p>
<p>Lets create a simple Silverlight application by adding a Textbox and two Buttons.</p>
<p>In this example, user will key in SQL query directly into the Textbox.</p>
<p>Button of [ExecuteScalar] will send the SQL to the Web Service and retrieve data back. (SELECT, SHOW, etc.)</p>
<p>Button of [ExecuteNonQuery] will send the SQL to the Web Service for execution only. (INSERT, UPDATE, DELETE, etc.)</p>
<p><img src="https://i.stack.imgur.com/vbZ1g.png" alt="Design a simple SilverLight App"></p>
<p>This is the initial code behind of MainPage.xaml:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication1
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void btExecuteScalar_Click(object sender, RoutedEventArgs e)
{
}
private void btExecuteNonQuery_Click(object sender, RoutedEventArgs e)
{
}
}
}
</code></pre>
<p>Now, these are what we are going to do here:</p>
<ul>
<li>Declare the service as static object at class level:
ServiceReference1.WebService1SoapClient </li>
<li>Create the service completed event of the two methods. </li>
<li>Call the service in the event of button click. </li>
<li>Display the service result: MessageBox.Show()</li>
</ul>
<p><br /></p>
<pre><code>public partial class MainPage : UserControl
{
ServiceReference1.WebService1SoapClient myService;
public MainPage()
{
InitializeComponent();
myService = new ServiceReference1.WebService1SoapClient();
myService.ExecuteScalarCompleted += myService_ExecuteScalarCompleted;
myService.ExecuteNonQueryCompleted += myService_ExecuteNonQueryCompleted;
}
void myService_ExecuteNonQueryCompleted(object sender,
ServiceReference1.ExecuteNonQueryCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
void myService_ExecuteScalarCompleted(object sender,
ServiceReference1.ExecuteScalarCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
private void btExecuteScalar_Click(object sender, RoutedEventArgs e)
{
myService.ExecuteScalarAsync(textBox1.Text);
}
private void btExecuteNonQuery_Click(object sender, RoutedEventArgs e)
{
myService.ExecuteNonQueryAsync(textBox1.Text);
}
}
</code></pre>
<p>Press [F5], run and test the Silverlight application.</p>
<p><img src="https://i.stack.imgur.com/E1YNH.png" alt="Testing"></p>
<p><img src="https://i.stack.imgur.com/U8dUW.png" alt="Testing"></p>
<p><img src="https://i.stack.imgur.com/JP2qO.png" alt="Testing"></p>
<p>Together with your creativity, I believe you can do something more than this for now Smile | :)</p>
<p>If you have done any changes to the Web Service, maybe you added new Service (new web methods), you have to update the Service Reference at Silverlight to re-bind the Services. You might want to update the Web Service address, if you uploaded the files to a different web hosting.</p>
<p><img src="https://i.stack.imgur.com/RtGb3.png" alt="update the Service Reference"></p>
<p>Happy coding.</p>
<p>Read More:</p>
<ol>
<li><a href="http://www.codeproject.com/Articles/633789/Connecting-MySQL-From-SilverLight-With-Web-Service" rel="nofollow noreferrer">Original Post - Connecting MySQL From SilverLight With Web Services - CodeProject.com (written by me)</a><br /></li>
<li><a href="http://www.codeproject.com/Articles/263087/Access-a-Web-Service-from-a-Silverlight-Applicatio" rel="nofollow noreferrer">Access a Web Service from a Silverlight Application</a><br /></li>
<li><a href="http://support.microsoft.com/kb/308359" rel="nofollow noreferrer">HOW TO: Write a Simple Web Service by Using Visual C# .NET</a><br /></li>
<li><a href="http://msdn.microsoft.com/en-us/library/cc197940%28v=vs.95%29.aspx" rel="nofollow noreferrer">How to: Build a Service for Silverlight Clients</a></li>
</ol>
| 12,531
|
<p>Given a list of locations such as</p>
<pre class="lang-html prettyprint-override"><code> <td>El Cerrito, CA</td>
<td>Corvallis, OR</td>
<td>Morganton, NC</td>
<td>New York, NY</td>
<td>San Diego, CA</td>
</code></pre>
<p>What's the easiest way to generate a Google Map with pushpins for each location?</p>
|
<p>I'm assuming you have the basics for Maps in your code already with your API Key.</p>
<pre><code><head>
<script
type="text/javascript"
href="http://maps.google.com/maps?
file=api&v=2&key=xxxxx">
function createMap() {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.44, -122.14), 14);
}
</script>
</head>
<body onload="createMap()" onunload="GUnload()">
</code></pre>
<p>Everything in Google Maps is based off of latitude (lat) and longitude (lng).<br />
So to create a simple marker you will just create a GMarker with the lat and lng.</p>
<pre><code>var where = new GLatLng(37.925243,-122.307358); //Lat and Lng for El Cerrito, CA
var marker = new GMarker(where); // Create marker (Pinhead thingy)
map.setCenter(where); // Center map on marker
map.addOverlay(marker); // Add marker to map
</code></pre>
<p>However if you don't want to look up the Lat and Lng for each city you can use Google's Geo Coder. Heres an example:</p>
<pre><code>var address = "El Cerrito, CA";
var geocoder = new GClientGeocoder;
geocoder.getLatLng(address, function(point) {
if (point) {
map.clearOverlays(); // Clear all markers
map.addOverlay(new GMarker(point)); // Add marker to map
map.setCenter(point, 10); // Center and zoom map on marker
}
});
</code></pre>
<p>So I would just create an array of GLatLng's of every city from the GeoCoder and then draw them on the map.</p>
|
<p>I guess more information would be needed to really give you an answer, but over at Django Pluggables there is a <a href="http://djangoplugables.com/projects/django-googlemap/" rel="nofollow noreferrer">django-googlemap plugin</a> that might be of help.</p>
<p><strong>Edit:</strong> Adam has a much better answer. When it doubt look at the API examples. </p>
| 3,606
|
<p>I'd like know what people think about using RAISERROR in stored procedures to pass back user messages (i.e. business related messages, not error messages) to the application. </p>
<p>Some of the senior developers in my firm have been using this method and catching the SqlException in our C# code to pick up the messages and display them to the user. I am not happy with this method and would like to know how other people deal with these types of user messages from stored procs.</p>
|
<p>I've done this, but it was usually to pass along business "error" messages, essentially a data configuration had to be in place that couldn't be enforced with standard FK constraints for whatever reason.</p>
<p>If they are actually "errors", I don't have much of a problem with it. If it's inserting a record and using RAISERROR to throw ("You have successfully registered for XYZ!"), then you've got a problem. If that was the case, I'd probably come up with a team/department/company development standard for using out parameters.</p>
|
<p>If it can't be checked/caught earlier it might be difficult to do anything else. </p>
<p>I've had to write a raiseerror in a procedure I wrote and used as a constraint on inserting/updating a table because it was the 'last stop' for the data and I had to check it there. </p>
<p>I think in general if you are getting errors back from the DB.. its a pain in the butt and harder to give 'nice' feedback to the user without a lot of effort, but sometimes you just don't know until you insert/update :P</p>
| 11,381
|
<p>I am told that good developers can spot/utilize the difference between <code>Null</code> and <code>False</code> and <code>0</code> and all the other good "nothing" entities.<br>
What <em>is</em> the difference, specifically in PHP? Does it have something to do with <code>===</code>?</p>
|
<h2>It's language specific, but in PHP :</h2>
<p><strong><code>Null</code></strong> means "<strong>nothing</strong>". The var has not been initialized.</p>
<p><strong><code>False</code></strong> means "<strong>not true in a boolean context</strong>". Used to explicitly show you are dealing with logical issues.</p>
<p><strong><code>0</code></strong> is an <strong><code>int</code></strong>. Nothing to do with the rest above, used for mathematics.</p>
<p>Now, what is tricky, it's that in dynamic languages like PHP, <em>all of them have a value in a boolean context</em>, which (in PHP) is <code>False</code>.</p>
<p>If you test it with <code>==</code>, it's testing the boolean value, so you will get equality. If you test it with <code>===</code>, it will test the type, and you will get inequality.</p>
<h2>So why are they useful ?</h2>
<p>Well, look at the <code>strrpos()</code> function. It returns False if it did not found anything, but 0 if it has found something at the beginning of the string !</p>
<pre><code><?php
// pitfall :
if (strrpos("Hello World", "Hello")) {
// never exectuted
}
// smart move :
if (strrpos("Hello World", "Hello") !== False) {
// that works !
}
?>
</code></pre>
<p>And of course, if you deal with states:</p>
<p>You want to make a difference between <code>DebugMode = False</code> (set to off), <code>DebugMode = True</code> (set to on) and <code>DebugMode = Null</code> (not set at all, will lead to hard debugging ;-)).</p>
|
<p>The issues with falsyness comes from the PHP history. The problem targets the not well defined scalar type.</p>
<pre><code>'*' == true -> true (string match)
'*' === true -> false (numberic match)
(int)'*' == true -> false
(string)'*' == true -> true
</code></pre>
<p>PHP7 strictness is a step forward, but maybe not enough. <a href="https://web-techno.net/typing-with-php-7-what-you-shouldnt-do/" rel="nofollow noreferrer">https://web-techno.net/typing-with-php-7-what-you-shouldnt-do/</a></p>
| 16,630
|
<p>We are currently testing a Java Swing application for it's performance. I wonder if there is a good tool to automate this?</p>
|
<p>A few years ago I used <a href="http://jakarta.apache.org/jmeter/" rel="nofollow noreferrer">JMeter</a> for such a task. I generally enjoyed using it, though I never did much research on what else is available and I don't know if it's still actively developed.</p>
|
<p>The Pragmatic Programmers also came out with a <a href="https://rads.stackoverflow.com/amzn/click/com/1934356182" rel="nofollow noreferrer" rel="nofollow noreferrer">book</a> on using Ruby to do GUI testing.</p>
<p>In particular, they give extensive examples using JRuby to test a swing app. </p>
<p>The testing they are doing is mostly to test functionality, but I think it would not be hard to add in some performance measures. </p>
<p>The benefit of doing it this way is that you get lots of flexibility, but it is not a packaged tool. </p>
| 11,813
|
<p>I've seen people doing things like this in their HTML:</p>
<pre><code><!--[if IE]>
<link rel="stylesheet" href="ie.css" type="text/css" />
<![endif]-->
</code></pre>
<p>Does this work across all modern browsers and is there a list of browser types that will work with that kind of if statement?</p>
<p><strong>Edit</strong></p>
<p>Thanks <a href="https://stackoverflow.com/questions/46124/is-there-a-list-of-browser-conditionals-for-use-including-stylesheets#46126">Ross</a>. Interesting to find out about <strong>gt, lt, gte, & lte</strong>.</p>
|
<p>This works across all browsers because anything except IE sees <code><!--IGNORED COMMENT--></code>. Only IE reads the comment if it contains a conditional clause. Have a look at <a href="http://www.quirksmode.org/css/condcom.html" rel="noreferrer">this article</a></p>
<p>You can also specify which version of IE. For example:</p>
<pre><code><!--[if IE 8]>
<link rel="stylesheet type="text/css" href="ie8.css" />
<![endif]-->
</code></pre>
|
<p>Further to Ross' answer, you can only target the Internet Explorer rendering engine with conditional comments; there is no similar construct for other browsers. For example, you can't write conditional comments that target Firefox, but are ignored by Internet Explorer. </p>
<p>The way I achieve the same effect as your example above is to sniff the user agent string. I then deliver a suitable CSS file for that browser. This isn't perfect because sometimes people change their user-agent string for compatibility. </p>
<p>The other way to target different browsers is to utilise browser specific hacks. These are particularly nasty because they usually rely on bugs in the browser and bugs are liable to be fixed!</p>
<p>User-agent sniffing is the best all-round solution in my opinion.</p>
| 6,814
|
<p>Is there some way to do multi-threading in JavaScript?</p>
|
<p>See <a href="http://caniuse.com/#search=worker" rel="nofollow noreferrer">http://caniuse.com/#search=worker</a> for the most up-to-date support info.</p>
<p>The following was the state of support circa 2009.</p>
<hr />
<p>The words you want to google for are <a href="http://www.google.com/search?q=JavaScript+worker+threads" rel="nofollow noreferrer">JavaScript Worker Threads</a></p>
<p>Apart from from <a href="http://gears.google.com/" rel="nofollow noreferrer">Gears</a> there's nothing available right now, but there's plenty of talk about how to implement this so I guess watch this question as the answer will no doubt change in future.</p>
<p>Here's the relevant documentation for Gears: <a href="http://code.google.com/apis/gears/api_workerpool.html" rel="nofollow noreferrer">WorkerPool API</a></p>
<p>WHATWG has a Draft Recommendation for worker threads: <a href="http://www.whatwg.org/specs/web-workers/current-work/" rel="nofollow noreferrer">Web Workers</a></p>
<p>And there's also Mozilla’s <a href="https://wiki.mozilla.org/DOMWorkerThreads" rel="nofollow noreferrer">DOM Worker Threads</a></p>
<hr />
<p><strong>Update:</strong> June 2009, current state of browser support for JavaScript threads</p>
<p><strong>Firefox 3.5</strong> has web workers. Some demos of web workers, if you want to see them in action:</p>
<ul>
<li><a href="http://blog.mozbox.org/post/2009/04/10/Web-Workers-in-action" rel="nofollow noreferrer">Simulated Annealing</a> ("Try it" link)</li>
<li><a href="https://web.archive.org/web/20120406122342/https://developer.mozilla.org/web-tech/2008/12/04/web-workers-part-2" rel="nofollow noreferrer">Space Invaders</a> (link at end of post)</li>
<li><a href="http://www.yafla.com/dforbes/Web_Workers_and_You__A_Faster_More_Powerful_JavaScript_World" rel="nofollow noreferrer">MoonBat JavaScript Benchmark</a> (first link)</li>
</ul>
<p>The Gears plugin can also be installed in Firefox.</p>
<p><strong>Safari 4</strong>, and the <strong>WebKit nightlies</strong> have worker threads:</p>
<ul>
<li><a href="http://blog.owensperformance.com/2009/02/safari-4-worker-threads-javascript-domination/" rel="nofollow noreferrer">JavaScript Ray Tracer</a></li>
</ul>
<p><strong>Chrome</strong> has Gears baked in, so it can do threads, although it requires a confirmation prompt from the user (and it uses a different API to web workers, although it will work in any browser with the Gears plugin installed):</p>
<ul>
<li><a href="http://code.google.com/apis/gears/samples/hello_world_workerpool/hello_world_workerpool.html" rel="nofollow noreferrer">Google Gears WorkerPool Demo</a> (not a good example as it runs too fast to test in Chrome and Firefox, although IE runs it slow enough to see it blocking interaction)</li>
</ul>
<p><strong>IE8</strong> and <strong>IE9</strong> can only do threads with the Gears plugin installed</p>
|
<p>With HTML5 <a href="https://www.w3.org/TR/workers/" rel="nofollow noreferrer">specification</a> you do not need to write too much JS for the same or find some hacks.</p>
<p>One of the feature introduced in HTML5 is <a href="http://www.w3schools.com/html/html5_webworkers.asp" rel="nofollow noreferrer">Web Workers</a> which is JavaScript running in the background,independently of other scripts, without affecting the performance of the page. </p>
<p>It is supported in almost all browsers : </p>
<p>Chrome - 4.0+ </p>
<p>IE - 10.0+</p>
<p>Mozilla - 3.5+</p>
<p>Safari - 4.0+</p>
<p>Opera - 11.5+</p>
| 4,988
|
<p>How can I set a custom background color of a button? </p>
<p>Interface Builder doesn't seem to have an interface to do this. </p>
<p>Is it only available programmatically?
If so, can you provide an example, please?</p>
|
<p>I found that I needed to use a stretchable image to accomplish this. Apple's UICatalog example has one or more colored buttons that are drawn in this fashion. You could use their template image and recolor it to suit your button needs.</p>
<p>I'm not sure about doing this in Interface Builder, but I was able to create a button and use an image for its contents using the following code: </p>
<pre><code>downloadButton = [[UIButton alloc] initWithFrame:CGRectMake(36, 212, 247, 37)];
downloadButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
downloadButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[downloadButton setTitle:NSLocalizedStringFromTable(@"Download", @"Localized", nil) forState:UIControlStateNormal];
[downloadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[downloadButton setFont:[UIFont boldSystemFontOfSize:14.0]];
UIImage *newImage = [[UIImage imageNamed:@"greenButton.png"] stretchableImageWithLeftCapWidth:12.0f topCapHeight:0.0f];
[downloadButton setBackgroundImage:newImage forState:UIControlStateNormal];
[downloadButton addTarget:self action:@selector(downloadNewItem) forControlEvents:UIControlEventTouchDown];
downloadButton.backgroundColor = [UIColor clearColor];
[downloadDisplayView addSubview:downloadButton];
</code></pre>
|
<p>May be I misunderstood your question, but does below not work for you?</p>
<p><img src="https://i.stack.imgur.com/I7i5W.png" alt=""></p>
| 48,727
|
<p>I'm using RichFaces per a client requirement, but the markup it (and the stock JSF controls) generates is an awful mess of nested tables. Are there any control libraries out there that generate nicer markup? AJAX support is a huge plus!</p>
|
<p>There is ICEFaces which provides more semantic support than RichFaces .Also you can try Nitobi suite which also provides similar kinda solution.If you are not satisfied with any of these I suggest try to write your own part extending the Sun faces</p>
|
<p>Short answer: No I have not yet found one.
Your options include using less complicated controls and know what html the standard controls emit. Thing like h:panelGrid render as a table. There is nothing stopping you writing your own rendering family which produces more standards compliment html, but this would be a big time investment.
As for using RichFaces if you stick more to the a4j: namespace of tags you will still be getting the cross browser ajax with out all the mark up you don't like.</p>
| 8,896
|
<p>Our rails app is designed as a single code base linking to multiple client databases. Based on the subdomain the app determines which db to connect to.</p>
<p>We use liquid templates to customise the presentation for each client. We are unable to customise the generic 'We're Sorry, somethign went wrong..' message for each client.</p>
<p>Can anyone recommend an approach that would allow us to do this.</p>
<p>Thanks</p>
<p>DOm</p>
|
<p>For catching exceptions in Rails 2, <code>rescue_from</code> controller method is a great way to specify actions which handle various cases.</p>
<pre><code>class ApplicationController < ActionController::Base
rescue_from MyAppError, :with => :show_errors
def show_errors
render :action => "..."
end
end
</code></pre>
<p>This way you can make dynamic error pages to replace the static "public/500.html" page.</p>
|
<p>It's not clear if you're trying to do inline error messaging or new page error messaging, but if you want to improve the text around inline error messaging, <a href="http://www.softiesonrails.com/2008/4/23/better-messages-for-activerecord-validation-errors" rel="nofollow noreferrer">this post</a> provides good information.</p>
| 12,633
|
<p>Are there any other IDEs worth my time for Lotus Notes development? We're doing mostly LotusScript development and would kill for features of Eclipse or Visual Studio, like "Show Declaration". I know there's <a href="http://www.ibm.com/developerworks/lotus/library/notes-eclipse/" rel="nofollow noreferrer">an Eclipse plugin for Java development in Notes</a>, but seems like it <em>only</em> does Java, and we have too many pieces of legacy code in LotusScript to abandon it.</p>
|
<p>Lotus Notes has moved to the Eclipse platform in version 8. You can run the client in 2 different modes, basic mode which is the version we all know or on the Eclipse platform (know as the standard). The IDE is also moving to eclipse, version 8.5 beta 2 is currently available with the new Eclipse based IDE. Bear in mind that it's a Beta version and it's not feature complete.</p>
|
<p>Teamstudio sell a number of tools to assist your Lotus Notes development, and it looks like they can do some of the things you want, but it doesn't look like they can be assembled into an IDE.</p>
<p><a href="http://www.teamstudio.com/products/product-index.html" rel="nofollow noreferrer">http://www.teamstudio.com/products/product-index.html</a></p>
<p>(Disclosure: I worked for a sister company of Team Studio a number of years back, but never had much to do with their products)</p>
| 16,117
|
<p>I am just getting started with flex and am using the SDK (not Flex Builder). I was wondering what's the best way to compile a mxml file from an ant build script. </p>
|
<p>The Flex SDK ships with a set of ant tasks. More info at:</p>
<p><a href="http://livedocs.adobe.com/flex/3/html/help.html?content=anttasks_1.html" rel="noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=anttasks_1.html</a></p>
<p>Here is an example of compiling Flex SWCs with ant:</p>
<p><a href="http://www.mikechambers.com/blog/2006/05/19/example-using-ant-with-compc-to-compile-swcs/" rel="noreferrer">http://www.mikechambers.com/blog/2006/05/19/example-using-ant-with-compc-to-compile-swcs/</a></p>
<p>mike chambers</p>
|
<p>If you're open to Maven, try the flex-compiler-mojo plugin:</p>
<p><a href="http://code.google.com/p/flex-mojos/" rel="nofollow noreferrer">http://code.google.com/p/flex-mojos/</a></p>
<p>Christiaan</p>
| 10,368
|
<p>Currently I monitoring a particular file with a simple shell one-liner:</p>
<pre><code>filesize=$(ls -lah somefile | awk '{print $5}')
</code></pre>
<p>I'm aware that Perl has some nice modules to deal with Excel files so the idea is to, let's say, run that check daily, perhaps with cron, and write the result on a spreadsheet for further statistical use.</p>
|
<p>You can check the size of the file using the -s operator.</p>
<pre>
use strict;
use warnings;
use File::Slurp qw(read_file write_file);
use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::SaveParser;
use Spreadsheet::WriteExcel;
my $file = 'path_to_file';
my $size_file = 'path_to_file_keeping_the_size';
my $excel_file = 'path_to_excel_file.xls';
my $current_size = -s $file;
my $old_size = 0;
if (-e $size_file) {
$old_size = read_file($size_file);
}
if ($old_size new;
my $excel = $parser->Parse($excel_file);
my $row = 1;
$row++ while $excel->{Worksheet}[0]->{Cells}[$row][0];
$excel->AddCell(0, $row, 0, scalar(localtime));
$excel->AddCell(0, $row, 1, $current_size);
my $workbook = $excel->SaveAs($excel_file);
$workbook->close;
} else {
my $workbook = Spreadsheet::WriteExcel->new($excel_file);
my $worksheet = $workbook->add_worksheet();
$worksheet->write(0, 0, 'Date');
$worksheet->write(0, 1, 'Size');
$worksheet->write(1, 0, scalar(localtime));
$worksheet->write(1, 1, $current_size);
$workbook->close;
}
}
write_file($size_file, $current_size);
</pre>
<p>A simple way to write Excel files would be using
<a href="http://search.cpan.org/dist/Spreadsheet-Write/" rel="noreferrer">Spreadsheet::Write</a>.
but if you need to update an existing Excel file you should look into
<a href="http://search.cpan.org/dist/Spreadsheet-ParseExcel/" rel="noreferrer">Spreadsheet::ParseExcel</a>.</p>
|
<p>The module you should be using is <a href="http://search.cpan.org/~jmcnamara/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm" rel="nofollow noreferrer">Spreadsheet::WriteExcel</a>.</p>
| 9,717
|
<p>Has anyone ever used the <a href="https://www.dofactory.com/net/bridge-design-pattern" rel="nofollow noreferrer">Bridge pattern</a> in a real world application? If so, how did you use it? Is it me, or is it just the <a href="https://www.dofactory.com/net/adapter-design-pattern" rel="nofollow noreferrer">Adapter pattern</a> with a little dependency injection thrown into the mix? Does it really deserve its own pattern?</p>
|
<p>The Bridge pattern is an application of the old advice, "prefer composition over inheritance".
It becomes handy when you must subclass different times in ways that are orthogonal with one another. Say you must implement a hierarchy of colored shapes. You wouldn't subclass Shape with Rectangle and Circle and then subclass Rectangle with RedRectangle, BlueRectangle and GreenRectangle and the same for Circle, would you? You would prefer to say that each Shape <em>has</em> a Color and to implement a hierarchy of colors, and that is the Bridge Pattern. Well, I wouldn't implement a "hierarchy of colors", but you get the idea...</p>
|
<pre><code>Bridge design pattern we can easily understand helping of service and dao layer.
Dao layer -> create common interface for dao layer ->
public interface Dao<T>{
void save(T t);
}
public class AccountDao<Account> implement Dao<Account>{
public void save(Account){
}
}
public LoginDao<Login> implement Dao<Login>{
public void save(Login){
}
}
Service Layer ->
1) interface
public interface BasicService<T>{
void save(T t);
}
concrete implementation of service -
Account service -
public class AccountService<Account> implement BasicService<Account>{
private Dao<Account> accountDao;
public AccountService(AccountDao dao){
this.accountDao=dao;
}
public void save(Account){
accountDao.save(Account);
}
}
login service-
public class LoginService<Login> implement BasicService<Login>{
private Dao<Login> loginDao;
public AccountService(LoginDao dao){
this.loginDao=dao;
}
public void save(Login){
loginDao.save(login);
}
}
public class BridgePattenDemo{
public static void main(String[] str){
BasicService<Account> aService=new AccountService(new AccountDao<Account>());
Account ac=new Account();
aService.save(ac);
}
}
}
</code></pre>
| 41,344
|
<p>i am creating a system. What i want to know is if a msg is unsupported what should it do? should i throw saying unsupported msg? should i return 0 or -1? or should i set an errno (base->errno_). Some messages i wouldnt care if there was an error (such as setBorderColour). Others i would (addText or perhaps save if i create a save cmd).</p>
<p>I want to know what the best method is for 1) coding quickly 2) debugging 3) extending and maintenance. I may make debugging 3rd, its hard to debug ATM but thats bc there is a lot of missing code which i didnt fill in. Actual bugs arent hard to correct. Whats the best way to let the user know there is an error?</p>
<p>The system works something like this but not exactly the same. This is C style and mycode has a bunch of inline functions that wrap settext(const char*text){ to msg(this, esettext, text)</p>
<pre><code>Base base2, base;
base = get_root();
base2 = msg(base, create, BASE_TYPE);
msg(base2, setText, "my text");
const char *p = (const char *)msg(base2, getText);
</code></pre>
|
<p>Generally if it's C++, prefer exceptions unless performance is critical or unless you may be running in an environment (e.g. an embedded platform) that does not support exceptions. Exceptions are by far the best choice for debugging because they are very noticeable when they occur and are ignored. Further, exceptions are self-documenting. They have their own type name and usually a contained message that explains the error. Return codes and errno require separate code definitions and some kind of out-of-band way of communicating what the codes mean in any given context (e.g. man pages, comments).</p>
<p>For coding quickly, return codes are probably easier since they don't involve potentially defining your own exception types, and often the error checking code is not as verbose as with exceptions. But of course the big risk is that it is much easier to silently ignore error return codes, leading to problems that may not be noticed until well after they occur, making debugging and maintenance a nightmare.</p>
<p>Try to avoid ever using errno, since it's very error-prone itself. It's a global, so you never know who is resetting it, and it is most definitively <em>not</em> thread safe.</p>
<p><strong>Edit:</strong> I just realized you meant an errno member variable and not the C-style errno. That's better in that it's not global, but you still need additional constructs to make it thread safe (if your app is multi-threaded), and it retains all the problems of a return code.</p>
|
<p>Personally when it comes to output graphics, I feel a silent fail is fine. It just makes your picture wrong.</p>
<p>Graphical errors are super easy to spot anyways.</p>
| 39,572
|
<p>Is it legal to more or less "copy" (or euphemistically, be very "inspired by") the idea and UI of a copyrighted program? This question popped in my mind when looking at "<a href="http://culturedcode.com/things/" rel="noreferrer">Things</a>" which is a Mac-only program.</p>
<p>How legal would it be for someone to make a Windows version of this program with a basically identical UI design and feature set? Where are the legal boundaries of what counts as copyright infringement?</p>
<p>Unless you specify otherwise, I am assuming an "IANAL" for any answer, so you don't have to write that. ;)</p>
|
<p>Specific elements of a design can be copyrighted. Apple won the "trashcan" icon, but effectively nothing else during the Microsoft/Apple lawsuit over a look and feel. As long as the code is entirely your own, the graphics are your own (and yes, copying too closely a <em>specific</em> graphic element like the trashcan can be a problem) and you aren't doing cloning elements that are trademark/tradedress related, you should be within the law (in the US).</p>
<p>Of course, that doesn't mean that someone can't <em>sue</em> you. Meritless lawsuits are started all the time for intimidation. Also note that patents can cover the interaction of the user with a UI, so copyright might not be your primary problem in some cases.</p>
|
<p>I think in general the answer is no, it would not be illegal. Apple tried to sue Microsoft for stealing the "look and feel" of Mac OS, and lost... There are lots of linux programs, which copy the UI of similar windows programs almost exactly...</p>
| 30,896
|
<p>I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JavaScript. This is for script that runs on local machine for administration scripts, not for the web browser.</p>
<p>My IDL file for the COM object has the interface that I am calling into as:</p>
<pre>
HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray);
</pre>
<p>The function returns correctly, but the strings are getting 'lost' when they are being assigned to a variable in JavaScript.</p>
<p>The question is:
What is the proper way to get the array of strings returned to a JavaScript variable?
</p>
|
<p>If i recall correctly, you'll need to wrap the <code>SAFEARRAY</code> in a <code>VARIANT</code> in order for it to get through, and then use a <a href="http://msdn.microsoft.com/en-us/library/y39d47w8(VS.85).aspx" rel="noreferrer">VBArray object</a> to unpack it on the JS side of things:</p>
<pre><code>HRESULT GetArrayOfStrings(/*[out, retval]*/ VARIANT* pvarBstrStringArray)
{
// ...
_variant_t ret;
ret.vt = VT_ARRAY|VT_VARIANT;
ret.parray = rgBstrStringArray;
*pvarBstrStringArray = ret.Detach();
return S_OK;
}
</code></pre>
<p>then</p>
<pre><code>var jsFriendlyStrings = new VBArray( axOb.GetArrayOfStrings() ).toArray();
</code></pre>
|
<p><a href="https://stackoverflow.com/questions/45169/how-do-i-return-an-array-of-strings-from-an-activex-object-to-jscript#45211">Shog9</a>
is correct. COM scripting requires that all outputs be VARIANTS. </p>
<p>In fact, it also requires that all the <strong>INPUTs</strong> be VARIANTS as well -- see the nasty details of IDispatch in your favorite help file. It's only thought the magic of the Dual Interface implementation by ATL and similar layers (which most likely is what you are using) that you don't have to worry about that. The input VARIANTs passed by the calling code are converted to match your method signature before your actual method is called.</p>
| 6,698
|
<p>Until this morning, I have had Apache 2.0 running as a service using a local account which was configured with appropriate permissions. Sometime yesterday, someone must have changed something, and now Apache 2.0 won't start as a service under this account.</p>
<p>I made the account an Administrator temporarily, and Apache 2.0 starts fine.</p>
<p>I tried following the access listed in the <a href="http://httpd.apache.org/docs/2.0/platform/windows.html" rel="nofollow noreferrer">official documentation</a>, but it seems to require more access. <strong>Does anyone know what access Apache 2.0 needs to start as a service?</strong></p>
<p>I'm running Apache 2.0.63 with SVN 1.4.6 and mod_auth_sspi for windows domain authentication.</p>
<p>I also checked the syntax of the configuration file from command-line using the <strong>-t</strong> parameter, but I received the message <strong>Syntax OK</strong>.</p>
<p>Here's the error I get when starting as a service from command-line:</p>
<pre>
X:\>net start apache2
The Apache2 service is starting.
The Apache2 service could not be started.
A service specific error occurred: 1.
More help is available by typing NET HELPMSG 3547.
</pre>
|
<p>I have discovered the problem. After establishing the connection and the message listener the service went into a loop with Thread.Sleep(500). Dumb. I refactored the service to start everything up in OnStart and dispose of it in OnStop.</p>
<p>Since doing that, everything is running perfectly.</p>
<p>Classic ID-10-T error occurring between keyboard and chair.</p>
|
<p>we have just come across exactly the same issue using a .Net service talking to ActiveMQ, but ours locks up after only about 10-20 messages being delivered.</p>
<p>Have tried it with and without the spring framework and it's slightly better without (unless I'm imagining things).</p>
<p>Would you mind checking over this code and letting me know if it bears any resemblance to your own?</p>
<pre><code>ConnectionFactory connectionFactory = new ConnectionFactory("tcp://activemq:61616");
Connection connection = (Connection)connectionFactory.CreateConnection();
connection.Start();
Session session = (Session)connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
IDestination queue = session.GetQueue("test.queue");
MessageConsumer consumer = (MessageConsumer)session.CreateConsumer(queue);
for (int i = 0; i < 1000; i++)
{
IMessage msg = consumer.Receive();
if (msg != null)
Console.WriteLine((msg as ITextMessage).Text);
}
</code></pre>
| 33,833
|
<p>Added: Working with SQL Server 2000 and 2005, so has to work on both. Also, value_rk is not a number/integer (Error: Operand data type uniqueidentifier is invalid for min operator)</p>
<p>Is there a way to do a single column "DISTINCT" match when I don't care about the other columns returned? Example:</p>
<pre><code>**Table**
Value A, Value L, Value P
Value A, Value Q, Value Z
</code></pre>
<p>I need to return only one of these rows based on what is in the first one (Value A). I still need results from the second and third columns (the second should actually match all across the board anyway, but the third is a unique key, which I need at least one of).</p>
<p>Here's what I've got so far, although it doesn't work obviously:</p>
<pre><code>SELECT value, attribute_definition_id, value_rk
FROM attribute_values
WHERE value IN (
SELECT value, max(value_rk)
FROM attribute_values
)
ORDER BY attribute_definition_id
</code></pre>
<p>I'm working in ColdFusion so if there's a simple workaround in that I'm open to that as well. I'm trying to limit or "group by" the first column "value". value_rk is my big problem since every value is unique but I only need one.</p>
<p>NOTE: value_rk is not a number, hence this DOES NOT WORK</p>
<p>UPDATE: I've got a working version, it's probably quite a bit slower than a pure SQL version, but honestly anything working at this point is better than nothing. It takes the results from the first query, does a second query except limiting it's results to one, and grabs a matching value_rk for the value that matches. Like so:</p>
<pre><code><cfquery name="queryBaseValues" datasource="XXX" timeout="999">
SELECT DISTINCT value, attribute_definition_id
FROM attribute_values
ORDER BY attribute_definition_id
</cfquery>
<cfoutput query="queryBaseValues">
<cfquery name="queryRKValue" datasource="XXX">
SELECT TOP 1 value_rk
FROM attribute_values
WHERE value = '#queryBaseValues.value#'
</cfquery>
<cfset resourceKey = queryRKValue.value_rk>
...
</code></pre>
<p>So there you have it, selecting a single column distinctly in ColdFusion. Any pure SQL Server 2000/2005 suggestions are still very welcome :)</p>
|
<p>this might work:</p>
<pre><code>SELECT DISTINCT a.value, a.attribute_definition_id,
(SELECT TOP 1 value_rk FROM attribute_values WHERE value = a.value) as value_rk
FROM attribute_values as a
ORDER BY attribute_definition_id
</code></pre>
<p>.. not tested.</p>
|
<p>Less elegant than I would like---- it's essentially what you're doing, just in pure SQL--- but it works and can all be done in SQL.</p>
<pre>
DECLARE @mytable TABLE(mykey NVARCHAR(512), myVal NVARCHAR(512))
DECLARE @keyVal NVARCHAR(512)
DECLARE @depVal NVARCHAR(512)
DECLARE myCursor CURSOR for
SELECT DISTINCT(value) FROM attribute_values
OPEN myCursor
FETCH NEXT FROM myCursor INTO @keyVal
WHILE @@FETCH_STATUS=0
BEGIN
SET @depVal = (SELECT TOP 1 attribute_definition_id FROM attribute_values WHERE VALUE=@keyVal ORDER BY attribute_definition_id)
INSERT INTO @mytable (mykey, myVal) VALUES (@keyVal, @depVal)
FETCH NEXT FROM myCursor INTO @keyVal
END
DEALLOCATE myCursor
SELECT * FROM @mytable
</pre>
<p>You can add a depVal2 and others using this method. </p>
| 31,285
|
<p>I am interested in references to designs which use a customized support instead of the slicer's default normal/tree support.</p>
<p>The background is this: I am making a hubcap with a 3D logo. I do not want to place the logo on the print bed because the logo will become very messy. So, I place the rim of the hubcap on the bed. This means that a lot of support is needed. With support = normal the print time taken is 36.5 hours using 290 g of filament. With support = tree the time taken is 29.5 hours using 200 g of filament. In comparison, with support = none the time taken is 14.5 hours using 115 g of filament, but of course is not practical. So, I decided to make my own support and I manually inserted it at a specified layer - just below the top disk and the logo above it. The design included some small brackets to hold the support. The time taken and amount of filament is the same as no support - about half the time & amount for tree support! Here is what the support looks like:</p>
<p><a href="https://i.stack.imgur.com/TfeLg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TfeLg.png" alt="enter image description here" /></a></p>
<p>I intended to snip away the mesh, but it blends in quite well with the layer above it. (Perhaps a finer mesh is easier to remove.)</p>
<p>I am interested to know of others who have designed customized supports.</p>
|
<p>Your question may be closed for being somewhat vague and outside the scope of the SE, but consider to view <a href="https://www.youtube.com/watch?v=RPijCjz9G1w" rel="nofollow noreferrer">Maker's Muse video</a> about creating alternatives to slicer-generated supports.</p>
<p>The video suggests creating primitives in locations appropriate to the overall design. For example, an unsupported "shelf" or "ledge" could result in a massive number of supports if left to the slicer. The MM method suggests that a small rectangular prism on the edge of the ledge turns the object from an unsupported item to a bridging solution. If the gap is excessive, multiple primitives in strategic locations would reduce the slicer-generated support.</p>
<p><a href="https://i.stack.imgur.com/qgY3N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qgY3N.png" alt="user generated support primitive" /></a>
Image is screen shot from linked video.</p>
<p>I've had to print a counterbore that I did not want to load with supports. The primitive was a simple cylinder with a diameter of 0.4 mm larger than the diameter of the hole. This created a peg attached to the edge of the counterbore, which the slicer saw as a bridging solution. Easily snapped clean after the print completed.</p>
|
<p>In this situation I probably wouldn't use supports at all.</p>
<p>I'd put something round on the bed that fits the space instead.</p>
| 2,191
|
<p>We are developing a C# application for a web-service client. This will run on Windows XP PC's.</p>
<p>One of the fields returned by the web service is a DateTime field. The server returns a field in GMT format i.e. with a "Z" at the end.</p>
<p>However, we found that .NET seems to do some kind of implicit conversion and the time was always 12 hours out.</p>
<p>The following code sample resolves this to some extent in that the 12 hour difference has gone but it makes no allowance for NZ daylight saving.</p>
<pre><code>CultureInfo ci = new CultureInfo("en-NZ");
string date = "Web service date".ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);
</code></pre>
<p>As per <a href="http://www.timeanddate.com/worldclock/city.html?n=22" rel="noreferrer">this date site</a>:</p>
<blockquote>
<p>UTC/GMT Offset </p>
<p>Standard time zone: UTC/GMT +12 hours<br>
Daylight saving time: +1 hour<br>
Current time zone offset: <strong>UTC/GMT +13 hours</strong> </p>
</blockquote>
<p>How do we adjust for the extra hour? Can this be done programmatically or is this some kind of setting on the PC's?</p>
|
<p>For strings such as <code>2012-09-19 01:27:30.000</code>, <code>DateTime.Parse</code> cannot tell what time zone the date and time are from.</p>
<p><code>DateTime</code> has a <em>Kind</em> property, which can have one of three time zone options:</p>
<ul>
<li>Unspecified</li>
<li>Local</li>
<li>Utc</li>
</ul>
<p><strong>NOTE</strong> <em>If you are wishing to represent a date/time other than UTC or your local time zone, then you should use <a href="http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx" rel="noreferrer"><code>DateTimeOffset</code></a>.</em></p>
<hr>
<p>So for the code in your question:</p>
<pre><code>DateTime convertedDate = DateTime.Parse(dateStr);
var kind = convertedDate.Kind; // will equal DateTimeKind.Unspecified
</code></pre>
<p>You say you know what kind it is, so tell it.</p>
<pre><code>DateTime convertedDate = DateTime.SpecifyKind(
DateTime.Parse(dateStr),
DateTimeKind.Utc);
var kind = convertedDate.Kind; // will equal DateTimeKind.Utc
</code></pre>
<p>Now, once the system knows its in UTC time, you can just call <code>ToLocalTime</code>:</p>
<pre><code>DateTime dt = convertedDate.ToLocalTime();
</code></pre>
<p>This will give you the result you require.</p>
|
<p>This code block uses universal time to convert current DateTime object then converts it back to local DateTime. Works perfect for me I hope it helps!</p>
<pre><code>CreatedDate.ToUniversalTime().ToLocalTime();
</code></pre>
| 21,709
|
<p>I'm trying to format a column in a <code><table/></code> using a <code><col/></code> element. I can set <code>background-color</code>, <code>width</code>, etc., but can't set the <code>font-weight</code>. Why doesn't it work?</p>
<pre><code><table>
<col style="font-weight:bold; background-color:#CCC;">
<col>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>
</code></pre>
|
<p>As far as I know, you can only format the following using CSS on the <code><col></code> element: </p>
<ul>
<li>background-color</li>
<li>border</li>
<li>width</li>
<li>visibility</li>
</ul>
<p>This <a href="http://www.quirksmode.org/css/columns.html" rel="noreferrer">page</a> has more info.</p>
<p>Herb is right - it's better to style the <code><td></code>'s directly. What I do is the following:</p>
<pre><code><style type="text/css">
#mytable tr > td:first-child { color: red;} /* first column */
#mytable tr > td:first-child + td { color: green;} /* second column */
#mytable tr > td:first-child + td + td { color: blue;} /* third column */
</style>
</head>
<body>
<table id="mytable">
<tr>
<td>text 1</td>
<td>text 2</td>
<td>text 3</td>
</tr>
<tr>
<td>text 4</td>
<td>text 5</td>
<td>text 6</td>
</tr>
</table>
</code></pre>
<p>This won't work in IE however.</p>
|
<p>A <code>col</code> tag must be inside of a <code>colgroup</code> tag, This may be something to do with the problem.</p>
| 19,077
|
<p>related to:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/21265/">comparing ieee floats and doubles for equality</a></li>
<li><a href="https://stackoverflow.com/questions/328475/">Should we compare floating point numbers for equality against a <em>relative</em> error</a></li>
<li><a href="https://stackoverflow.com/questions/17333/#17467">Most effective way for float and double comparison</a></li>
</ul>
<p>However with regard to <a href="http://download.intel.com/design/processor/manuals/253665.pdf" rel="nofollow noreferrer">80 bit IEEE floats</a> (see section 8.2) on an x86</p>
<p>In particular I like the <a href="https://stackoverflow.com/questions/21265/comparing-ieee-floats-and-doubles-for-equality#21277">this implementation</a> using a count of representable values between the operands because it scale by default.</p>
<p>One use case would be for numeric approximations where two values approach each other and I need to check to see if they are close enough. </p>
<hr>
<p>p.s. The implementation language will be D but I can translate. Also an implementation that can automatically handle whatever the underlying type is (for instance if only 64bit real was available) would be ideal.</p>
<p><a href="http://www.dsource.org/projects/scrapple/browser/trunk/units/unit.d#L141" rel="nofollow noreferrer">The current code in use:</a></p>
|
<p>Since D has 80-bit reals built in (as far as I can tell), why would you not just use the standard approach of comparing with an epsilon value. This can be a fixed value if you know the rough range in advance, such as US currency:</p>
<pre><code>if (abs (a - b) < 1e-6) // effectively equal
</code></pre>
<p>or an acceptable relative error, such as 1 part per million of the average:</p>
<pre><code>if (abs (a - b) < ((a + b) / 2) / 1e6) // effectively equal
</code></pre>
<p>Keep in mind I don't know D, the code above is for demonstrative purposes only.</p>
|
<p>My current solution is</p>
<pre><code>bool Near(real a, real b, int count = 5)
{
// Returns the number of mantissa bits which are equal in x and y.
int i = std.math.feqrel!(real)(a,b);
return i + count >= real.mant_dig;
}
</code></pre>
<p>It gives the number of miss-matched bits in the inputs. I'm not sure how well this will work near powers of 2.</p>
| 46,278
|
<p>I'm using Visual Studio icon library (VS2008ImageLibrary), there are some BMP files with a pink background. How can I make the pink background become transparent? What software can I use to do this? Any free one? </p>
<p>Thanks</p>
|
<p>I used IrfanView's batch conversion tool. It's still some work, because you have to click the pink area on every single icon instead of just specifying pink as transparent color, but it worked. It would be easy to write a simple conversion tool using GDI+ though, which I considered as well.</p>
<p>Note that even though you can use them then as transparent images, many of them unfortunately still have ugly edges when you render them on a dark background or use them as overlay. If you just want very few of them, consider tweaking them individually if you think you'll not always have a bright background.</p>
|
<p>While I don't know the modern .NET answer to your question, it's worth noting the historical reason for these bitmaps with magenta backgrounds:</p>
<p>Back in the Win32-only days, there were some Common Controls (like the Toolbar, and ListView) that took these bitmaps and a colour to be treated as transparent, and then rendered that colour as transparent. I imagine that, behind the scenes, they used functions like <a href="http://msdn.microsoft.com/en-us/library/dd145141(VS.85).aspx" rel="nofollow noreferrer">TransparentBtl</a>.</p>
| 29,244
|
<p>I'm taking a look at how the model system in django works and I noticed something that I don't understand.</p>
<p>I know that you create an empty <code>__init__.py</code> file to specify that the current directory is a package. And that you can set some variable in <code>__init__.py</code> so that import * works properly.</p>
<p>But django adds a bunch of from ... import ... statements and defines a bunch of classes in <code>__init__.py</code>. Why? Doesn't this just make things look messy? Is there a reason that requires this code in <code>__init__.py</code>?</p>
|
<p>All imports in <code>__init__.py</code> are made available when you import the package (directory) that contains it.</p>
<p>Example:</p>
<p><code>./dir/__init__.py</code>:</p>
<pre><code>import something
</code></pre>
<p><code>./test.py</code>:</p>
<pre><code>import dir
# can now use dir.something
</code></pre>
<p>EDIT: forgot to mention, the code in <code>__init__.py</code> runs the first time you import any module from that directory. So it's normally a good place to put any package-level initialisation code.</p>
<p>EDIT2: dgrant pointed out to a possible confusion in my example. In <code>__init__.py</code> <code>import something</code> can import any module, not necessary from the package. For example, we can replace it with <code>import datetime</code>, then in our top level <code>test.py</code> both of these snippets will work:</p>
<pre><code>import dir
print dir.datetime.datetime.now()
</code></pre>
<p>and</p>
<pre><code>import dir.some_module_in_dir
print dir.datetime.datetime.now()
</code></pre>
<p>The bottom line is: all names assigned in <code>__init__.py</code>, be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package.</p>
|
<blockquote>
<p>"We recommend not putting much code in an <code>__init__.py</code> file, though. Programmers do not expect actual logic to happen in this file, and much like with <code>from x import *</code>, it can trip them up if they are looking for the declaration of a particular piece of code and can't find it until they check <code>__init__.py</code>. "</p>
<p>-- Python Object-Oriented Programming Fourth Edition Steven F. Lott Dusty Phillips</p>
</blockquote>
| 14,496
|
<p>Dear stack overflow community,</p>
<p>I've been given the task of overhauling a couple of websites for a large corporation I'm working for, as well as developing an internal intranet site for content management and document storage within the organization.</p>
<p>My "problem" is this: They want me to use a framework/set of languages/technologies that I can prove to them are "stable, enterprise-ready technologies with a proven track record."</p>
<p>The spec's "big picture" really isn't too complicated: Implement an enterprise-class CMS for management of each division's web pages that deal mostly with product information and documentation (i.e. a simpler version of www.linksys.com).</p>
<p>As an open-source programmer, I'd like to use Python with TurboGears and build it from scratch, but I can't really find a way to prove to the president that TurboGears has a huge enterprise track record. Zope seems to have a lot of enterprise usage, but it looks a bit bloated to me. Django could be an option, but doesn't seem as flexible as TurboGears.</p>
<p>I'd rather not use PHP, but Drupal has a very nice resume with the "right" names under it (AOL, Sony, MTV); plus it could save me building many of the CMS components from scratch.</p>
<p>Rails might be another option, but I'm not too familiar with it (and as a Python/PHP programmer, Ruby's syntax drives me crazy).</p>
<p>What would the S.O. community suggest for a project like this? I'm sure many of you have faced the same dilemma. What ended up working/not working for you? As I said before, my first choice would be Python, second would be PHP, third would be Rails.</p>
<p>Thank you,
Seth</p>
|
<p>If you like Python, and you want a web framework, I wouldn't go past Django. It's simple, powerful, and runs plenty of enterprise-level sites.</p>
<p>A few of the bigger sites using Django are <a href="http://www.lawrence.com/" rel="nofollow noreferrer">Lawrence.com</a>, <a href="http://www.curse.com/" rel="nofollow noreferrer">Curse Gaming</a> and some <a href="http://projects.washingtonpost.com/congress/" rel="nofollow noreferrer">Washington Post</a> sites. It just went to version 1.0 recently as well, so you have a solid code base to work from.</p>
<p>You can always throw in a <a href="http://wiki.python.org/moin/OrganizationsUsingPython" rel="nofollow noreferrer">list of companies that use Python</a> if you want to, it includes people like Google, Yahoo and NASA.</p>
|
<blockquote>
<p>CMS for a medium-big company is not about Software. It is about proccesses and policies.</p>
</blockquote>
<p>Very true! </p>
<p>Association with prestigious names is not necessarily an indicator of pleasing end results. </p>
<p>I like Sony products, yes, but on the various occasions on which I have sought support from Sony sites I have felt like banging my head against a brick wall! Those head-cracking sites may not have been Drupal-oriented, I have no idea, but the point is: don't be sucked in by big names alone.</p>
<p>An issue you should expect is: preconceptions of what may be achieved (or constrained) by a system. </p>
<p>Allow yourself some learning time with Plone — ideally, for a large project such as this, <em>invest</em> in expert advice — and you'll realise that traditional-ish ideas of what a system can or should accomplish are mostly exceeded by Plone's capabilities. </p>
<p>Gauge user requirements with a very open mind (not based on simplicities such as "I'd like a system that's equal to system x") then come to plone.org | Support | Chat Room to further discuss your requirements.</p>
| 29,904
|
<p>Is there a difference between the two examples below for beginning a Perl script? If so, when would I use one over the other?</p>
<p>example 1:</p>
<pre><code>#!/usr/bin/perl
use warnings;
</code></pre>
<p>example 2:</p>
<pre><code>#!/usr/bin/perl -w
</code></pre>
|
<p>Using the switch will enable all warnings in <strong>all</strong> modules used by your program. Using the pragma you enable it only in that specific module (or script). Ideally, you use warnings in all your modules, but often that's not the case. Using the switch can get you a lot of warnings when you use a third party module that isn't warnings-safe.</p>
<p>So, ideally it doesn't matter, but pragmatically it's often preferable for your end-users not to use the switch but the pragma.</p>
|
<p>In addition to enabling/disabling specific assertions using the pragma, you can also promote some or all warnings to errors:</p>
<pre><code>use strict;
use warnings FATAL => 'all', NONFATAL => 'exec';
</code></pre>
| 27,362
|
<p>There is a select dropdown and I want to add "No selection" item to the list which should give me 'null' when submitted.
I'm using SimpleFormController derived controller.</p>
<pre><code>protected Map referenceData(HttpServletRequest httpServletRequest, Object o, Errors errors) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("countryList", Arrays.asList(Country.values()));
return map;
}
</code></pre>
<p>And the jspx part is</p>
<pre class="lang-html prettyprint-override"><code><form:select path="country" items="${countryList}" title="country"/>
</code></pre>
<p>One possible solution seems to be in adding a null value to the beginning of the list and then using a custom PropertyEditor to display this 'null' as 'No selection'.
Is there a better solution?</p>
<p>@Edit: I have solved this with a custom validation annotation which checks if the selected value is "No Selection". Is there a more standard and easier solution?</p>
|
<p>One option:</p>
<pre class="lang-html prettyprint-override"><code><form:select path="country" title="country" >
<form:option value="">&nbsp;</form:option>
<form:options items="${countryList}" />
</form:select>
</code></pre>
|
<p>I don't think you should need a property editor for this. If the "blank" option is first in the list, and the tag that outputs the list doesn't mark any of them as selected, then the browser should select the first, "blank" one automatically.</p>
<p>When you submit the form, try and work it so that the "blank" value is bound to your command as a null, which might happen automatically, depending on the type.</p>
| 19,650
|
<p>Given an array of <strong>n</strong> Objects, let's say it is an <strong>array of strings</strong>, and it has the following values:</p>
<pre><code>foo[0] = "a";
foo[1] = "cc";
foo[2] = "a";
foo[3] = "dd";
</code></pre>
<p>What do I have to do to delete/remove all the strings/objects equal to <strong>"a"</strong> in the array?</p>
|
<p>[If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.]</p>
<p>To flesh out <a href="https://stackoverflow.com/a/112507/13">Dustman's idea</a>:</p>
<pre><code>List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);
</code></pre>
<p>Edit: I'm now using <code>Arrays.asList</code> instead of <code>Collections.singleton</code>: singleton is limited to one entry, whereas the <code>asList</code> approach allows you to add other strings to filter out later: <code>Arrays.asList("a", "b", "c")</code>.</p>
<p>Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a <em>new</em> array sized exactly as required, use this instead:</p>
<pre><code>array = list.toArray(new String[0]);
</code></pre>
<hr>
<p>Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:</p>
<pre><code>private static final String[] EMPTY_STRING_ARRAY = new String[0];
</code></pre>
<p>Then the function becomes:</p>
<pre><code>List<String> list = new ArrayList<>();
Collections.addAll(list, array);
list.removeAll(Arrays.asList("a"));
array = list.toArray(EMPTY_STRING_ARRAY);
</code></pre>
<p>This will then stop littering your heap with useless empty string arrays that would otherwise be <code>new</code>ed each time your function is called.</p>
<p>cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:</p>
<pre><code>array = list.toArray(new String[list.size()]);
</code></pre>
<p>I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling <code>size()</code> on the wrong list).</p>
|
<p>Assign null to the array locations.</p>
| 13,756
|
<p>I'm writing a little web-based utility for my brother who needs to merge columns in a CSV file. I know things like this surely exist somewhere, but a large part of this is that is a fun little exercise.</p>
<p>Anyways, I'm trying to figure out the best/neatest way to present the part of the UI where he reorders the columns and chooses which columns get merged.</p>
<p>The jQuery UI "selectable" interaction provides about 85% of what I need - the simple reordering of the columns - but I'm having a bit of a rough time with the merging. What I'm trying to do is make it so that "merged" columns become a nested list under a single item.</p>
<p>For example:</p>
<pre><code><ul id="columns">
<li>Column 1</li>
<li>Column 2</li>
</ul>
</code></pre>
<p>would become:</p>
<pre><code><ul id="columns">
<li>Column 1<ul class="merge"><li>Column 2</li></ul></li>
</ul>
</code></pre>
<p>This is proving to be a bit more of a pain than I anticipated, so I was wondering if anyone had any ideas for a better way to present the overall UI. I'm fairly comfortable in jQuery, so bonus points if it can be done in jQuery :D</p>
<p>@dylanfm: This <em>isn't</em> tabular data - it's just a list of column <em>names</em>, but no actual data. Besides, the specific HTML element I use is hardly at the heart of what I'm asking.</p>
<p>@smo: I like the simplicity of your idea, but the problem is that there are several <em>dozen</em> different columns, so listing every column once per column would unfortunately be out of the question.</p>
<p>@strager: That's pretty much exactly what I've been trying to do, it's just that particulars of making UI respond the way I want have been giving me problems. I'll give you the answer for now, and I guess it's back to the salt mines for me.</p>
|
<p>Basic steps:</p>
<ol>
<li>Grab the list of columns to be merged as an array of <li>'s.
<ul>
<li>If you're merging two already-merged columns (or one of the colums is already merged), extract each column in the group. In your structure, you'd want to make "Column 1" have its own <li> without the child <ul>.</li>
<li>You'd probably want to clone these, as you'll be deleting the original nodes in (6).</li>
</ul></li>
<li>Create a new <ul> node, adding the proper "merged" className.</li>
<li>Add all the <li>'s you gathered in (1), except the first one, and insert them as children to the <ul>.</li>
<li>Insert the <ul> as the last child of the first <li> you gathered in (1).</li>
<li>Insert the <li> (parent in (4)) as a child of the column list ($('#columns')).</li>
<li>Delete the original columns which you were going to merge.</li>
</ol>
|
<p>I'd say to stick with using tables for tabular data, unordered lists don't seem to suit the content as much.</p>
| 40,327
|
<p>I have an Open Source app and I currently only post the binary for the Windows build. At this point Linux users have to get the source and compile it. Is there a standard way for posting a Linux binary? </p>
<p>My app is in c / c++ and compiled with gcc, the only external Linux code I use is X Windows and CUPS.</p>
|
<p>The most common way would be to package it in a <a href="http://en.wikipedia.org/wiki/RPM_Package_Manager" rel="nofollow noreferrer">.rpm file</a> for <a href="http://www.redhat.com/" rel="nofollow noreferrer">RedHat</a>-based distros like <a href="http://fedoraproject.org/" rel="nofollow noreferrer">Fedora</a>, or a <a href="http://en.wikipedia.org/wiki/Deb_(file_format)" rel="nofollow noreferrer">.deb file</a> for <a href="http://www.debian.org/" rel="nofollow noreferrer">Debian</a>-based distros like <a href="http://www.ubuntu.com/" rel="nofollow noreferrer">Ubuntu</a>.</p>
|
<p>I only use precompiled binaries from my distribution - never from other hand. If you can afford it just roll a tarball and add some buildscript so that people can build your project. To publish it add it to sites like: <a href="http://www.freshmeat.net" rel="nofollow noreferrer">Freshmeat</a></p>
| 15,815
|
<p>I have a question about Slic3r software.</p>
<p>I would like to subtract two parts. For example, I have an STL model, when I right click on the part, I can select <strong>Settings...</strong>, and in the <strong>Settings</strong> window, I can select modifier and I can select slab.with selecting proper thickness. Now we have two parts where one of them is inside of another. My problem is subtracting those two parts.</p>
<p>How can I subtract this part from another?</p>
|
<p>Given my limited familiarity with all the CAD tools that exist, I would fall back to something that I know does binary operations on volumes -- openScad.</p>
<p>One can create two objects, one from each of the two STL files, and subtract one from the other. One can also compute intersections, unions, and other operations.</p>
<p>There are probably other programs that also do this, but openScad allows for doing in programmatically, so that once you have it right, you can update the objects without needing to redo the finicky part of the operations.</p>
<p>slic3r may do this, but I haven't seen such features in my multi-year use of slic3r for slicing. </p>
<p>When in doubt, IMO it is better to script something. It is virtually never that I do something only once, especially in 3D printing where rapid prototype leads to rapid change and improvement.</p>
|
<p>I am assuming your trying to perforate, hollow or cut your design in a specific shape that is the same as the inner 3D object or vice versa? </p>
<p>Do this with 3Ds max its just really easy there for such operations.</p>
<p>Please load into Autodesk 3Ds max and perform Boolean.</p>
<p>This is the link on how to use the Boolean tool, <a href="https://knowledge.autodesk.com/support/3ds-max/learn-explore/caas/CloudHelp/cloudhelp/2017/ENU/3DSMax/files/GUID-3DBEB7C2-43CC-4B78-9463-5DD448FD921C-htm.html" rel="nofollow noreferrer">Boolean Compound Object</a></p>
<p>There are other software like magics where this can be done but as you seem to be trying this for the first time. I will suggest only 3Ds max.</p>
| 937
|
<p>Various programs can do stuff only when you haven't used the computer for a while (eg screensaver, Google Desktop indexing, etc).</p>
<p>How do they know when it has been inactive? Is there some function in Windows that tells you how long it has been inactive, or do you have to use some kind of keyboard/mouse hook to track activity yourself?</p>
<p>I'm using C#, but I'm interested in any method of determining the inactivity.</p>
|
<p>EDIT: changed answer, providing text and detail behind Shy's answer (which should be and was accepted). Feel free to merge and delete this one.</p>
<p><a href="http://pinvoke.net/default.aspx/user32/GetLastInputInfo.html" rel="nofollow noreferrer">GetLastInputInfo</a> Function
The GetLastInputInfo function retrieves the time of the last input event.</p>
<p>Pasted here from P/Invoke</p>
<p>This function retrieves the time since last user input</p>
<pre><code>[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
static int GetLastInputTime()
{
int idleTime = 0;
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
lastInputInfo.cbSize = Marshal.SizeOf( lastInputInfo );
lastInputInfo.dwTime = 0;
int envTicks = Environment.TickCount;
if( GetLastInputInfo( ref lastInputInfo ) )
{
int lastInputTick = lastInputInfo.dwTime;
idleTime = envTicks - lastInputTick;
}
return (( idleTime > 0 ) ? ( idleTime / 1000 ) : idleTime );
}
[StructLayout( LayoutKind.Sequential )]
struct LASTINPUTINFO
{
public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));
[MarshalAs(UnmanagedType.U4)]
public int cbSize;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwTime;
}
</code></pre>
<p><strike>
FWIW:
I implemented a global keyboard and mouse hook during AnAppADay. See this app for the source - it's pretty close to what you want. The classes you'll want are in the AnAppADay.Utils namespace.
</strike> [scratched due to linkrot]</p>
|
<p>The keyboard and mouse hooks are what I find to be most valuable. The class below can be inserted and you just have to figure out what you want to do with the information about key and mouse updates. </p>
<pre><code>using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace Example {
public class Hook {
delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
[FlagsAttribute]
public enum WindowMessage {
WM_KEYDOWN = 0x0000000000000100, // &H100
WM_MOUSEMOVE = 0x0000000000000200, // &H200
WM_LBUTTONDOWN = 0x0000000000000201, // &H201
WM_RBUTTONDOWN = 0x0000000000000204, // &H204
WH_KEYBOARD = 2,
WH_MOUSE = 7,
HC_ACTION = 0
}
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
private static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
private static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
//Declare MouseHookProcedure as a HookProc type.
static HookProc MouseHookProcedure;
static HookProc KeyboardHookProcedure;
private static int mhMouseHook = 0;
private static int mhKeyboardHook = 0;
public Hook() {}
public static void Init() {
MouseHookProcedure = new HookProc( MouseHookProc );
KeyboardHookProcedure = new HookProc( KeyboardHookProc );
mhMouseHook = SetWindowsHookEx( (int)WindowMessage.WH_MOUSE, MouseHookProcedure, (IntPtr)0, AppDomain.GetCurrentThreadId() );
mhKeyboardHook = SetWindowsHookEx( (int)WindowMessage.WH_KEYBOARD, KeyboardHookProcedure, (IntPtr)0, AppDomain.GetCurrentThreadId() );
}
public static void Terminate() {
UnhookWindowsHookEx( mhMouseHook );
UnhookWindowsHookEx( mhKeyboardHook );
}
private static int MouseHookProc( int nCode, IntPtr wParam, IntPtr lParam ) {
if ( nCode >= 0 ) {
//do something here to update the last activity point, i.e. a keystroke was detected so reset our idle timer.
}
return CallNextHookEx( mhMouseHook, nCode, wParam, lParam );
}
private static int KeyboardHookProc( int nCode, IntPtr wParam, IntPtr lParam ) {
if ( nCode >= 0 ) {
//do something here to update the last activity point, i.e. a mouse action was detected so reset our idle timer.
}
return CallNextHookEx( mhKeyboardHook, nCode, wParam, lParam );
}
}
}
</code></pre>
<p>Of course this only works within the application you are hooking. If you need to track inactivity across the entire system, you need to create a DLL that can be loaded into the address spaces of all other windows. Unfortunately, I haven't heard of any hack that would allow a .net compiled .dll that will work in this scenario; we have a C++ DLL that hooks for this purpose.</p>
| 24,885
|
<p>Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?"</p>
<p>So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type?</p>
<p>So I have</p>
<pre><code>typeof(int)
typeof(DateTime)
System.Type t = something;
</code></pre>
<p>and I want</p>
<pre><code>int?
DateTime?
</code></pre>
<p>or</p>
<pre><code>Nullable<int> (which is the same)
if (t is primitive) then Nullable<T> else just T
</code></pre>
<p>Is there a built-in method?</p>
|
<p>Here is the code I use:</p>
<pre><code>Type GetNullableType(Type type) {
// Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable.
type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null
if (type.IsValueType)
return typeof(Nullable<>).MakeGenericType(type);
else
return type;
}
</code></pre>
|
<p>There isn't anything built in that I know of, as the <code>int?</code>, etc. is just syntactic sugar for <code>Nullable<T></code>; and isn't given special treatment beyond that. It's especially unlikely given you're attempting to obtain this from the type information of a given type. Typically that always necessitates some 'roll your own' code as a given. You would have to use Reflection to create a new <code>Nullable</code> type with type parameter of the input type.</p>
<p><strong>Edit:</strong> As the comments suggest actually <code>Nullable<></code> <em>is</em> treated specially, and in the runtime to boot as explained in <a href="http://blogs.msdn.com/somasegar/archive/2005/08/11/450640.aspx" rel="nofollow noreferrer">this article</a>.</p>
| 13,351
|
<p>Two ways to normalize a Vector3 object; by calling Vector3.Normalize() and the other by normalizing from scratch:</p>
<pre><code>class Tester {
static Vector3 NormalizeVector(Vector3 v)
{
float l = v.Length();
return new Vector3(v.X / l, v.Y / l, v.Z / l);
}
public static void Main(string[] args)
{
Vector3 v = new Vector3(0.0f, 0.0f, 7.0f);
Vector3 v2 = NormalizeVector(v);
Debug.WriteLine(v2.ToString());
v.Normalize();
Debug.WriteLine(v.ToString());
}
}
</code></pre>
<p>The code above produces this:</p>
<pre><code>X: 0
Y: 0
Z: 1
X: 0
Y: 0
Z: 0.9999999
</code></pre>
<p>Why?</p>
<p>(Bonus points: Why Me?)</p>
|
<p>Look how they implemented it (e.g. in asm).</p>
<p>Maybe they wanted to be faster and produced something like:</p>
<pre><code> l = 1 / v.length();
return new Vector3(v.X * l, v.Y * l, v.Z * l);
</code></pre>
<p>to trade 2 divisions against 3 multiplications (because they thought mults were faster than divs (which is for modern fpus most often not valid)). This introduced one level more of operation, so the less precision.</p>
<p>This would be the often cited "premature optimization".</p>
|
<p>Don't care about this. There's always some error involved when using floats. If you're curious, try changing to double and see if this still happens.</p>
| 41,831
|
<p>I would like to write some data to a file in Ruby. What is the best way to do that?</p>
|
<pre><code>File.open("a_file", "w") do |f|
f.write "some data"
end
</code></pre>
<p>You can also use <code>f << "some data"</code> or <code>f.puts "some data"</code> according to personal taste/necessity to have newlines. Change the <code>"w"</code> to <code>"a"</code> if you want to append to the file instead of truncating with each open.</p>
|
<pre><code>filey = File.new("/path/to/the/file", APPEND)
filey.puts "stuff to write"
</code></pre>
| 18,171
|
<p>I hope I haven't painted myself into a corner. I've gotten what seems to be most of the way through implementing a Makefile and I can't get the last bit to work. I hope someone here can suggest a technique to do what I'm trying to do.</p>
<p>I have what I'll call "bills of materials" in version controlled files in a source repository and I build something like:</p>
<pre><code>make VER=x
</code></pre>
<p>I want my Makefile to use $(VER) as a tag to retrieve a BOM from the repository, generate a dependency file to include in the Makefile, rescan including that dependency, and then build the product. </p>
<p>More generally, my Makefile may have several targets -- A, B, C, etc. -- and I can build different versions of each so I might do:</p>
<pre><code>make A VER=x
make B VER=y
make C VER=z
</code></pre>
<p>and the dependency file includes information about all three targets.</p>
<p>However, creating the dependency file is somewhat expensive so if I do:</p>
<pre><code>make A VER=x
...make source (not BOM) changes...
make A VER=x
</code></pre>
<p>I'd really like the Makefile to not regenerate the dependency. And just to make things as complicated as possible, I might do:</p>
<pre><code>make A VER=x
.. change version x of A's BOM and check it in
make A VER=x
</code></pre>
<p>so I need to regenerate the dependency on the second build.</p>
<p>The check out messes up the timestamps used to regenerate the dependencies so I think I need a way for the dependency file to depend not on the BOM but on some indication that the BOM changed.</p>
<p>What I've come to is making the BOM checkout happen in a .PHONY target (so it always gets checked out) and keeping track of the contents of the last checkout in a ".sig" file (if the signature file is missing or the contents are different than the signature of the new file, then the BOM changed), and having the dependency generation depend on the signatures). At the top of my Makefile, I have some setup:</p>
<pre><code>BOMS = $(addsuffix .bom,$(MAKECMDGOALS)
SIGS = $(subst .bom,.sig,$(BOMS))
DEP = include.d
-include $(DEP)
</code></pre>
<p>And it seems I always need to do:</p>
<pre><code>.PHONY: $(BOMS)
$(BOMS):
...checkout TAG=$(VER) $@
</code></pre>
<p>But, as noted above, if i do just that, and continue:</p>
<pre><code>$(DEP) : $(BOMS)
... recreate dependency
</code></pre>
<p>Then the dependency gets updated every time I invoke make. So I try:</p>
<pre><code>$(DEP) : $(SIGS)
... recreate dependency
</code></pre>
<p>and</p>
<pre><code>$(BOMS):
...checkout TAG=$(VER) $@
...if $(subst .bom,.sig,$@) doesn't exist
... create signature file
...else
... if new signature is different from file contents
... update signature file
... endif
...endif
</code></pre>
<p>But the dependency generation doesn't get tripped when the signature changes. I think it's because because $(SIGS) isn't a target, so make doesn't notice when the $(BOMS) rule updates a signature.</p>
<p>I tried creating a .sig:.bom rule and managing the timestamps of the checked out BOM with touch but that didn't work.</p>
<p>Someone suggested something like:</p>
<pre><code>$(DEP) : $(SIGS)
... recreate dependency
$(BOMS) : $(SIGS)
...checkout TAG=$(VER) $@
$(SIGS) :
...if $(subst .bom,.sig,$(BOMS)) doesn't exist
... create it
...else
... if new signature is different from file contents
... update signature file
... endif
...endif
</code></pre>
<p>but how can the BOM depend on the SIG when the SIG is created from the BOM? As I read that it says, "create the SIG from the BOM and if the SIG is newer than the BOM then checkout the BOM". How do I bootstrap that process? Where does the first BOM come from?</p>
|
<p>Make is very bad at being able to detect actual file changes, as opposed to just updated timestamps. </p>
<p>It sounds to me that the root of the problem is that the bom-checkout always modifies the timestamp of the bom, causing the dependencies to be regenerated. I would probably try to solve this problem instead -- try to checkout the bom without messing up the timestamp. A wrapper script around the checkout tool might do the trick; first checkout the bom to a temporary file, compare it to the already checked out version, and replace it only if the new one is different.</p>
<p>If you're not strictly bound to using make, there are other tools which are much better at detecting actual file changes (SCons, for example).</p>
|
<p>I'm not a make expert, but I would try have $(BOMS) depend on $(SIGS), and making the $(SIGS) target execute the if/else rules that you currently have under the $(BOMS) target.</p>
<pre><code>$(DEP) : $(SIGS)
... recreate dependency
$(BOMS) : $(SIGS)
...checkout TAG=$(VER) $@
$(SIGS) :
...if $(subst .bom,.sig,$(BOMS)) doesn't exist
... create it
...else
... if new signature is different from file contents
... update signature file
... endif
...endif
</code></pre>
<p><strong>EDIT:</strong> You're right, of course, you can't have $(BOM) depend on $(SIGS). But in order to have $(DEP) recreate, you need to have $(SIG) as a target. Maybe have an intermediate target that depends on both $(BOM) and $(SIG).</p>
<pre><code>$(DEP) : $(SIGS)
... recreate dependency
$(NEWTARGET) : $(BOMS) $(SIGS)
$(BOMS) :
...checkout TAG=$(VER) $@
$(SIGS) :
...if $(subst .bom,.sig,$(BOMS)) doesn't exist
... create it
...else
... if new signature is different from file contents
... update signature file
... endif
...endif
</code></pre>
<p>$(SIGS) might also need to depend on $(BOMS), I would play with that and see.</p>
| 9,705
|
<p>Can you specialize a template method within a template class without specializing the class template parameter?</p>
<p>Please note that the specialization is on the <em>value</em> of the template parameter, not its type.</p>
<p>This seems to compile under Visual Studio 2008 SP1 complier, but not GCC 4.2.4.</p>
<pre><code>#include <iostream>
using namespace std;
template <typename T>
class A
{
private:
template <bool b>
void testme();
template <>
void testme<true>() { cout << "true" << endl; };
template <>
void testme<false>() { cout << "false" << endl; };
public:
void test();
};
template<typename T> struct select {};
template<> struct select<int> { static const bool value = true; };
template<> struct select<double> { static const bool value = false; };
template <class T>
void A<T>::test() { testme<select<T>::value>(); }
int main(int argc, const char* argv[])
{
A<int> aInt;
A<double> aDouble;
aInt.test();
aDouble.test();
return 0;
}
</code></pre>
<p>GCC tells me:"error: explicit specialization in non-namespace scope ‘class A’"</p>
<p>If it is not supported in the standard, can anyone tell me why?</p>
|
<p>It is not supported in the standard (and it is apparently a known bug with Visual Studio that you <em>can</em> do it).</p>
<p>The standard doesn't allow an inner template (member function <em>or</em> class) to be specialized without the outer template being specialized as well. One of the reasons for this is that you can normally just overload the function:</p>
<pre><code>template<typename ty>
class A
{
public:
void foo(bool b);
void foo(int i);
};
</code></pre>
<p>Is equivalent to:</p>
<pre><code>template<typename ty>
class A
{
public:
template<typename ty2>
void foo(ty2);
template<>
void foo(bool b);
template<>
void foo(int i);
};
</code></pre>
|
<p>I've never heard of that being possible; it would make sense to me if it was <em>not</em> supported by all compilers. So here is an idea for a workaround:</p>
<p>Implement a template function outside of your class which takes the same action as the method. Then you can specialize this function, and it call it from the method. Of course, you'll also have to pass in any member variables that it needs (and pointers thereto if you want to modify their values).</p>
<p>You could also create another template class as a subclass, and specialize that one, although I've never done this myself and am not 100% sure it would work. (Please comment to augment this answer if you know whether or not this second approach would work!)</p>
| 9,005
|
<p>I'm trying to create a POST request, unfortunately the body of the POST never seems to be sent.</p>
<p>Below is the code that I'm using. The code is invoked when a user clicks on a link, not a form "submit" button. It runs without error, invokes the servlet that is being called but, as I mentioned earlier, the body of the POST never seems to be sent.</p>
<p>I can validate that the request body is never sent since I have access to the servlet being called.</p>
<p>I've tried using "parameters" in replace of "requestBody." I've also tried using a parameter string (x=a?y=b). I've also validated that "ckULK" does contain a valid value.</p>
<p>Any ideas?</p>
<pre><code>new Ajax.Request(sURL,
{
method: 'POST'
, contentType: "text/x-json"
, requestBody: {ulk:ckULK}
, onFailure:
function(transport)
{
vJSONResp = transport.responseText;
var JSON = eval( "(" + vJSONResp + ")" );
updateStatus(JSON.code + ": " + JSON.message);
} // End onFailure
, onSuccess:
function(transport)
{
if (200 == transport.status)
{
vJSONResp = transport.responseText;
}
else
{
log.value += "\n" + transport.status;
}
} // End onSuccess
}); // End Ajax.request
</code></pre>
|
<p>These are the kind of situations where Firebug and Firefox are really helpful. I suggest you install Firebug if you don't have it and check the request that is being sent.</p>
<p>You also definitely need to stick to <code>parameters</code> instead of <code>requestBody</code>.</p>
<p>This:</p>
<pre><code>new Ajax.Request(sURL,
{
method: 'POST',
parameters: 'hello=world&test=yes',
onFailure: function(transport) {
vJSONResp = transport.responseText;
var JSON = eval( "(" + vJSONResp + ")" );
updateStatus(JSON.code + ": " + JSON.message);
},
onSuccess: function(transport) {
if (200 == transport.status) {
vJSONResp = transport.responseText;
} else {
log.value += "\n" + transport.status;
}
}
});
</code></pre>
<p>Should definitely work.</p>
|
<p>When I hit this problem the solution was to remove <code>contentType</code> from <code>Ajax.Request</code> options. </p>
<p>In <a href="https://stackoverflow.com/a/216074/1483">answer</a> by <a href="https://stackoverflow.com/users/16417/paolo-bergantino">Paolo Bergantino</a> <code>contentType</code> is not defined in <code>Ajax.Request</code> options.</p>
<p>From unknown reasons params defined in <code>parameters</code> wasn't sent (FF didn't show them and my server saw empty POST body).</p>
<p>One of my coworkers suggested to use <code>postBody</code> instead of <code>parameters</code> but I didn't try it.</p>
| 26,562
|
<p>What's the best way to parse fragments of HTML in C#?</p>
<p>For context, I've inherited an application that uses a great deal of composite controls, which is fine, but a good deal of the controls are rendered using a long sequence of literal controls, which is fairly terrifying. I'm trying to get the application into unit tests, and I want to get these controls under tests that will find out if they're generating well formed HTML, and in a dream solution, validate that HTML.</p>
|
<p>Have a look at the <a href="http://www.codeplex.com/htmlagilitypack" rel="nofollow noreferrer">HTMLAgility</a> pack. It's very compatible with the .NET XmlDocument class, but it much more forgiving about HTML that's not clean/valid XHTML.</p>
|
<p>You can also look into <a href="http://tidy.sourceforge.net/" rel="nofollow noreferrer">HTML Tidy</a> for HTML parsing/cleanup. I don't think they have specific .NET libraries, but you might be able to run the binary via command-line, or IKVM the java libraries.</p>
| 31,138
|
<p>I've switched computers a few times recently, and somewhere along the way I lost my .emacs. I'm trying to build it up again, but while I'm at it, I thought I'd pick up other good configurations that other people use.</p>
<p>So, if you use Emacs, what's in <i>your</i> .emacs?</p>
<p>Mine is pretty barren right now, containing only:</p>
<ol>
<li>Global font-lock-mode! <code>(global-font-lock-mode 1)</code></li>
<li>My personal preferences with respect to indentation, tabs, and spaces.</li>
<li>Use cperl-mode instead of perl-mode.</li>
<li>A shortcut for compilation.</li>
</ol>
<p>What do you think is useful?</p>
|
<p>Use the <a href="http://dotfiles.org/.emacs" rel="nofollow noreferrer">ultimate dotfiles site</a>. Add your '.emacs' here. Read the '.emacs' of others.</p>
|
<p>One line to amend the load path
One line to load my init library
One line to load my emacs init files</p>
<p>Of course, the "emacs init files" are quite numerous, one per specific thing, loaded in a deterministic order.</p>
| 18,617
|
<p>I have a list of input words separated by comma. I want to sort these words by alphabetical and length. How can I do this without using the built-in sorting functions?</p>
|
<p>Good question!! Sorting is probably the most important concept to learn as an up-and-coming computer scientist.</p>
<p>There are actually lots of different algorithms for sorting a list.</p>
<p>When you break all of those algorithms down, the most fundamental operation is the comparison of two items in the list, defining their "natural order".</p>
<p>For example, in order to sort a list of integers, I'd need a function that tells me, given any two integers X and Y whether X is less than, equal to, or greater than Y.</p>
<p>For your strings, you'll need the same thing: a function that tells you which of the strings has the "lesser" or "greater" value, or whether they're equal.</p>
<p>Traditionally, these "comparator" functions look something like this:</p>
<pre><code>int CompareStrings(String a, String b) {
if (a < b)
return -1;
else if (a > b)
return 1;
else
return 0;
}
</code></pre>
<p>I've left out some of the details (like, how do you compute whether a is less than or greater than b? clue: iterate through the characters), but that's the basic skeleton of any comparison function. It returns a value less than zero if the first element is smaller and a value greater than zero if the first element is greater, returning zero if the elements have equal value.</p>
<p>But what does that have to do with sorting?</p>
<p>A sort routing will call that function for pairs of elements in your list, using the result of the function to figure out how to rearrange the items into a sorted list. The comparison function defines the "natural order", and the "sorting algorithm" defines the logic for calling and responding to the results of the comparison function.</p>
<p>Each algorithm is like a big-picture strategy for guaranteeing that ANY input will be correctly sorted. Here are a few of the algorithms that you'll probably want to know about:</p>
<p><strong>Bubble Sort:</strong></p>
<p>Iterate through the list, calling the comparison function for all adjacent pairs of elements. Whenever you get a result greater than zero (meaning that the first element is larger than the second one), swap the two values. Then move on to the next pair. When you get to the end of the list, if you didn't have to swap ANY pairs, then congratulations, the list is sorted! If you DID have to perform any swaps, go back to the beginning and start over. Repeat this process until there are no more swaps.</p>
<p>NOTE: this is usually not a very efficient way to sort a list, because in the worst cases, it might require you to scan the whole list as many as N times, for a list with N elements.</p>
<p><strong><em>Merge Sort:</em></strong></p>
<p>This is one of the most popular divide-and-conquer algorithms for sorting a list. The basic idea is that, if you have two already-sorted lists, it's easy to merge them. Just start from the beginning of each list and remove the first element of whichever list has the smallest starting value. Repeat this process until you've consumed all the items from both lists, and then you're done!</p>
<pre><code>1 4 8 10
2 5 7 9
------------ becomes ------------>
1 2 4 5 7 8 9 10
</code></pre>
<p>But what if you don't have two sorted lists? What if you have just one list, and its elements are in random order?</p>
<p>That's the clever thing about merge sort. You can break any single list into smaller pieces, each of which is either an unsorted list, a sorted list, or a single element (which, if you thing about it, is actually a sorted list, with length = 1).</p>
<p>So the first step in a merge sort algorithm is to divide your overall list into smaller and smaller sub lists, At the tiniest levels (where each list only has one or two elements), they're very easy to sort. And once sorted, it's easy to merge any two adjacent sorted lists into a larger sorted list containing all the elements of the two sub lists.</p>
<p>NOTE: This algorithm is <strong><em>much</em></strong> better than the bubble sort method, described above, in terms of its worst-case-scenario efficiency. I won't go into a detailed explanation (which involves some fairly trivial math, but would take some time to explain), but the quick reason for the increased efficiency is that this algorithm breaks its problem into ideal-sized chunks and then merges the results of those chunks. The bubble sort algorithm tackles the whole thing at once, so it doesn't get the benefit of "divide-and-conquer".</p>
<hr>
<p>Those are just two algorithms for sorting a list, but there are a lot of other interesting techniques, each with its own advantages and disadvantages: Quick Sort, Radix Sort, Selection Sort, Heap Sort, Shell Sort, and Bucket Sort.</p>
<p>The internet is overflowing with interesting information about sorting. Here's a good place to start:</p>
<p><a href="http://en.wikipedia.org/wiki/Sorting_algorithms" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Sorting_algorithms</a></p>
|
<p>If you don't want to use build-in-functions, you have to create one by your self. I would recommend <em>Bubble sort</em> or some similar algorithm. Bubble sort is not an effective algoritm, but it get the works done, and is easy to understand.</p>
<p>You will find much good reading on <a href="http://en.wikipedia.org/wiki/Sorting_algorithm" rel="nofollow noreferrer">wikipedia</a>.</p>
| 42,499
|
<p>I have a large codebase without Javadoc, and I want to run a program to write a skeleton with the basic Javadoc information (e.g., for each method's parameter write @param...), so I just have to fill the gaps left.</p>
<p>Anyone know a good solution for this?</p>
<p><strong>Edit:</strong></p>
<p>JAutodoc is what I was looking for. It has Ant tasks, an Eclipse plugin, and uses Velocity for the template definition.</p>
|
<p>The <a href="http://jautodoc.sourceforge.net/" rel="noreferrer">JAutodoc</a> plugin for eclipse does exactly what you need, but with a package granularity : </p>
<p>right click on a package, select "Add javadoc for members..." and the skeleton will be added.</p>
<p>There are numerous interesting options : templates for javadoc, adding a TODO in the header of every file saying : "template javadoc, must be filled...", etc.</p>
|
<p>If you right-click in the source of a file in Eclipse, it has a Javadoc generation option under the source menu.</p>
| 4,941
|
<p>I'm trying TripleDES Encryption with ECB mode. My code looks like that:</p>
<pre><code>public static string EncryptDES(string InputText)
{
byte[] key = new byte[] { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48 };
byte[] clearData = System.Text.Encoding.UTF8.GetBytes(InputText);
MemoryStream ms = new MemoryStream();
TripleDES alg = TripleDES.Create();
alg.Key = key;
alg.Mode = CipherMode.ECB;
CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(clearData, 0, clearData.Length);
cs.FlushFinalBlock();
byte[] CipherBytes = ms.ToArray();
ms.Close();
cs.Close();
string EncryptedData = Convert.ToBase64String(CipherBytes);
return EncryptedData;
}
</code></pre>
<p>When I run a test I got an exception that the "Length of Data to decrypt is invalid."</p>
<p>Does anyone knows what I'm doing wrong?</p>
<p>Thank you in advance.</p>
<h2>Update</h2>
<p>My bad !
I found my problem
Instead of using <code>alg.CreateEncryptor()</code> I was using <code>alg.CreateDecyptor()</code>.</p>
<p>A copy paste issue. :(</p>
<p>Thanks for help, guys</p>
|
<p>My bad !
I found my problem
Instead of using <code>alg.CreateEncryptor()</code> I was using <code>alg.CreateDecyptor()</code>.</p>
<p>A copy paste issue. :(</p>
<p>Thanks for help, guys</p>
|
<p>It sounds like your encryption method is using a different key/salt combo than the decryption method and it can't decrypt the data.</p>
<p>During debugging it might be benefical to convert your key & salt to readable strings and waste the cycle's converting them to bytes.. at least for readability.</p>
| 38,935
|
<p>Sorry, I'm new in 3D printing and modeling and I need help.</p>
<p>I bought a 3D model with a hollow part of the body that doesn't print on my printer normally (with very high resolution (layer is 0.12 mm, the nozzle is 0.4 mm) because the walls are very thin). I tried to make it as a solid in MeshMixer or ZBrush, but I can't. Can you help me, how I can fix this defect?</p>
<p>I use Cura for slicing.</p>
<p>I know, that I can take a thinner nozzle (0.2 mm) and Cura will slice it better, but I want to make this model solid so I could print it with nozzle 0.4 mm.</p>
<p><a href="https://i.stack.imgur.com/QqOdU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QqOdU.png" alt="Hollow part of body" /></a></p>
<p><a href="https://i.stack.imgur.com/VZNwk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VZNwk.jpg" alt="How Cura have sliced that" /></a></p>
|
<p>The model clearly contains an enclosed surface, which is directed to the inside - in other words, it was modeled to contain a volume of air.</p>
<p>Those surfaces need to be removed to print the body solid. To do this, you could check if those surfaces constitute a separate shell for meshmixer. If yes, you can just go, run separate shells, remove those internal items, and then re-merge all other shells. Slicing that should result in the voids being filled.</p>
<p>If however the shell is meant to exist, then it should instead simply get its normals inverted. This is best done with modeling software such as blender. Some steps you need can be seen <a href="https://3dprinting.stackexchange.com/a/15881/8884">here</a></p>
|
<p>This is a problem with the model, you need to make sure that the model isn't hollow. You might be able to get around this though if you use scaffolding, it might recognize the overhand hand build supports for your print inside of your print, you just might have to mess around with the scaffolding settings a bit.</p>
| 1,938
|
<p>i have created a workflow activity that do give the item creater of a specific list full control on the item and set everyone else to read only access (permission) </p>
<p>someone told me that doing it this way (if i have a lot of users) the performance will go down dramatically </p>
<p>is that correct ?!!</p>
<p>if yes what is the best solution to create a list where any one can create new items but after the item is created only the creater can edit it and the rest of the users can read it only </p>
|
<p>Performance degradation will happen when you use large ACLs for each list item. Just make sure that item-level permissions basically have the minimum entries. For example:</p>
<ul>
<li>The user that has permissions to edit that item</li>
<li>A single security group that contains all the users with only Reader permissions.</li>
</ul>
<p>So, can Sharepoint offer these default permissions OOB? Not that I'm aware of. The only option that I can think of is using workflows that set these permissions dinamycally when the document is uploaded.</p>
<p>If you want to avoid performance degradation just make sure that you never display (or iterate using the object model) more than 2000 of those items in a Fine Grained Permissions list. THAT would definitely cause major performance issues.</p>
|
<p>Yes, you might solve this with workflows but that might be a bit clumsy and it might slow your server.</p>
<p>The better option is to use List Settings > Advanced Settings > Item-level Permissions. </p>
<p>This feature is not available for Document and Form Libraries.</p>
| 11,097
|
<p>trying to get a side project hobby going to keep me motivated from my 9-5 job on C# and was looking at Boo. some ?'s</p>
<ul>
<li>what has your experience being with Boo?</li>
<li>what kind of apps/projects have you done with Boo or </li>
<li>what is Boo capable of?</li>
</ul>
<p>Guess being the web world, would like to get my hands dirty with desktop applications etc.</p>
|
<p>My personal experiences with Boo were from about 18 months back, and I've not followed it actively since then, <strong>so keep that in mind wrt to what I say</strong>. It is a <em>cool</em> language. But it is also experimental. What this means in practical terms:</p>
<ul>
<li>You can do cool things w/ the language. The macros they allow, plus mixing in good features from ruby and python and other languages.</li>
<li>There is a WinForms designer you can use via SharpDevelop (which has Boo integrated as a standard development language). </li>
<li><p>There inconsistencies and bugs at occasionally critical areas because it is not done yet.</p></li>
<li><p>I'm not sure if Generics can be created yet w/ Boo, but they certainly can be consumed.</p></li>
<li><p>Performance is good, but the compiler doesn't have an optimizer.</p></li>
<li><p>Type inference is cool. Duck typing is cool. All that lets you approach the illusion of dynamic typing.</p></li>
</ul>
<p>Personally, I worked on a tool to make creative writing easier. Think IDE for writers.</p>
|
<p>You should have a look at some of Boo's interesting <a href="http://boo.codehaus.org/Language+Features" rel="nofollow noreferrer">language features</a>.</p>
| 25,303
|
<p>I don't understand where the extra bits are coming from in <a href="http://en.wikipedia.org/wiki/S-box" rel="nofollow noreferrer">this article</a> about s-boxes. Why doesn't the s-box take in the same number of bits for input as output?</p>
|
<p>It is the way s-boxes work. They can be m * n ==> m bit input , n bit output.
For example, in the <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard" rel="nofollow noreferrer">AES</a> S-box the number of bits in input is equal to the number of bits in output.</p>
<p>In <a href="http://en.wikipedia.org/wiki/Data_Encryption_Standard" rel="nofollow noreferrer">DES</a>, m=6 and n=4.</p>
<p>The input is expanded from 32 to 48 bits in the first stages of DES. So it is be reduced to 32 bits again by applying one round of S-box substitution. Thus no information is lost here.</p>
<p>The Wikipedia article on itself can be a bit confusing. It will make people think that information is lost. You should read the article in conjuncture with implementation details of some encryption algorithm using s-boxes.</p>
|
<p>What extra bits? They are going from 6 to 4.</p>
<p>EDIT: Whoops! I'm an idiot. This is kinda like a 2nd grade multiplication table. They strip the outer bits off of the 6-bit block to be encypted, and leave the middle 4. Just like a table for an arithmatic operation, they go down one side, and find the outer bit sequence, then across the top and find the middle ones. To answer your question, it could input and output the same number of bits, but this s-box is just set up to do it the way it does. Its arbitrary.</p>
| 4,378
|
<p>I use the Boost Test framework for my C++ code but there are two problems with it that are probably common to all C++ test frameworks:</p>
<ul>
<li>There is no way to create automatic test stubs (by extracting public functions from selected classes for example).</li>
<li>You cannot run a single test - you have to run the entire 'suite' of tests (unless you create lots of different test projects I guess).</li>
</ul>
<p>Does anyone know of a better testing framework or am I forever to be jealous of the test tools available to Java/.NET developers?</p>
|
<p>I've just pushed my own framework, <a href="http://www.levelofindirection.com/journal/2010/12/28/unit-testing-in-c-and-objective-c-just-got-easier.html" rel="noreferrer">CATCH</a>, out there. It's still under development but I believe it already surpasses most other frameworks.
Different people have different criteria but I've tried to cover most ground without too many trade-offs.
Take a look at my linked blog entry for a taster. My top five features are:</p>
<ul>
<li>Header only</li>
<li>Auto registration of function and method based tests</li>
<li>Decomposes standard C++ expressions into LHS and RHS (so you don't need a whole family of assert macros).</li>
<li>Support for nested sections within a function based fixture</li>
<li>Name tests using natural language - function/ method names are generated</li>
</ul>
<p>It <em>doesn't</em> do generation of stubs - but that's a fairly specialised area. I think <a href="http://www.typemock.com/isolatorpp-product-page" rel="noreferrer">Isolator++</a> is the first tool to truly pull that off. Note that Mocking/ stubbing frameworks are usually independent of unit testing frameworks. CATCH works particularly well with mock objects as test state is not passed around by context.</p>
<p>It also has Objective-C bindings.</p>
<p>[update]</p>
<p>Just happened back across this answer of mine from a few years ago. Thanks for all the great comments!
Obviously Catch has developed on a lot in that time. It now has support for BDD style testing (given/ when/ then), tags, now in a <em>single</em> header, and loads of internal improvements and refinements (e.g. richer command line, clear and expressive output etc). <a href="http://www.levelofindirection.com/journal/2013/6/28/catch-10.html" rel="noreferrer">A more up-to-date blog post is here.</a></p>
|
<p>Eclipse/JUnit is a solid package for java, and there are C++ extensions/equivalents for both. It can do what you're talking about. Of course, you'd have to change IDEs...</p>
| 11,337
|
<p>Is it possible to load child entities in a <strong><em>single</em></strong> query without using DataLoadOptions?</p>
<p>I am using one data context per request in an asp.net web application and trying to get around the linq to sql limitation of not being able to change dataloadoptions once a query has been executed.</p>
<p>Thanks.</p>
|
<p>If you don't mind the link to the data context, as you say you don't, you could write a stored procedure that returns multiple results that map to your objects. <a href="http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/05/linq-to-sql-stored-procedures-with-multiple-results-imultipleresults.aspx" rel="nofollow noreferrer">Read more about it here</a>.</p>
|
<p>Use Include...</p>
<p>var q = from u in context.Users.Include("address")...</p>
<p>Would cause the address child object to be populated as well.</p>
| 29,497
|
<p>I have a large c# solution file (~100 projects), and I am trying to improve build times. I think that "Copy Local" is wasteful in many cases for us, but I am wondering about best practices.</p>
<p>In our .sln, we have application A depending on assembly B which depends on assembly C. In our case, there are dozens of "B" and a handful of "C". Since these are all included in the .sln, we're using project references. All assemblies currently build into $(SolutionDir)/Debug (or Release).</p>
<p>By default, Visual Studio marks these project references as "Copy Local", which results in every "C" being copied into $(SolutionDir)/Debug once for every "B" that builds. This seems wasteful. What can go wrong if I just turn "Copy Local" off? What do other people with large systems do?</p>
<p>FOLLOWUP:</p>
<p>Lots of responses suggest breaking up the build into smaller .sln files... In the example above, I would build the foundation classes "C" first, followed by the bulk of the modules "B", and then a few applications, "A". In this model, I need to have non-project references to C from B. The problem I run into there is that "Debug" or "Release" gets baked into the hint path and I wind up building my Release builds of "B" against debug builds of "C". </p>
<p>For those of you that split the build up into multiple .sln files, how do you manage this problem?</p>
|
<p>In a previous project I worked with one big solution with project references and bumped into a performance problem as well. The solution was three fold:</p>
<ol>
<li><p>Always set the Copy Local property to false and enforce this via a custom msbuild step</p></li>
<li><p>Set the output directory for each project to the same directory (preferably relative to $(SolutionDir)</p></li>
<li><p>The default cs targets that get shipped with the framework calculate the set of references to be copied to the output directory of the project currently being built. Since this requires calculating a transitive closure under the 'References' relation this can become <strong>VERY</strong> costly. My workaround for this was to redefine the <code>GetCopyToOutputDirectoryItems</code> target in a common targets file (eg. <code>Common.targets</code> ) that's imported in every project after the import of the <code>Microsoft.CSharp.targets</code>. Resulting in every project file to look like the following: </p>
<pre><code><Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
... snip ...
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="[relative path to Common.targets]" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
</code></pre></li>
</ol>
<p>This reduced our build time at a given time from a couple of hours (mostly due to memory constraints), to a couple of minutes.</p>
<p>The redefined <code>GetCopyToOutputDirectoryItems</code> can be created by copying the lines 2,438–2,450 and 2,474–2,524 from <code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets</code> into <code>Common.targets</code>.</p>
<p>For completeness the resulting target definition then becomes:</p>
<pre><code><!-- This is a modified version of the Microsoft.Common.targets
version of this target it does not include transitively
referenced projects. Since this leads to enormous memory
consumption and is not needed since we use the single
output directory strategy.
============================================================
GetCopyToOutputDirectoryItems
Get all project items that may need to be transferred to the
output directory.
============================================================ -->
<Target
Name="GetCopyToOutputDirectoryItems"
Outputs="@(AllItemsFullPathWithTargetPath)"
DependsOnTargets="AssignTargetPaths;_SplitProjectReferencesByFileExistence">
<!-- Get items from this project last so that they will be copied last. -->
<CreateItem
Include="@(ContentWithTargetPath->'%(FullPath)')"
Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"
>
<Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectoryAlways"
Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectory"
Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
</CreateItem>
<CreateItem
Include="@(_EmbeddedResourceWithTargetPath->'%(FullPath)')"
Condition="'%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always' or '%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"
>
<Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectoryAlways"
Condition="'%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectory"
Condition="'%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
</CreateItem>
<CreateItem
Include="@(Compile->'%(FullPath)')"
Condition="'%(Compile.CopyToOutputDirectory)'=='Always' or '%(Compile.CopyToOutputDirectory)'=='PreserveNewest'">
<Output TaskParameter="Include" ItemName="_CompileItemsToCopy"/>
</CreateItem>
<AssignTargetPath Files="@(_CompileItemsToCopy)" RootFolder="$(MSBuildProjectDirectory)">
<Output TaskParameter="AssignedFiles" ItemName="_CompileItemsToCopyWithTargetPath" />
</AssignTargetPath>
<CreateItem Include="@(_CompileItemsToCopyWithTargetPath)">
<Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectoryAlways"
Condition="'%(_CompileItemsToCopyWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectory"
Condition="'%(_CompileItemsToCopyWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
</CreateItem>
<CreateItem
Include="@(_NoneWithTargetPath->'%(FullPath)')"
Condition="'%(_NoneWithTargetPath.CopyToOutputDirectory)'=='Always' or '%(_NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"
>
<Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectoryAlways"
Condition="'%(_NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectory"
Condition="'%(_NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
</CreateItem>
</Target>
</code></pre>
<p>With this workaround in place I found it workable to have as much as > 120 projects in one solution, this has the main benefit that the build order of the projects can still be determined by VS instead of doing that by hand by splitting up your solution.</p>
|
<p>Usually, you only need to Copy Local if you want your project using the DLL that is in your Bin vs. what is somewhere else (the GAC, other projects, etc.)</p>
<p>I would tend to agree with the other folks that you should also try, if at all possible, to break up that solution.</p>
<p>You can also use Configuration Manager to make yourself different build configurations within that one solution that will only build given sets of projects.</p>
<p>It would seem odd if all 100 projects relied on one another, so you should be able to either break it up or use Configuration Manager to help yourself out.</p>
| 35,509
|
<p>If a class defined an annotation, is it somehow possible to force its subclass to define the same annotation?</p>
<p>For instance, we have a simple class/subclass pair that share the <code>@Author @interface.</code>
What I'd like to do is force each further subclass to define the same <code>@Author</code> annotation, preventing a <code>RuntimeException</code> somewhere down the road. </p>
<p>TestClass.java:</p>
<pre><code>import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@interface Author { String name(); }
@Author( name = "foo" )
public abstract class TestClass
{
public static String getInfo( Class<? extends TestClass> c )
{
return c.getAnnotation( Author.class ).name();
}
public static void main( String[] args )
{
System.out.println( "The test class was written by "
+ getInfo( TestClass.class ) );
System.out.println( "The test subclass was written by "
+ getInfo( TestSubClass.class ) );
}
}
</code></pre>
<p>TestSubClass.java:</p>
<pre><code>@Author( name = "bar" )
public abstract class TestSubClass extends TestClass {}
</code></pre>
<p>I know I can enumerate all annotations at runtime and check for the missing <code>@Author</code>, but I'd really like to do this at compile time, if possible.</p>
|
<p>You can do that with JSR 269, at compile time.
See : <a href="http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api" rel="nofollow noreferrer">http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api</a></p>
<p>Edit 2020-09-20: Link is dead, archived version here : <a href="https://web.archive.org/web/20150516080739/http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html" rel="nofollow noreferrer">https://web.archive.org/web/20150516080739/http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html</a></p>
|
<p>I am quite sure that this is impossible to do at compile time.</p>
<p>However, this is an obvious task for a "unit"-test. If you have conventions like this that you would like enforced, but which can be difficult or impossible to check with the compiler, "unit"-tests are a simple way to check them.</p>
<p>Another possibility is to implement a custom rule in a static analyzer. There are many options here, too.</p>
<p>(I put unit in scare-quotes, since this is really a test of conventions, rather than of a specific unit. But it should run together with your unit-tests).</p>
| 12,098
|
<p>How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the <code>fork()</code> system call, using Python?</p>
<p>I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.</p>
|
<p>Use the python <a href="http://docs.python.org/library/multiprocessing.html" rel="noreferrer">multiprocessing module</a> which will work everywhere.</p>
<p>Here is a <a href="http://www.ibm.com/developerworks/aix/library/au-multiprocessing/" rel="noreferrer">IBM developerWords article</a> that shows how to convert from os.fork() to the multiprocessing module.</p>
|
<p>Possibly a version of spawn() for python? <a href="http://en.wikipedia.org/wiki/Spawn_(operating_system)" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Spawn_(operating_system)</a></p>
| 4,337
|
<p>Is there a tool that will find for me all the css classes that I am referencing in my HTML that don't actually exist?</p>
<p>ie. if I have <ul class="topnav" /> in my HTML and the topnav class doesn't exist in any of the referenced CSS files.</p>
<p>This is similar to <a href="https://stackoverflow.com/questions/33242/how-can-i-find-unused-images-and-css-styles-in-a-website">SO#33242</a>, which asks how to find unused CSS styles. This isn't a duplicate, as that question asks which CSS classes are not used. This is the opposite problem.</p>
|
<p>You can put this JavaScript in the page that can perform this task for you:</p>
<pre><code>function forItems(a, f) {
for (var i = 0; i < a.length; i++) f(a.item(i))
}
function classExists(className) {
var pattern = new RegExp('\\.' + className + '\\b'), found = false
try {
forItems(document.styleSheets, function(ss) {
// decompose only screen stylesheets
if (!ss.media.length || /\b(all|screen)\b/.test(ss.media.mediaText))
forItems(ss.cssRules, function(r) {
// ignore rules other than style rules
if (r.type == CSSRule.STYLE_RULE && r.selectorText.match(pattern)) {
found = true
throw "found"
}
})
})
} catch(e) {}
return found
}
</code></pre>
|
<p><a href="http://www.jetbrains.com/idea/features/html_css_editor.html" rel="nofollow noreferrer" title="IntelliJ Idea">IntelliJ Idea</a> tool does that as well. </p>
| 10,462
|
<p>I am building web client for CodeCentral web service from CodeGear web site.</p>
<p>I need to restrict number of items return by Search operation of CodeGear web service, say it, 10 per page. This way I can minimize loading of my web page.</p>
<p>I just don't know how to do it. Any ideas?</p>
|
<p>Sorry, I don't know the answer off hand.</p>
<p>I would suggest you contact John Kaster of CodeGear. He would know all the ins and outs of that. I haven't seen him posting here. Usually the email is [first initial][last name]@codegear.com. You might also try posting in the <a href="https://forums.codegear.com/forum.jspa?forumID=8" rel="nofollow noreferrer">Developer Network / CodeCentral forum</a> which I imagine John and his team will be monitoring.</p>
|
<p>You're right. The search form on the CodeCentral page lists the maximum number of entries as an option (the "Show" option), but does not allow you to select the option. And trying various obvious parameter values doesn't work.</p>
<p>I haven't tried it, but what might help you is if you research the CodeCentral Expert, which is a package to help search the CodeCentral website from within Delphi and C++ Builder: <a href="http://dn.codegear.com/article/23023" rel="nofollow noreferrer">http://dn.codegear.com/article/23023</a> </p>
<p>The package seems to be quite old, since comments on that page date from 2000, so there's no guarantee that it will work with the new site. However, checking through archive.org, it appears that the CodeCentral search page has remained the same for quite a number of years, and the search page, and even the missing "Show" option, has not changed over that time.</p>
<p>Even if the package doesn't work, maybe the package will give you the correct parameters you need for the calls to their search.</p>
<p>Otherwise, you'll have to send an email as previously answered.</p>
| 39,622
|
<p>So, I know that try/catch does add some overhead and therefore isn't a good way of controlling process flow, but where does this overhead come from and what is its actual impact?</p>
|
<p>I'm not an expert in language implementations (so take this with a grain of salt), but I think one of the biggest costs is unwinding the stack and storing it for the stack trace. I suspect this happens only when the exception is thrown (but I don't know), and if so, this would be decently sized hidden cost every time an exception is thrown... so it's not like you are just jumping from one place in the code to another, there is a lot going on.</p>
<p>I don't think it's a problem as long as you are using exceptions for EXCEPTIONAL behavior (so not your typical, expected path through the program).</p>
|
<p>Let us analyse one of the biggest possible costs of a try/catch block when used where it shouldn't need to be used:</p>
<pre><code>int x;
try {
x = int.Parse("1234");
}
catch {
return;
}
// some more code here...
</code></pre>
<p>And here's the one without try/catch:</p>
<pre><code>int x;
if (int.TryParse("1234", out x) == false) {
return;
}
// some more code here
</code></pre>
<p>Not counting the insignificant white-space, one might notice that these two equivelant pieces of code are almost exactly the same length in bytes. The latter contains 4 bytes less indentation. Is that a bad thing?</p>
<p>To add insult to injury, a student decides to loop while the input can be parsed as an int. The solution without try/catch might be something like:</p>
<pre><code>while (int.TryParse(...))
{
...
}
</code></pre>
<p>But how does this look when using try/catch?</p>
<pre><code>try {
for (;;)
{
x = int.Parse(...);
...
}
}
catch
{
...
}
</code></pre>
<p>Try/catch blocks are magical ways of wasting indentation, and we still don't even know the reason it failed! Imagine how the person doing debugging feels, when code continues to execute past a serious logical flaw, rather than halting with a nice obvious exception error. Try/catch blocks are a lazy man's data validation/sanitation.</p>
<p>One of the smaller costs is that try/catch blocks do indeed disable certain optimizations: <a href="http://msmvps.com/blogs/peterritchie/archive/2007/06/22/performance-implications-of-try-catch-finally.aspx" rel="nofollow noreferrer">http://msmvps.com/blogs/peterritchie/archive/2007/06/22/performance-implications-of-try-catch-finally.aspx</a>. I guess that's a positive point too. It can be used to disable optimizations that might otherwise cripple safe, sane message passing algorithms for multithreaded applications, and to catch possible race conditions ;) That's about the only scenario I can think of to use try/catch. Even that has alternatives.</p>
| 7,553
|
<p>I'm trying to recreate the iPhone flick / scroll event in a window using JavaScript.</p>
<p>Starting with JQuery, I'm measuring the mouse's acceleration and offset during click - drag - release events using a timer:</p>
<pre><code>var MouseY = {
init: function(context) {
var self = this;
self._context = context || window
self._down = false;
self._now = 0;
self._last = 0;
self._offset = 0;
self._timer = 0;
self._acceleration = 0;
$(self._context).mousedown(function() {self._down = true;});
$(self._context).mouseup(function() {self._down = false;});
$(self._context).mousemove(function(e) {self.move(e);});
},
move: function(e) {
var self = this;
self._timer++;
self._last = self._now;
self._now = e.clientY + window.document.body.scrollTop;
self._offset = self._now - self._last;
self._acceleration = self._offset / self._timer;
},
reset: function() {
this._offset = 0;
this._acceleration = 0;
this._timer = 0;
}
};
$(function() {
MouseY.init();
setInterval(function() {
$('#info').html(
'_acceleration:' + MouseY._acceleration + '<br />' +
'_now:' + MouseY._now + '<br />' +
'_offset:' + MouseY._offset + '<br />' +
'_timer:' + MouseY._timer + '<br />'
);
MouseY.reset();
}, 10);
});
</code></pre>
<p>Now the problem is translating that acceleration into screen movement - are there any algorithms (easing?) or animation libraries that could help me out on this? (I've looked into JQuery's .animate() but I'm unsure of how to apply it continuously during the drag events!</p>
<p><strong>Update - final solution here:</strong></p>
<p><a href="http://johnboxall.github.com/iphone.html" rel="noreferrer">http://johnboxall.github.com/iphone.html</a></p>
|
<p>Hit up this link for the full explanation of one approach that seems to be what you're looking for.</p>
<p><a href="http://www.faqts.com/knowledge_base/view.phtml/aid/14742/fid/53" rel="nofollow noreferrer">http://www.faqts.com/knowledge_base/view.phtml/aid/14742/fid/53</a></p>
<p>Here's an excerpt:</p>
<blockquote>
<p>This handler then sets up event
capture for mouse movement and stores
mouse cursor positions in variables
mouseX and mouseY. It then starts the
timer monitorMouse() which measures
mouse cursor speed by sampling the
values in these variables at regular
intervals. The variables mouseLeft
and mouseTop hold each samplings mouse
positions and the sampling rate is
set to 100 milliseconds in the
variable monitor.timerDelay.</p>
</blockquote>
<p>And some of the author's code:</p>
<pre><code>nn4 = (document.layers)? true:false;
mouseLeft = mouseTop = mouseX = mouseY = 0;
monitor = {
timerDelay:100,
moveLimit:2,
sampleLimit:10
};
function startMonitor(thisText) {
if (!tip) return;
toolTipText = thisText;
writeTooltip(toolTipText);
document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = function (evt) {
mouseX = evt.pageX;
mouseY = evt.pageY;
return true;
}
monitorMouse();
}
function stopMonitor() {
if (!tip) return;
hideTooltip();
if (monitor.timer) {
clearTimeout(monitor.timer);
monitor.timer = null;
}
document.releaseEvents(Event.MOUSEMOVE);
document.onmousemove = null;
monitor.slowSamples = 0;
}
function monitorMouse() {
if (Math.abs(mouseX - mouseLeft) > monitor.moveLimit
|| Math.abs(mouseY - mouseTop) > monitor.moveLimit)
{
monitor.slowSamples = 0;
}
else if (++monitor.slowSamples > monitor.sampleLimit) {
showTooltip();
return;
}
mouseLeft = mouseX;
mouseTop = mouseY;
monitor.timer = setTimeout("monitorMouse()",monitor.timerDelay);
}
</code></pre>
|
<p>You might be interested in the jQuery plugin named overscroll:
<a href="http://www.azoffdesign.com/overscroll" rel="nofollow noreferrer">http://www.azoffdesign.com/overscroll</a> (<a href="https://github.com/azoff/Overscroll" rel="nofollow noreferrer">GitHub page</a>)</p>
| 49,782
|
<p>I currently have 2 <code>BufferedReader</code>s initialized on the same text file. When I'm done reading the text file with the first <code>BufferedReader</code>, I use the second one to make another pass through the file from the top. Multiple passes through the same file are necessary.</p>
<p>I know about <code>reset()</code>, but it needs to be preceded with calling <code>mark()</code> and <code>mark()</code> needs to know the size of the file, something I don't think I should have to bother with.</p>
<p>Ideas? Packages? Libs? Code?</p>
<p>Thanks
TJ</p>
|
<p>What's the disadvantage of just creating a new <code>BufferedReader</code> to read from the top? I'd expect the operating system to cache the file if it's small enough.</p>
<p>If you're concerned about performance, have you proved it to be a bottleneck? I'd just do the simplest thing and not worry about it until you have a specific reason to. I mean, you could just read the whole thing into memory and then do the two passes on the result, but again that's going to be more complicated than just reading from the start again with a new reader.</p>
|
<p>"The whole business about mark() and reset() in BufferedReader smacks of poor design."</p>
<p>why don't you extend this class and have it do a mark() in the constructor() and then do a seek(0) in topOfFile() method.</p>
<p>BR,<br>
~A</p>
| 32,880
|
<p>I just moved over to the Visual Basic team here at work.</p>
<p>What is the equivalent keyword to <code>break</code> in Visual Basic, that is, to exit a loop early but not the method?</p>
|
<p>In both Visual Basic 6.0 and <a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET" rel="noreferrer">VB.NET</a> you would use:</p>
<ul>
<li><code>Exit For</code> to break from For loop</li>
<li><code>Wend</code> to break from While loop</li>
<li><code>Exit Do</code> to break from Do loop</li>
</ul>
<p>depending on the loop type. See <a href="https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/exit-statement" rel="noreferrer">Exit Statements</a> for more details.</p>
|
<p><code>Exit</code> [construct], and intelisense will tell you which one(s) are valid in a particular place.</p>
| 2,761
|
<p>Is there a Java equivalent to .NET's App.Config?</p>
<p>If not is there a standard way to keep you application settings, so that they can be changed after an app has been distributed?</p>
|
<p>For WebApps, web.xml can be used to store application settings.</p>
<p>Other than that, you can use the <a href="http://java.sun.com/javase/6/docs/api/java/util/Properties.html" rel="noreferrer">Properties</a> class to read and write properties files.</p>
<p>You may also want to look at the <a href="http://java.sun.com/javase/6/docs/api/java/util/prefs/Preferences.html" rel="noreferrer">Preferences</a> class, which is used to read and write system and user preferences. It's an abstract class, but you can get appropriate objects using the <code>userNodeForPackage(ClassName.class)</code> and <code>systemNodeForPackage(ClassName.class)</code>.</p>
|
<p>The simple way is to simply have a properties file, e.g., myapp.properties, with all your settings in. It's not a very advanced way to do settings but it suffices, or you can have your own XML based setup, or get them from a database, etc.</p>
| 26,121
|
<p>I have a situation where I need to process large (many GB's) amounts of data as such:</p>
<ol>
<li>build a large string by appending many smaller (C char*) strings</li>
<li>trim the string</li>
<li>convert the string into a C++ const std::string for processing (read only)</li>
<li>repeat</li>
</ol>
<p>The data in each iteration are independent.</p>
<p>My question is, I'd like to minimise (if possible eliminate) heap allocated memory usage, as it at the moment is my largest performance problem.</p>
<p>Is there a way to convert a C string (char*) into a stl C++ string (std::string) without requiring std::string to internally alloc/copy the data?</p>
<p>Alternatively, could I use stringstreams or something similar to re-use a large buffer?</p>
<p><strong>Edit:</strong> Thanks for the answers, for clarity, I think a revised question would be:</p>
<p><em>How can I build (via multiple appends) a stl C++ string efficiently. And if performing this action in a loop, where each loop is totally independant, how can I re-use thisallocated space.</em></p>
|
<p>You can't actually form a std::string without copying the data. A stringstream would probably reuse the memory from pass to pass (though I think the standard is silent on whether it actually has to), but it still wouldn't avoid the copying.</p>
<p>A common approach to this sort of problem is to write the code which processes the data in step 3 to use a begin/end iterator pair; then it can easily process either a std::string, a vector of chars, a pair of raw pointers, etc. Unlike passing it a container type like std::string, it would no longer know or care how the memory was allocated, since it would still belong to the caller. Carrying this idea to its logical conclusion is <a href="http://www.boost.org/doc/libs/1_37_0/libs/range/index.html" rel="noreferrer">boost::range</a>, which adds all the overloaded constructors to still let the caller just pass a string/vector/list/any sort of container with .begin() and .end(), or separate iterators.</p>
<p>Having written your processing code to work on an arbitrary iterator range, you could then even write a custom iterator (not as hard as it sounds, basically just an object with some standard typedefs, and operator ++/*/=/==/!= overloaded to get a forward-only iterator) that takes care of advancing to the next fragment each time it hit the end of the one it's working on, skipping over whitespace (I assume that's what you meant by trim). That you never had to assemble the whole string contiguously at all. Whether or not this would be a win depends on how many fragments/how large of fragments you have. This is essentially what the SGI rope mentioned by Martin York is: a string where append forms a linked list of fragments instead of a contiguous buffer, which is thus suitable for much longer values.</p>
<hr>
<p><strong>UPDATE</strong> (since I still see occasional upvotes on this answer):</p>
<p>C++17 introduces another choice: <a href="http://en.cppreference.com/w/cpp/string/basic_string_view" rel="noreferrer">std::string_view</a>, which replaced std::string in many function signatures, is a non-owning reference to a character data. It is implicitly convertible from std::string, but can also be explicitly constructed from contiguous data owned somewhere else, avoiding the unnecessary copying std::string imposes.</p>
|
<p>In this case, might it be better to process the char* directly, instead of assigning it to a std::string.</p>
| 47,182
|
<p>I'm unsure whether the following code would ensure all conditions given in Comparator's Javadoc. </p>
<pre><code>class TotalOrder<T> implements Comparator<T> {
public boolean compare(T o1, T o2) {
if (o1 == o2 || equal(o1, o2)) return 0;
int h1 = System.identityHashCode(o1);
int h2 = System.identityHashCode(o2);
if (h1 != h2) {
return h1 < h2 ? -1 : 1;
}
// equals returned false but identity hash code was same, assume o1 == o2
return 0;
}
boolean equal(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
}
</code></pre>
<p>Will the code above impose a total ordering on all instances of any class, even if that class does not implement Comparable?</p>
|
<blockquote>
<p>Hey, look at what I found!</p>
<p><a href="http://gafter.blogspot.com/2007/03/compact-object-comparator.html" rel="nofollow noreferrer">http://gafter.blogspot.com/2007/03/compact-object-comparator.html</a></p>
</blockquote>
<p>Oh yes, I forgot about the IdentityHashMap (Java 6 and above only). Just have to pay attention at releasing your comparator. </p>
|
<p>I'm not really sure about the <code>System.identityHashCode(Object)</code>. That's pretty much what the <strong>==</strong> is used for. You might rather want to use the <code>Object.hashCode()</code> - it's more in parallel with <code>Object.equals(Object)</code>.</p>
| 4,797
|
<p>Even though Silverlight2 is still in it's infancy, can anyone recommend a book to get started with? One that has more of a developer focus than a designer one? </p>
|
<p>I have this one pre-ordered: "Programming Silverlight 2"
by Jesse Liberty and Tim Heuer. The authors are both employed by Microsoft working on Silverlight 2, and their blogs are great, so I expect the book (to be released after RTM) to be up to date.</p>
|
<p>I'm currently working my way through <a href="https://rads.stackoverflow.com/amzn/click/com/073562528X" rel="nofollow noreferrer" rel="nofollow noreferrer">Introducing Microsoft Silverlight 2</a>, so far so good. </p>
<p>It's a typical Microsoft book serving up the <strong>koolaid</strong>, but gives a good introduction. I saw the guy speak at one of the local .NET User Groups in the Metro Detroit area and was impressed.</p>
<p><a href="http://ecx.images-amazon.com/images/I/51YD6H7PQyL._SL500_BO2,204,203,200_PIsitb-dp-500-arrow,TopRight,45,-64_OU01_AA240_SH20_.jpg" rel="nofollow noreferrer">alt text http://ecx.images-amazon.com/images/I/51YD6H7PQyL._SL500_BO2,204,203,200_PIsitb-dp-500-arrow,TopRight,45,-64_OU01_AA240_SH20_.jpg</a></p>
| 8,585
|
<p>Our 404 error logs show a lot of /SysVol http requests on our Windows Web Server 2008 for our website. It only has a webserver role and I believe that SysVol requests are meant for Domain Controllers? What's causing this and what would be the best solution to deal with these 404 requests?</p>
<p>I'm using code that access employee records via Active Directory (ldap) and the server is not trusted for delegaton in case this is related to the problem.</p>
|
<p>Well, some css code to see how you currently set your bullet images would be useful ;-)</p>
<p>Instead of actually setting the 'list-style-image' property, I've had far more consistent results with setting a background-image property for the li element. You can then control the positioning with pixel accuracy. Remember to set a suitable left-padding value to push your list item contents clear of the bullet image.</p>
|
<p>You can use something like this in your css...</p>
<pre><code>#content li{
list-style-image: url(../images/bullet.gif);
}
</code></pre>
| 26,779
|
<p>I need to create an <code>XmlDocument</code> with a root element containing multiple namespaces. Am using C# 2.0 or 3.0</p>
<p>Here is my code:</p>
<pre><code>XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("JOBS", "http://www.example.com");
doc.AppendChild(root);
XmlElement job = doc.CreateElement("JOB", "http://www.example.com");
root.AppendChild(job);
XmlElement docInputs = doc.CreateElement("JOB", "DOCINPUTS", "http://www.example.com");
job.AppendChild(docInputs);
XmlElement docInput = doc.CreateElement("JOB", "DOCINPUT", "http://www.example.com");
docInputs.AppendChild(docInput);
XmlElement docOutput = doc.CreateElement("JOB", "DOCOUTPUT", "http://www.example.com");
docOutputs.AppendChild(docOutput);
</code></pre>
<p>The current output:</p>
<pre><code><JOBS xmlns="http://www.example.com">
<JOB>
<JOB:DOCINPUTS xmlns:JOB="http://www.example.com">
<JOB:DOCINPUT />
</JOB:DOCINPUTS>
<JOB:DOCOUTPUTS xmlns:JOB="http://www.example.com">
<JOB:DOCOUTPUT />
</JOB:DOCOUTPUTS>
</JOB>
</JOBS>
</code></pre>
<p>However, my desired output is:</p>
<pre><code><JOBS xmlns:JOBS="http://www.example.com" xmlns:JOB="http://www.example.com">
<JOB>
<JOB:DOCINPUTS>
<JOB:DOCINPUT />
</JOB:DOCINPUTS>
<JOB:DOCOUTPUTS>
<JOB:DOCOUTPUT />
</JOB:DOCOUTPUTS>
</JOB>
</JOBS>
</code></pre>
<p>My question: how do I create an <code>XmlDocument</code> that contains a root element with multiple namespaces?</p>
|
<p>The following will generate the desired output that you requested above:</p>
<pre><code>XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("JOBS");
root.SetAttribute("xmlns:JOBS", "http://www.example.com");
root.SetAttribute("xmlns:JOB", "http://www.example.com");
doc.AppendChild(root);
XmlElement job = doc.CreateElement("JOB");
XmlElement docInputs = doc.CreateElement("JOB", "DOCINPUTS", "http://www.example.com");
XmlElement docInput = doc.CreateElement("JOB", "DOCINPUT", "http://www.example.com");
docInputs.AppendChild(docInput);
job.AppendChild(docInputs);
XmlElement docOutputs = doc.CreateElement("JOB", "DOCOUTPUTS", "http://www.example.com");
XmlElement docOutput = doc.CreateElement("JOB", "DOCOUTPUT", "http://www.example.com");
docOutputs.AppendChild(docOutput);
job.AppendChild(docOutputs);
doc.DocumentElement.AppendChild(job);
</code></pre>
<p>However, it seems odd that in your example/desired output that the same XML namespace was used against two different prefixes. Hope this helps.</p>
|
<p>try to add the namespace attribute to the root element:</p>
<pre><code> XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("JOBS", "http://www.example.com");
root.SetAttribute("xmlns:JOB", "http://www.example.com");
doc.AppendChild(root);
XmlElement job = doc.CreateElement("JOB", "http://www.example.com");
root.AppendChild(job);
XmlElement docInputs = doc.CreateElement("JOB", "DOCINPUTS", "http://www.example.com");
job.AppendChild(docInputs);
XmlElement docInput = doc.CreateElement("JOB", "DOCINPUT", "http://www.example.com");
docInputs.AppendChild(docInput);
XmlElement docOutput = doc.CreateElement("JOB", "DOCOUTPUT", "http://www.example.com");
root.AppendChild(docOutput);
</code></pre>
| 42,961
|
<p>Im trying to craft a regex that only returns <code><link></code> tag hrefs</p>
<p>Why does this regex return all hrefs including <a hrefs?</p>
<pre><code>(?&lt;=&lt;link\s+.*?)href\s*=\s*[\'\"][^\'\"]+
</code></pre>
<pre class="lang-html prettyprint-override"><code><link rel="stylesheet" rev="stylesheet" href="idlecore-tidied.css?T_2_5_0_228" media="screen">
<a href="anotherurl">Slash Boxes&lt;/a>
</code></pre>
|
<p>Either</p>
<pre><code>/(?<=<link\b[^<>]*?)\bhref=\s*=\s*(?:"[^"]*"|'[^']'|\S+)/
</code></pre>
<p>or</p>
<pre><code>/<link\b[^<>]*?\b(href=\s*=\s*(?:"[^"]*"|'[^']'|\S+))/
</code></pre>
<p>The main difference is <code>[^<>]*?</code> instead of <code>.*?</code>. This is because you don't want it to continue the search into other tags.</p>
|
<pre><code>/(?<=<link\s+.*?)href\s*=\s*[\'\"][^\'\"]+[^>]*>/
</code></pre>
<p>i'm a little shaky on the back-references myself, so I left that in there. This regex though:</p>
<pre><code>/(<link\s+.*?)href\s*=\s*[\'\"][^\'\"]+[^>]*>/
</code></pre>
<p>...works in my Javascript test.</p>
| 33,672
|
<p>Which is better to do client side or server side validation?</p>
<p>In our situation we are using </p>
<ul>
<li>jQuery and MVC. </li>
<li>JSON data to pass between our View and Controller. </li>
</ul>
<p>A lot of the validation I do is validating data as users enter it.
For example I use the the <code>keypress</code> event to prevent letters in a text box, set a max number of characters and that a number is with in a range. </p>
<p>I guess the better question would be, Are there any benefits to doing server side validation over client side?</p>
<hr>
<p>Awesome answers everyone. The website that we have is password protected and for a small user base(<50). If they are not running JavaScript we will send ninjas. But if we were designing a site for everyone one I'd agree to do validation on both sides.</p>
|
<p>As others have said, you should do both. Here's why:</p>
<h2>Client Side</h2>
<p>You want to validate input on the client side first because you can give <strong>better feedback to the average user</strong>. For example, if they enter an invalid email address and move to the next field, you can show an error message immediately. That way the user can correct every field <strong>before</strong> they submit the form.</p>
<p>If you only validate on the server, they have to submit the form, get an error message, and try to hunt down the problem. </p>
<p>(This pain can be eased by having the server re-render the form with the user's original input filled in, but client-side validation is still faster.)</p>
<h2>Server Side</h2>
<p>You want to validate on the server side because you can <strong>protect against the malicious user</strong>, who can easily bypass your JavaScript and submit dangerous input to the server. </p>
<p>It is very dangerous to trust your UI. <strong>Not only can they abuse your UI, but they may not be using your UI at all, or even a browser</strong>. What if the user manually edits the URL, or runs their own Javascript, or tweaks their HTTP requests with another tool? What if they send custom HTTP requests from <code>curl</code> or from a script, for example?</p>
<p>(<em>This is not theoretical; eg, I worked on a travel search engine that re-submitted the user's search to many partner airlines, bus companies, etc, by sending <code>POST</code> requests as if the user had filled each company's search form, then gathered and sorted all the results. Those companies' form JS was never executed, and it was crucial for us that they provide error messages in the returned HTML. Of course, an API would have been nice, but this was what we had to do.</em>)</p>
<p>Not allowing for that is not only naive from a security standpoint, but also non-standard: a client should be allowed to send HTTP by whatever means they wish, and you should respond correctly. That includes validation.</p>
<p>Server side validation is also important for <strong>compatibility</strong> - not all users, even if they're using a browser, will have JavaScript enabled.</p>
<h2>Addendum - December 2016</h2>
<p>There are some validations that <strong>can't even be properly done in server-side application code, and are utterly impossible in client-side code</strong>, because they depend on the current state of the database. For example, "nobody else has registered that username", or "the blog post you're commenting on still exists", or "no existing reservation overlaps the dates you requested", or "your account balance still has enough to cover that purchase." <strong>Only the database can reliably validate data which depends on related data.</strong> Developers <a href="http://www.bailis.org/papers/feral-sigmod2015.pdf" rel="noreferrer">regularly screw this up</a>, but <a href="http://nathanmlong.com/2016/01/protect-your-data-with-postgresql-constraints/" rel="noreferrer">PostgreSQL provides some good solutions</a>.</p>
|
<p>If you are doing light validation, it is best to do it on the client. It will save the network traffic which will help your server perform better. If if it complicated validation that involves pulling data from a database or something, like passwords, then it best to do it on the server where the data can be securely checked.</p>
| 19,613
|
<p>Is it possible to change the hostname in Windows 2003 from the command line with out-of-the-box tools?</p>
|
<p>The previously mentioned <code>wmic</code> command is the way to go, as it is installed by default in recent versions of Windows. </p>
<p>Here is my small improvement to generalize it, by retrieving the current name from the environment:</p>
<pre class="lang-dos prettyprint-override"><code>wmic computersystem where name="%COMPUTERNAME%"
call rename name="NEW-NAME"
</code></pre>
<p>NOTE: The command must be given in one line, but I've broken it into two to make scrolling unnecessary. As @rbeede mentions you'll have to reboot to complete the update.</p>
|
<p>If you are looking to do this from Windows 10 IoT, then there is a built in command you can use:</p>
<p><code>setcomputername [newname]</code></p>
<p>Unfortunately, this command does <em>not exist</em> in the full build of Windows 10.</p>
| 7,868
|
<p>Can anyone recommend a good application that could be used to convert VB.NET projects to C#, without having to do too much manual work?</p>
<p>We've used Reflector to do small libraries manually, but some of the larger projects will be too slow and complex to do this manually.</p>
|
<p>You can use Lutz Roeders Reflector (<a href="http://www.red-gate.com/products/reflector" rel="noreferrer">http://www.red-gate.com/products/reflector</a>) which can decompile whole Assemblies into Visual Studio projects. This way you can convert from ANY .NET Langauge into one of the supported languages of this program (C#.VB.NET,MC++,Delphi,Chrome)</p>
|
<p>There's also the <a href="http://www.developerfusion.com/tools/" rel="nofollow noreferrer">free online converters up at developerfusion</a> :)</p>
| 46,313
|
<p>Situation:</p>
<ul>
<li>text: a string</li>
<li>R: a regex that matches part of the string. This might be expensive to calculate. </li>
</ul>
<p>I want to both delete the R-matches from the text, and see what they actually contain. Currently, I do this like:</p>
<pre><code>import re
ab_re = re.compile("[ab]")
text="abcdedfe falijbijie bbbb laifsjelifjl"
ab_re.findall(text)
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
ab_re.sub('',text)
# 'cdedfe flijijie lifsjelifjl'
</code></pre>
<p>This runs the regex twice, near as I can tell. Is there a technique to do it all on pass, perhaps using re.split? It seems like with split based solutions I'd need to do the regex at least twice as well. </p>
|
<pre><code>import re
r = re.compile("[ab]")
text = "abcdedfe falijbijie bbbb laifsjelifjl"
matches = []
replaced = []
pos = 0
for m in r.finditer(text):
matches.append(m.group(0))
replaced.append(text[pos:m.start()])
pos = m.end()
replaced.append(text[pos:])
print matches
print ''.join(replaced)
</code></pre>
<p>Outputs:</p>
<pre><code>['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
cdedfe flijijie lifsjelifjl
</code></pre>
|
<p>You could use split with capturing parantheses. If you do, then the text of all groups in the pattern are also returned as part of the resulting list (from <a href="http://www.python.org/doc/2.5.2/lib/node46.html" rel="nofollow noreferrer">python doc</a>).</p>
<p>So the code would be </p>
<pre><code>import re
ab_re = re.compile("([ab])")
text="abcdedfe falijbijie bbbb laifsjelifjl"
matches = ab_re.split(text)
# matches = ['', 'a', '', 'b', 'cdedfe f', 'a', 'lij', 'b', 'ijie ', 'b', '', 'b', '', 'b', '', 'b', ' l', 'a', 'ifsjelifjl']
# now extract the matches
Rmatches = []
remaining = []
for i in range(1, len(matches), 2):
Rmatches.append(matches[i])
# Rmatches = ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
for i in range(0, len(matches), 2):
remaining.append(matches[i])
remainingtext = ''.join(remaining)
# remainingtext = 'cdedfe flijijie lifsjelifjl'
</code></pre>
| 25,087
|
<p>I have a tabpanel with a calendar control on the 4th tab but when I select a date, the postback causes the tabpanel to return to the first tab instead of the 4th that it came from.
Is there a way to get it to return to the tab that the calendar control is on and not revert back to the first tab ?</p>
<p>I know setting autoPostback to true on the TabContainer will do this but that means it reloads on every tab change not just the one I want.</p>
<p>Any ideas ?</p>
|
<p>The <a href="http://www.ecma-international.org/publications/standards/Ecma-334.htm" rel="nofollow noreferrer">C# specification</a> states on p.305 (17.4.4)</p>
<blockquote>
<p>The initial value of a field, whether it be a static field or an instance field, is the default value (§12.2) of the
field’s type. It is not possible to observe the value of a field before this default initialization has occurred,
and a field is thus never “uninitialized”.</p>
</blockquote>
|
<p>Yes, you can really trust .NET to initialize fields to their default values.
There are basically no repercussions for doing it explicitly. (One small caveat here: if you initialize static fields explicitly, then anyone running the type initializer a second time via reflection will end up re-initializing those fields. This is a real corner case though!)</p>
<p>Do whatever promotes the most readability in your particular codebase.</p>
| 33,680
|
<p>we have users in each region of the world. I would like to create an environment picker that shows up a map on the form and has a link for each region. So if i was in NY i would click NY and would get the NY environment. Any ideas of doing this dynamically in winforms as opposed to having a static map image.</p>
|
<p>I may be misreading the question, but it sounds like you want something akin to how the old-school <a href="http://blogs.msdn.com/oldnewthing/archive/2006/10/27/880411.aspx" rel="nofollow noreferrer">Windows time zone picker</a> worked. The rest of this is based on that assumption, so if I'm wrong, feel free to disregard.</p>
<p>You are, in effect, dealing with an image of a world (or national, or regional, etc.) map, with clickable "hotspots." Given that, you need some form of image to start with. :)</p>
<p>Now you have two choices: You can embed a bitmap image of your map in the application, or you can draw it yourself using GDI+ primitives. Either way, you would display it on the form, and wire up the MouseUp event for the various hotspots. (The MouseUp event, I believe, includes the X,Y coordinates of where the user clicked.)</p>
<p>If you wanted to get really fancy, you could change the mouse pointer on the MouseOver event if the user is in the defined hotspots.</p>
<p>Either way, it's a great UI -- very visual, very in tune with how people think -- but it will be time-intensive to code correctly.</p>
|
<p>Have you tried using MapPoint and its API? You'd probably want to use their web service. Just google "mappoint api" for some examples and documentation.</p>
| 24,281
|
<p>How can I set the font used by the FLVPlaybackCaptioning component for subtitles? Using the style property of the textarea does nothing, and using a TextFormat makes the text go blank, even though the font had been embedded.</p>
|
<p>It seems the font, as well as the other properties of the text, are specified in the XML file where the subtitles are read (this is from the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlaybackCaptioning.html" rel="nofollow noreferrer">documentation</a>):</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<tt xml:lang="en" xmlns="http://www.w3.org/2006/04/ttaf1" xmlns:tts="http://www.w3.org/2006/04/ttaf1#styling">
<head>
<styling>
<style id="1" tts:textAlign="right"/>
<style id="2" tts:color="transparent"/>
<style id="3" style="2" tts:backgroundColor="white"/>
<style id="4" style="2 3" tts:fontSize="20"/>
</styling>
</head>
<body>
<div xml:lang="en">
<p begin="00:00:00.50" dur="500ms">Four score and twenty years ago</p>
<p begin="00:00:02.50"><span tts:fontFamily="monospaceSansSerif,proportionalSerif,TheOther"tts:fontSize="+2">our forefathers</span> brought forth<br /> on this continent</p>
<p begin="00:00:04.40" dur="10s" style="1">a <span tts:fontSize="12 px">new</span> <span tts:fontSize="300%">nation</span></p>
<p begin="00:00:06.50" dur="3">conceived in <span tts:fontWeight="bold" tts:color="#ccc333">liberty</span> <span tts:color="#ccc333">and dedicated to</span> the proposition</p>
<p begin="00:00:11.50" tts:textAlign="right">that <span tts:fontStyle="italic">all</span> men are created equal.</p>
<p begin="15s" style="4">The end.</p>
</div>
</body>
</tt>
</code></pre>
<p>So maybe the component doesn't want you overriding those?</p>
|
<p>//Create a listener for your FLVPlaybackCaptioning instance, listening for the creation of the textfield/target eg.</p>
<pre><code>myFLVPlybkcap.addEventListener(CaptionTargetEvent.CAPTION_TARGET_CREATED, captionTargetCreatedHandler);
</code></pre>
<p>//Then when that occurs, set the 'defaultTextFormat' of the textfield to your own...</p>
<pre><code>private function captionTargetCreatedHandler(e:CaptionTargetEvent):void{
var myTextFormat:TextFormat = new TextFormat();
myTextFormat.font = "Arial";
myTextFormat.color = 0x00FF00;
myTextFormat.size = 18;
(e.captionTarget as TextField).defaultTextFormat = myTextFormat;
}
</code></pre>
| 25,560
|
<p>Is it even possible?</p>
<p>So far, I found that we can buy TypeMock to mock the SharePoint objects and then use any free Mocking framework (<a href="http://code.google.com/p/moq/" rel="nofollow noreferrer">Moq</a>?) to do the rest of the job.</p>
<p>What do you think?</p>
<p>It seams that without TypeMock, it's impossible to do unit test within SharePoint.</p>
<p>To properly test our events, we need to give the event a SPItemEventProperties. The class is sealed and have an internal constructor that require a SPSite.</p>
<p>If I use the SPSite I can instantiate the class and give the proper values to test for my event. However, I want to remove that dependency and TypeMock seams to be the only one able to do that.</p>
<p>Any way around it?</p>
|
<p>I haven't used it yet, but I am anxious to try this product: <a href="http://www.typemock.com/sharepointpage.php" rel="nofollow noreferrer">TypeMock for SharePoint</a></p>
<p>Video introduction here on the <a href="http://www.typemock.com/Multimedia.html" rel="nofollow noreferrer">multimedia page (#5)</a></p>
<p>Here's a nice little overview of the <a href="http://blogs.msdn.com/francischeung/archive/2008/08/22/unit-testing-sharepoint-2007-applications.aspx" rel="nofollow noreferrer">trickiness with unit testing SharePoint</a></p>
<p>jt</p>
|
<p>Currenlty typemock Isolator is the only framework that can fake or <a href="http://www.typemock.com/sharepointpage.php" rel="nofollow noreferrer">mock SharePoint</a>. That's because it can create mock objects that have private constructors or are sealed, like most SharePoint objects are.</p>
| 47,161
|
<p>Recently, I started maintaining a web application which unfortunately works only with IE 6. Most of the issues are related to CSS.</p>
<p>Is there any tool which can help me standardize the CSS classes to work with <strong>both</strong> <strong>IE 6 and IE 7</strong>? I understand I have to go through standards but I need something to start with quickly.</p>
<p>Firebug can help me to some extend in identifying the CSS classes related to the UI elements (if the page renders on firefox). But, I was looking for something more like an advisor tool. If you have some experience to share, please feel free.</p>
|
<p>Try out <a href="http://www.webdesignerdepot.com/2009/03/microsoft-announces-superpreview-for-ie-browser-testing/" rel="nofollow noreferrer">SuperPreview</a> or the <a href="http://www.istartedsomething.com/20090318/expression-web-superpreview-cross-browser-testing/" rel="nofollow noreferrer">whole package</a> (Expression Web announced at Mix)..</p>
<p>SuperPreview is a new free standalone application from Microsoft (still in beta) which enables you to see how your websites will look across different versions of Internet Explorer making migration from IE6 to 7 and 8 much easier than before, without have to start up a Virtual Machine to run IE6, or have a separate computer dedicated to running IE6. </p>
|
<p>Sometimes you need to introduce a little hack for IE6 and IE7 like removing double margin and I use the following pure CSS code</p>
<pre><code>css-selector { code for all browsers }
*html css-selector {code for IE6 browser }
*+html css-selector {code for IE7 browser }
</code></pre>
<p>it is not a tool that you expecting, but may be it would helpfull</p>
| 36,059
|
<p>What I want is system which is logging methods called by users and their returning values if they have. For example a user logs in and he/she is surfing on my web app. then naturally he/she clicks on somethings and so he/she fires up some event method whatever then my log system must log this method name and time stamp combined with user login name or id into database.</p>
<p>So how can I do that in asp.net.</p>
|
<p>Well, the <em>simplest</em> way is just to add all the logging statements to your code, using a logging framework such as <a href="http://logging.apache.org/log4net/index.html" rel="nofollow noreferrer">Log4Net</a>. If you want a more automatic way of doing this, you might want to look into <a href="http://www.sharpcrafters.com" rel="nofollow noreferrer">PostSharp</a> so that you could just decorate the appropriate methods with an attribute - but that's certainly more complex, and probably only worth it if you have a lot of events to log.</p>
|
<p>you can attach your write logic class to events triggered from parts of code.
using events driven architecture is a good pattern </p>
| 46,304
|
<p>I would like to show the user with a spinner, that something is done in background but do not know how this works in a batchfile.</p>
<p>Does anyone have a clue?</p>
|
<p>This can actually be done quite easily with pure native commands, you just have to know how to use the more tricky of them. No use of external tools like VBScript or nasty side effects like clearing the screen are necessary.</p>
<p>What you're looking for is the equivalent of the bash "<code>echo -n</code>" command which outputs a line without the newline. In XP batch, this is achieved by using "<code>set /p</code>" (ask user for response with a prompt) with empty input as follows:</p>
<pre><code><nul (set /p junk=Hello)
echo. again.
</code></pre>
<p>will output the string "Hello again." with no intervening newline.</p>
<p>That trick (and the use of CTRL-H, the backspace character can be seen in the following test script which starts (one after the other) a 10-second sub-task with a 20-second timeout and a 15-second sub-task with a 10-second timeout.</p>
<p>The payload script is created by the actual running script and its only requirement is that it do the work it has to do then delete a flag file when finished, so that the monitor function will be able to detect it.</p>
<p>Keep in mind that the ^H strings in this script are actually CTRL-H characters, the ^| is two separate characters used to escape the pipe symbol.</p>
<pre><code>@echo off
:: Localise environment.
setlocal enableextensions enabledelayedexpansion
:: Specify directories. Your current working directory is used
:: to create temporary files tmp_*.*
set wkdir=%~dp0%
set wkdir=%wkdir:~0,-1%
:: First pass, 10-second task with 20-second timeout.
del "%wkdir%\tmp_*.*" 2>nul
echo >>"%wkdir%\tmp_payload.cmd" ping 127.0.0.1 -n 11 ^>nul
echo >>"%wkdir%\tmp_payload.cmd" del "%wkdir%\tmp_payload.flg"
call :monitor "%wkdir%\tmp_payload.cmd" "%wkdir%\tmp_payload.flg" 20
:: Second pass, 15-second task with 10-second timeout.
del "%wkdir%\tmp_*.*" 2>nul:
echo >>"%wkdir%\tmp_payload.cmd" ping 127.0.0.1 -n 16 ^>nul
echo >>"%wkdir%\tmp_payload.cmd" del "%wkdir%\tmp_payload.flg"
call :monitor "%wkdir%\tmp_payload.cmd" "%wkdir%\tmp_payload.flg" 10
goto :final
:monitor
:: Create flag file and start the payload minimized.
echo >>%2 dummy
start /min cmd.exe /c "%1"
:: Start monitoring.
:: i is the indicator (0=|,1=/,2=-,3=\).
:: m is the number of seconds left before timeout.
set i=0
set m=%3
<nul (set /p z=Waiting for child to finish: ^|)
:: Loop here awaiting completion.
:loop
:: Wait one second.
ping 127.0.0.1 -n 2 >nul
:: Update counters and output progress indicator.
set /a "i = i + 1"
set /a "m = m - 1"
if %i% equ 4 set i=0
if %i% equ 0 <nul (set /p z=^H^|)
if %i% equ 1 <nul (set /p z=^H/)
if %i% equ 2 <nul (set /p z=^H-)
if %i% equ 3 <nul (set /p z=^H\)
:: End conditions, complete or timeout.
if not exist %2 (
echo.
echo. Complete.
goto :final
)
if %m% leq 0 (
echo.
echo. *** ERROR: Timed-out waiting for child.
goto :final
)
goto :loop
:final
endlocal
</code></pre>
|
<pre><code>:LOOP
ECHOX -n "~r%Processing..."
IF %CTR% EQU 4 SET /A CTR=0
IF %CTR%==0 (set /p DOT=³)<NUL
IF %CTR%==1 (set /p DOT=/)<NUL
IF %CTR%==2 (set /p DOT=Ä)<NUL
IF %CTR%==3 (set /p DOT=\)<NUL
ECHOX -n "~r"
SET /A CTR+=1
SET /A TCT+=1
IF %TCT% GTR %MAX_COUNT% GOTO :END
GOTO :LOOP
</code></pre>
| 48,045
|
<p>I am new to Hibernate and attempting to run a java/spring example that retrieves data from a table in MS SqlServer. Everytime I try to run the program, the data source loads ok. But when spring tries to load the session facotry it gets the following error:</p>
<pre><code>Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory'
defined in class path resource [ml/spring/src/applicationContext.xml]:
Instantiation of bean failed; nested exception is
java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
Caused by: java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
</code></pre>
<p>Below is the application Context file I am using:</p>
<pre><code><!-- Data source bean -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName">
<value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value></property>
<property name="url">
<value>jdbc:microsoft:sqlserver://machine:port</value></property>
<property name="username"><value>user</value></property>
<property name="password"><value>password</value></property>
</bean>
<!-- Session Factory Bean -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"><ref local="dataSource"/></property>
<property name="mappingResources">
<list>
<value>authors.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=net.sf.hibernate.dialect.SQLServerDialect
</value>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</code></pre>
|
<p>You are missing a JAR file containing the JTA API classes. You probably have one already when you downloaded Hibernate. It should be called something like:</p>
<pre><code>jta-1.1.jar
</code></pre>
<p>Hope this helps.</p>
|
<p>In case you are using maven, use <a href="https://mvnrepository.com/artifact/javax.transaction/jta/1.1" rel="nofollow noreferrer">this</a>,</p>
<pre><code><dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
</code></pre>
| 33,745
|
<p>How much do you rely on database transactions? </p>
<p>Do you prefer small or large transaction scopes ? </p>
<p>Do you prefer client side transaction handling (e.g. TransactionScope in .NET) over server
side transactions or vice-versa? </p>
<p>What about nested transactions? </p>
<p>Do you have some tips&tricks related to transactions ?</p>
<p>Any gotchas you encountered working with transaction ?</p>
<p>All sort of answers are welcome.</p>
|
<p>I always wrap a transaction in a using statement.</p>
<pre><code>using(IDbTransaction transaction )
{
// logic goes here.
transaction.Commit();
}
</code></pre>
<p>Once the transaction moves out of scope, it is disposed. If the transaction is still active, it is rolled back. This behaviour fail-safes you from accidentally locking out the database. Even if an unhandled exception is thrown, the transaction will still rollback. </p>
<p>In my code I actually omit explicit rollbacks and rely on the using statement to do the work for me. I only explicitly perform commits. </p>
<p>I've found this pattern has drastically reduced record locking issues.</p>
|
<p>As Sara Chipps said, transaction is overkill for high traffic applications. So we should avoid it as much as possible. In other words, we use a <a href="http://queue.acm.org/detail.cfm?id=1394128" rel="nofollow noreferrer">BASE architecture</a> rather than ACID. Ebay is a typical case. Distributed transaction is not used at all in Ebay architecture. But for <a href="http://queue.acm.org/detail.cfm?id=1466448" rel="nofollow noreferrer">eventual consistency</a>, you have to do some sort of trick on your own.</p>
| 6,069
|
<p>I'm looking for a solution to map one or all of the following Flickr, twitter, vimeo, by exif, keywords or whatever to google maps. I'm trying to show a map of my location from updating social sites.</p>
|
<p>If each of the services you want <a href="http://georss.org/" rel="nofollow noreferrer">supports GeoRSS</a>, then you can actually build such a map with zero coding whatsoever! This is because Google Maps supports mapping a GeoRSS feed directly. All you have to do is type the URL of the RSS feed with the GeoRSS data within, into the box on Google maps. Here's an example of the <a href="http://maps.google.com/maps?f=q&hl=en&geocode=&q=http:%2F%2Ffeeds.feedburner.com%2FWhatsTheHarm" rel="nofollow noreferrer">feed from my What's The Harm? website</a> mapped in Google Maps.</p>
<p>Now you mention several services there, each of which whould presumably have its own GeoRSS feed. What you would need to do is merge the feeds together before handing the resulting feed to Google Maps. There are a variety of ways to do this, one quick point-and-click way is via <a href="http://pipes.yahoo.com" rel="nofollow noreferrer">Yahoo Pipes</a>. Search for "merge feed" or "merge RSS" on there and you can find many examples that you can copy and modify.</p>
<p>Yahoo Pipes also has functionality to <em>add</em> GeoRSS coding to feeds that don't have it already. You could use that to bring in data like blog posts and son on that might not be GeoRSS. Look under "Operators" for the "Location Extractor" widget.</p>
<p>As for the websites you mentioned:</p>
<ul>
<li>Flickr: Yes. Make sure you map your photos, and use the feed marked "geoFeed".</li>
<li>twitter: There's a service called <a href="http://geotwitter.net" rel="nofollow noreferrer">GeoTwitter</a> that can add this for you.</li>
<li>vimeo: It doesn't appear they support it out of the box.</li>
</ul>
|
<p>There's a nice greasemonkey <a href="http://txfx.net/2005/05/17/flickr-google-maps-geobloggers/" rel="nofollow noreferrer">script</a> to ease geotagging on Flickr.</p>
| 13,781
|
<p>What does the term <b>referential transparency</b> mean? I've heard it described as "it means you can replace equals with equals" but this seems like an inadequate explanation.</p>
|
<p>The term "referential transparency" comes from <a href="https://en.wikipedia.org/wiki/Analytical_philosophy" rel="noreferrer">analytical philosophy</a>, the branch of philosophy that analyzes natural language constructs, statements and arguments based on the methods of logic and mathematics. In other words, it is the closest subject outside computer science to what we call <a href="https://en.wikipedia.org/wiki/Programming_language_semantics" rel="noreferrer">programming language semantics</a>. The philosopher <a href="https://en.wikipedia.org/wiki/Willard_Van_Orman_Quine" rel="noreferrer">Willard Quine</a> was responsible for initiating the concept of referential transparency, but it was also implicit in the approaches of Bertrand Russell and Alfred Whitehead.</p>
<p>At its core, "referential transparency" is a very simple and clear idea. The term "referent" is used in analytical philosophy to talk about <em>the thing that an expression refers to</em>. It is roughly the same as what we mean by "meaning" or "denotation" in programming language semantics. Using Andrew Birkett's example (<a href="http://www.nobugs.org/blog/archives/2008/11/12/why-do-they-call-it-referentially-transparent/" rel="noreferrer">blog post</a>), the term "the capital of Scotland" refers to the city of Edinburgh. That is a straightforward example of a "referent".</p>
<p>A context in a sentence is "referentially transparent" if replacing a term in that context by another term that <em>refers to the same entity</em> doesn't alter the meaning. For example</p>
<blockquote>
<p>The Scottish Parliament meets in the capital of Scotland.</p>
</blockquote>
<p>means the same as</p>
<blockquote>
<p>The Scottish Parliament meets in Edinburgh.</p>
</blockquote>
<p>So the context "The Scottish Parliament meets in ..." is a referentially transparent context. We can replace "the capital of Scotland" with "Edinburgh" without altering the meaning. To put another way, the context only cares about what the term refers to and nothing else. That is the sense in which the context is "referentially transparent."</p>
<p>On the other hand, in the sentence,</p>
<blockquote>
<p>Edinburgh has been the capital of Scotland since 1999.</p>
</blockquote>
<p>we can't do such a replacement. If we did, we would get "Edinburgh has been Edinburgh since 1999", which is a nutty thing to say, and doesn't convey the same meaning as the original sentence. So, it would seem that the context "Edinburgh has been ... since 1999" is referentially opaque (the opposite of referentially transparent). It apparently cares about <em>something more</em> than what the term refers to. What is it?</p>
<p>Things such as "the capital of Scotland" are called <em>definite terms</em> and they gave no lean amount of head ache to logicians and philosophers for a long time. Russell and Quine sorted them out saying that they are not actually "referential", i.e., it is a mistake to think that the above examples are used to refer to entities. The right way to understand "Edinburgh has been the capital of Scotland since 1999" is to say</p>
<blockquote>
<p>Scotland has had a capital since 1999 and that capital is Edinburgh.</p>
</blockquote>
<p>This sentence cannot be transformed to a nutty one. Problem solved! The point of Quine was to say that natural language is messy, or at least complicated, because it is made to be convenient for practical use, but philosophers and logicians should bring clarity by understanding them in the right way. Referential transparency is a tool to be used for bringing such <em>clarity of meaning</em>.</p>
<p>What does all this have to do with programming? Not very much, actually. As we said, referential transparency is a tool to be used in understanding language, i.e., in assigning <em>meaning</em>. <a href="https://en.wikipedia.org/wiki/Christopher_Strachey" rel="noreferrer">Christopher Strachey</a>, who founded the field of programming language semantics, used it in his study of meaning. His foundational paper "<a href="https://github.com/papers-we-love/papers-we-love/blob/master/languages-theory/fundamental-concepts-in-programming-languages.pdf" rel="noreferrer">Fundamental concepts in programming languages</a>" is available on the web. It is a beautiful paper and everybody can read and understand it. So, please do so. You will be much enlightened. He introduces the term "referential transparency" in this paragraph:</p>
<blockquote>
<p>One of the most useful properties of expressions is that called by Quine referential
transparency. In essence this means that if we wish to find the value of an expression which
contains a sub-expression, the only thing we need to know about the sub-expression is its
value. Any other features of the sub-expression, such as its internal structure, the number
and nature of its components, the order in which they are evaluated or the colour of the ink
in which they are written, are irrelevant to the value of the main expression.</p>
</blockquote>
<p>The use of "in essence" suggests that Strachey is paraphrasing it in order to explain it in simple terms. Functional programmers seem to understand this paragraph in their own way. There are 9 other occurrences of "referential transparency" in the paper, but they don't seem to bother about any of the others. In fact, the whole paper of Strachey is devoted to explaining the meaning of <em>imperative programming languages</em>. But, today, functional programmers claim that imperative programming languages are <em>not</em> referentially transparent. Strachey would be turning in his grave.</p>
<p>We can salvage the situation. We said that natural language is "messy, or at least complicated" because it is made to be convenient for practical use. Programming languages are the same way. They are "messy, or at least complicated" because they are made to be convenient for practical use. That does not mean that they need to confuse us. They just have to be understood the right way, using a meta language that is referentially transparent so that we have clarity of meaning. In the paper I cited, Strachey does exactly that. He explains the meaning of imperative programming languages by breaking them down into elementary concepts, never losing clarity anywhere. An important part of his analysis is to point out that expressions in programming languages have two kinds of "values", called <em>l-values</em> and <em>r-values</em>. Before Strachey's paper, this was not understood and confusion reigned supreme. Today, the definition of C mentions it routinely and every C programmer understands the distinction. (Whether the programmers in other languages understand it equally well is hard to say.)</p>
<p>Both Quine and Strachey were concerned with the meaning of language constructions that involve some form of context-dependence. For example, our example "Edinburgh has been the capital of Scotland since 1999" signifies the fact that "capital of Scotland" depends on the time at which it is being considered. Such context-dependence is a reality, both in natural languages and programming languages. Even in functional programming, free and bound variables are to be interpreted with respect to the context in which they appear in. Context dependence of any kind blocks referential transparency in some way or the other. If you try to understand the meaning of terms without regard to the contexts they depend on, you would again end up with confusion. Quine was concerned with the meaning of modal logic. He held that <a href="https://plato.stanford.edu/entries/logic-modal/" rel="noreferrer">modal logic</a> was referentially opaque and it should be cleaned up by translating it into a referentially transparent framework (e.g., by regarding necessity as provability). He largely lost this debate. Logicians and philosophers alike found Kripke's possible world semantics to be perfectly adequate. Similar situation also reigns with imperative programming. State-dependence explained by Strachey and store-dependence explained by Reynolds (in a manner similar to Kripke's possible world semantics) are perfectly adequate. Functional programmers don't know much of this research. Their ideas on referential transparency are to be taken with a large grain of salt.</p>
<p>[Additional note: The examples above illustrate that a simple phrase such as "capital of Scotland" has multiple levels of meaning. At one level, we might be talking about the capital at the current time. At another level, we might talking about all possible capitals that Scotland might have had through the course of time. We can "zoom into" a particular context and "zoom out" to span all contexts quite easily in normal practice. The efficiency of natural language makes use of our ability to do so. Imperative programming languages are efficient in very much the same way. We can use a variable <em>x</em> on the right hand side of an assignment (the <em>r-value</em>) to talk about its value in a particular state. Or, we might talk about its <em>l-value</em> which spans all states. People are rarely confused by such things. However, they may or may not be able to precisely explain all the layers of meaning inherent in language constructs. All such layers of meaning are not necessarily 'obvious' and it is a matter of science to study them properly. However, the inarticulacy of ordinary people to explain such layered meanings doesn't imply that they are confused about them.]</p>
<p><em>A separate "postscript" below relates this discussion to the concerns of functional and imperative programming</em>.</p>
|
<p>Referential transparency can be simply stated as:</p>
<ul>
<li>An expression always evaluating to the same result in any context <a href="https://wiki.haskell.org/Referential_transparency" rel="nofollow noreferrer">[1]</a>,</li>
<li>A function, if given the same parameters twice, must produce the same result twice <a href="http://learnyouahaskell.com/input-and-output" rel="nofollow noreferrer">[2]</a>.</li>
</ul>
<p>For example, the programming language Haskell is a pure functional language; meaning that it is referentially transparent.</p>
| 25,891
|
<p>I have added uc in contentplace holder of master page but how do you instantiate the user control in master page .cs file to make it visible when the master page loads</p>
|
<p>If you add it to a ContentPlaceHolder, and a child page adds content to that ContentPlaceHolder - you're user control will no longer appear. IOW, the controls you add are only the <em>default</em>.</p>
<p>Just add it outside of the ContentPlaceHolder if you want it always visible.</p>
|
<p>I'm not positive but I think you need to use the Page.LoadControl() to officially load a user control to a page at run time.</p>
| 43,535
|
<p>How can you find out the number of active users when you're using a StateServer? Also is it possible to query the StateServer and retrieve the contents in the Session State? </p>
<p>I know that this is all possible if you use SqlServer for a backing store, but I want them to be in memory.</p>
|
<p>The number of active <em>sessions</em> in the State Server can be viewed with a Performance Counter on the server running the State Server easily. This does not directly equate to active users (due to session timeout time)</p>
<p>The counter for active sessions is: "Asp.net" - "State Server Sessions Active"</p>
<p>For reference, here are all State Server related perfmon counters, from <a href="http://msdn.microsoft.com/en-us/library/fxk122b4.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/fxk122b4.aspx</a></p>
<p><strong>State Server Sessions Abandoned</strong>
The number of user sessions that have been explicitly abandoned. These are sessions that are ended by specific user actions, such as closing the browser or navigating to another site. This counter is available only on the computer where the state server service (aspnet_state) is running.</p>
<p><strong>State Server Sessions Active</strong>
The number of currently active user sessions. This counter is available only on the computer where the state server service (aspnet_state) is running.</p>
<p><strong>State Server Sessions Timed Out</strong>
The number of user sessions that have become inactive through user inaction. This counter is available only on the computer where the state server service (aspnet_state) is running.</p>
<p><strong>State Server Sessions Total</strong>
The number of sessions created during the lifetime of the process. This counter is the total value of State Server Sessions Active, State Server Sessions Abandoned, and State Server Sessions Timed Out. This counter is available only on the computer where the state server service (aspnet_state) is running.</p>
|
<p>Tracking the number of users would need to be done at the application level, not the session level.</p>
<p>You should be able to see what is currently in the session with the following:</p>
<pre><code>StringBuilder builder = new StringBuilder();
foreach ( String key in Session.Contents ) {
builder.AppendFormat("{0}: {1}<br />", key, Session[key]);
}
Response.Write(builder.ToString());
</code></pre>
| 30,884
|
<p>We have a set of applications that were developed for the ASCII character set. Now, we're trying to install it in Iceland, and are running into problems where the Icelandic characters are getting screwed up.</p>
<p>We are working through our issues, but I was wondering: Is there a good "guide" out there for writing C++ code that is designed for 8-bit characters and which will work properly when UTF-8 data is given to it?</p>
<p>I can't expect everyone to read the whole Unicode standard, but if there is something more digestible available, I'd like to share it with the team so we don't run into these issues again.</p>
<p>Re-writing all the applications to use wchar_t or some other string representation is not feasible at this time. I'll also note that these applications communicate over networks with servers and devices that use 8-bit characters, so even if we did Unicode internally, we'd still have issues with translation at the boundaries. For the most part, these applications just pass data around; they don't "process" the text in any way other than copying it from place to place.</p>
<p>The operating systems used are Windows and Linux. We use std::string and plain-old C strings. (And don't ask me to defend any of the design decisions. I'm just trying to help fix the mess.)</p>
<hr>
<p>Here is a list of what has been suggested:</p>
<ul>
<li><a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow noreferrer">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a></li>
<li><a href="http://www.cl.cam.ac.uk/~mgk25/unicode.html" rel="nofollow noreferrer">UTF-8 and Unicode FAQ for Unix/Linux</a></li>
<li><a href="ftp://ftp.ilog.fr/pub/Users/haible/utf8/Unicode-HOWTO.html" rel="nofollow noreferrer">The Unicode HOWTO</a></li>
</ul>
|
<p>This looks like a comprehensive quick guide:<br>
<a href="http://www.cl.cam.ac.uk/~mgk25/unicode.html" rel="nofollow noreferrer">http://www.cl.cam.ac.uk/~mgk25/unicode.html</a></p>
|
<p>You may want to use wide characters (wchar_t instead of char and std::wstring instead of std::string). This doesn't automatically solve 100% of your problems, but is good first step.</p>
<p>Also use string functions which are Unicode-aware (refer to documentation). If something manipulates wide chars or string it generally is aware that they are wide.</p>
| 16,264
|
<p>Specifically, in VS 2008, I want to connect to a data source that you can have by right-clicking on the automatically-generated App_Data folder (an .mdf "database"). Seems easy, and it is once you know how.</p>
|
<p>So here's the answer from MSDN:</p>
<blockquote>
<p>Choos[e] "Add New Data Source" from the
Data menu.[And follow the connection wizard]</p>
</blockquote>
<p>Very easy, except that I have no Data menu. If you don't have a Data menu, do the following:</p>
<ul>
<li>Click on Tools >> Connect to Database...</li>
<li>Select "Microsoft SQL Server Database File", take the default Data provider, and click OK</li>
<li>On the next screen, browse to your Database file, which will be in your VS Solution folder structure somewhere.</li>
</ul>
<p>Test the connection. It'll be good. If you want to add the string to the web.config, click the Advanced button, and copy the Data Source line (at the bottom of the dialog box), and paste it into a connection string in the appropriate place in the web.config file. You will have to add the "<code>AttachDbFilename</code>" attribute and value. Example:</p>
<p>The raw text from the Advanced panel:</p>
<pre><code>Data Source=.\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True
</code></pre>
<p>The actual entry in the web.config:</p>
<pre><code><add name="SomeDataBase" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\Development\blahBlah\App_Data\SomeDataFile.mdf;
Integrated Security=True; Connect Timeout=30; User Instance=True" />
</code></pre>
|
<p>In your Login.aspx.cs (the code behind file for your login page in the submit button click event) add</p>
<pre><code>string constr = @"Data Source=(LocalDB)\v11.0; AttachDbFilename=|DataDirectory|\myData.mdf; Integrated Security=True; Connect Timeout=30;";
using (SqlConnection conn = new SqlConnection(constr))
string constr = ConfigurationManager.ConnectionStrings["myData"].ToString();
using (SqlConnection conn = new SqlConnection(constr))
{
sqlQuery=" Your Query here"
SqlCommand com = new SqlCommand(sqlQuery, conn);
com.Connection.Open();
string strOutput = (string)com.ExecuteScalar();
}
</code></pre>
| 20,865
|
<p>I am using a List Control to display a representation of elements within a vector. When the list is clicked on another control shows information about that element. The index of the element is currently determined by its index in the control, however if I wish to sort or filter the results this will no longer work.</p>
<p>I have been told that I could use a virtual list control, but the MSDN is not very friendly, can someone run me through how I could use a virtual list control for this?</p>
|
<p>Frankly - tying data (the position in your data vector) to the presentation of the data in the list control (the position in the list ctrl) is something I would stay away from.</p>
<p>In MFC each control has a "Data" DWORD member variable - when coding in MFC I Always called "SetItemData" for each item added and passed in a pointer that the relevant row referred to e.g.
<code>YourListCtrl.SetItemData((DWORDPTR)&YourData);</code> </p>
<p>Then when the ListCtrl item is selected, you just call </p>
<p><code>DataTypeYouWant* pData = (DataTypeYouWant*)(YourListCtrl.GetItemData(indexofselecteditem));</code> </p>
<p>Or somesuch thing.</p>
<p>Alternatively - if you don't want to use pointers - hold the index of the item in your original vector in the itemdata for your row (just pass it into the above fns).</p>
|
<p>To use a virtual list control, set the LVS_OWNERDATA style. You then need to handle the LVN_GETDISPINFO notification message (which is sent via WM_NOTIFY).</p>
<p>If you do this, you are entirely responsible for the data, including the order in which it is shown. Therefore it is up to you to handle sorting and so forth.</p>
<p>By far the easiest way is just to use the item data to set/get an ID that can be used to retrieve the original data, whether that's a vector index or a pointer to the data, or even a key into an associative container.</p>
| 22,694
|
<p>How do you solve the problem with soft hyphens on your web pages? In a text there can be long words which you might want to line break with a hyphen. But you do not want the hyphen to show if the whole word is on the same line.</p>
<p>According to comments on <a href="http://www.thefutureoftheweb.com/blog/breaking-long-urls" rel="noreferrer">this page</a> <code><wbr></code> is a non standard "tag soup invented by Netscape". It seems like <code>&shy;</code> <a href="http://www.cs.tut.fi/~jkorpela/shy.html" rel="noreferrer">has its problems with standard compliance as well</a>. There seems to be <a href="http://www.quirksmode.org/oddsandends/wbr.html" rel="noreferrer">no way to get a working solution for all browsers</a>.</p>
<p>Which is your way for handling soft hyphens and why did you choose it? Is there a preferred solution or best practice?</p>
<p><hr>
See related SO Discussion <a href="https://stackoverflow.com/questions/904/in-html-how-to-word-break-on-a-dash">here</a>.</p>
|
<p><del>Unfortunately, <code>&shy</code>'s support is so inconsistent between browsers that it can't really be used.</del></p>
<p><del>QuirksMode is right -- there's no good way to use soft hyphens in HTML right now. See what you can do to go without them.</del></p>
<p>2013 edit: <a href="http://www.quirksmode.org/oddsandends/wbr.html" rel="noreferrer">According to QuirksMode</a>, <code>&shy;</code> now works/is supported on all major browsers.</p>
|
<p>Sometimes web browsers seems to be more forgiving if you use the Unicode string <code>&#173;</code> rather than the <code>&shy;</code> entity.</p>
| 28,006
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.