instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm looking for the best way to log errors in an ASP.NET application.
I want to be able to receive emails when errors occurs in my application, with detailed information about the Exception and the current Request.</p>
<p>In my company we used to have our own ErrorMailer, catching everything in the Global.asax Application_Error. It was "Ok" but not very flexible nor configurable.</p>
<p>We switched recently to NLog. It's much more configurable, we can define different targets for the errors, filter them, buffer them (not tried yet). It's a very good improvement.</p>
<p>But I discovered lately that there's a whole Namespace in the .Net framework for this purpose : <a href="http://msdn.microsoft.com/en-us/library/system.web.management.aspx" rel="noreferrer">System.Web.Management</a> and it can be configured in the <a href="http://msdn.microsoft.com/en-us/library/2fwh2ss9(VS.80).aspx" rel="noreferrer">healthMonitoring</a> section of web.config.</p>
<p>Have you ever worked with .Net health monitoring? What is your solution for error logging?</p>
|
<p>I use <a href="http://code.google.com/p/elmah/" rel="noreferrer">elmah</a>. It has some really nice features and here is a <a href="http://www.codeproject.com/KB/aspnet/ELMAHDemo.aspx" rel="noreferrer">CodeProject</a> article on it. I think the StackOverflow team uses elmah also!</p>
|
<p>We use a custom homegrown logging util we wrote. It requires you to implement logging on your own everywhere you need it. But, it also allows you to capture a lot more than just the exception.</p>
<p>For example our code would look like this:</p>
<pre><code>Try
Dim p as New Person()
p.Name = "Joe"
p.Age = 30
Catch ex as Exception
Log.LogException(ex,"Err creating person and assigning name/age")
Throw ex
End Try
</code></pre>
<p>This way our logger will write all the info we need to a SQL database. We have email alerts set up at the DB level to look for certain errors or frequently occurring errors. It helps us identify exactly where the errors are coming from.</p>
<p>This might not be exactly what you're looking for. Another approach similar to using Global.asax is to us a code injection technique like <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" rel="nofollow noreferrer">AOP</a> with <a href="http://www.postsharp.org/" rel="nofollow noreferrer">PostSharp</a>. This allows you to inject custom code at the beginning and end of every method or on every exception. It's an interesting approach but I believe it may have a heavy performance overhead.</p>
| 3,306
|
<p>I came across PHP way of doing the trick:</p>
<pre><code>my_bool reconnect = 1;
mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);
</code></pre>
<p>but no luck with MySQLdb (python-mysql).</p>
<p>Can anybody please give a clue? Thanks.</p>
|
<p>I solved this problem by creating a function that wraps the <code>cursor.execute()</code> method since that's what was throwing the <code>MySQLdb.OperationalError</code> exception. The other example above implies that it is the <code>conn.cursor()</code> method that throws this exception.</p>
<pre><code>import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb.connect()
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
db = DB()
sql = "SELECT * FROM foo"
cur = db.query(sql)
# wait a long time for the Mysql connection to timeout
cur = db.query(sql)
# still works
</code></pre>
|
<p>You other bet it to work around dropped connections yourself with code.</p>
<p>One way to do it would be the following:</p>
<pre><code>import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb.connect()
def cursor(self):
try:
return self.conn.cursor()
except (AttributeError, MySQLdb.OperationalError):
self.connect()
return self.conn.cursor()
db = DB()
cur = db.cursor()
# wait a long time for the Mysql connection to timeout
cur = db.cursor()
# still works
</code></pre>
| 25,502
|
<p>Details:</p>
<ul>
<li>Only disable after user clicks the submit button, but before the posting back to the server</li>
<li>ASP.NET Webforms (.NET 1.1)</li>
<li>Prefer jQuery (if any library at all)</li>
<li>Must be enabled if form reloads (i.e. credit card failed)</li>
</ul>
<p>This isn't a necessity that I do this, but if there is a simple way to do it without having to change too much, I'll do it. (i.e. if there isn't a simple solution, I probably won't do it, so don't worry about digging too deep)</p>
|
<p>For all submit buttons, via JQuery, it'd be:</p>
<pre><code>$('input[type=submit]').click(function() { this.disabled = true; });
</code></pre>
<p>Or it might be more useful to do so on form submission:</p>
<pre><code>$('form').submit(function() {
$('input[type=submit]', this).attr("disabled","disabled");
});
</code></pre>
<p>But I think we could give a better answer to your question if we knew a bit more about the context.</p>
<p>If this is an ajax request, then you'll need to make sure you enable submit buttons again on either success or failure.</p>
<p>If this is a standard HTTP form submission (aside from disabling the button with javascript) and you're doing this to safe guard from multiple submissions of the same form, then you ought to have some sort of control in the code that deals with the submitted data, because disabling a button with javascript might not prevent multiple submissions.</p>
|
<p>There are three ways to submit a form that should be covered. Use both David McLaughlin's and Jimmy's suggestions. One will disable the submit button form element while the other disables the basic HTML form submit.</p>
<p>For the third, these won't disable Javascript from doing a form.submit(). The <code>OnSubmit="return false"</code> method only applies when a user clicks the submit button or presses Enter in a input form element. Client side scripting will need to be handled as well.</p>
| 6,810
|
<p>At work I am responsible for writing specifications quite often and I am also the person who insisted on getting specifications in the first place. The problem is I am unsure how specifications should look and what they should contain. A lot of the time when my boss is writing the specifications (we are both inexperienced in it) they put in table names and things that I don't think belong there. So what is a good way to learn to write a good spec?</p>
<p>EDIT: Should a functional spec include things like assuming I am specifying a web application, the input types (a textbox, dropdown list, etc)?</p>
|
<p>The most important part of development documentation in my opinion, is <strong>having the correct person do it.</strong></p>
<ul>
<li>Requirements Docs - Users + Business Analyst</li>
<li>Functional Spec - Business Analyst + developer </li>
<li>Technical Spec (how the functionality will actually be implemented) - Sr. Developer /
Architect </li>
<li>Time estimates for scheduling purposes - The <strong>specific developer</strong> assigned to the task</li>
</ul>
<p>Having anyone besides the Sr. Developer / Architect define table structures / interfaces etc. is an exercise in futility - as the more experienced developer will generally throw most of it out.</p>
<p>Wikipedia is actually a good start for the Functional Spec, which seems similar to your Spec - <a href="http://en.wikipedia.org/wiki/Functional_specification" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Functional_specification</a>.</p>
|
<p>The important thing is to get something written down rather than worry about the format.</p>
| 13,804
|
<p>Is there a way to be sure we hold a useable reference to an object i.e. being sure it has not been already freed leaving that non nil reference dangling.</p>
|
<p>If you're using FastMM4 as your Memory Manager, you can check that the class is not <strong>TFreeObject</strong>.<br>
Or, in a more standard case, use a routine that will verify that your object is what it says it is by <strong>checking the class VMT</strong>.</p>
<p>There have been such ValidateObj functions hannging around for some time (by Ray Lischner and Hallvard Vassbotn: <a href="http://hallvards.blogspot.com/2004/06/hack-6checking-for-valid-object.html" rel="nofollow noreferrer">http://hallvards.blogspot.com/2004/06/hack-6checking-for-valid-object.html</a>)</p>
<p>Here's another: </p>
<pre><code>function ValidateObj(Obj: TObject): Pointer;
// see { Virtual method table entries } in System.pas
begin
Result := Obj;
if Assigned(Result) then
try
if Pointer(PPointer(Obj)^) <> Pointer(Pointer(Cardinal(PPointer(Obj)^) + Cardinal(vmtSelfPtr))^) then
// object not valid anymore
Result := nil;
except
Result := nil;
end;
end;
</code></pre>
<p>Update: A bit of caution... The above function will ensure that the result is either nil or a valid non nil Object. It does not guarantee that the Obj is still what you think it is, in case where the Memory Manager has already reallocated that previously freed memory.</p>
|
<p>Unfortunately there is no way to 100% guarantee that a pointer to anything is still valid, except by meticolously writing the correct code.</p>
| 13,859
|
<p>I have a button inside an updatepanel. I have a PopupControlExtender linked to the button so when the button is clicked a panel pops up. It works fine except it does a full postback and I can't figure out why. The button and the PopupControlExtender is inside an update panel which inside the ContentTemplate tag. When I take out the PopupControlExtender the button only does a partial postback. I'm having trouble finding any useful information on the PopupControlExtender. Do I have to declare a postback trigger or something?</p>
<p>Edit: If I use a LinkButton control it generates a partial postback. Seems to only do the full postback with a Button control.</p>
|
<p>Ensure the button's UseSubmitBehavior property is set to false</p>
|
<p>I have the exact opposite issue: the Link Button causes a full post-back while the Button control works. However unlike the other answer, the Button only works if UseSubmitBehavior is True/undefined.</p>
<p>So I just use some CSS with the button to it look like a link button, e.g.</p>
<pre><code>input.linkButton
{
background-color: transparent;
border-style: none;
color: #0000FF;
cursor: pointer;
text-align: left;
text-decoration: underline;
}
</code></pre>
<p>(Thanks to Englestone's blog for that one).</p>
| 28,439
|
<p>On a JSTL/JSP page, I have a java.util.Date object from my application. I need to find the day <em>after</em> the day specified by that object. I can use <jsp:scriptlet> to drop into Java and use java.util.Calendar to do the necessary calculations, but this feels clumsy and inelegant to me.</p>
<p>Is there some way to use JSP or JSTL tags to achieve this end without having to switch into full-on Java, or is the latter the only way to accomplish this?</p>
|
<p>I'm not a fan of putting java code in your jsp.</p>
<p>I'd use a static method and a taglib to accomplish this.</p>
<p>Just my idea though. There are many ways to solve this problem.</p>
<pre><code>public static Date addDay(Date date){
//TODO you may want to check for a null date and handle it.
Calendar cal = Calendar.getInstance();
cal.setTime (date);
cal.add (Calendar.DATE, 1);
return cal.getTime();
}
</code></pre>
<p>functions.tld</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>functions library</description>
<display-name>functions</display-name>
<tlib-version>1.1</tlib-version>
<short-name>xfn</short-name>
<uri>http://yourdomain/functions.tld</uri>
<function>
<description>
Adds 1 day to a date.
</description>
<name>addDay</name>
<function-class>Functions</function-class>
<function-signature>java.util.Date addDay(java.util.Date)</function-signature>
<example>
${xfn:addDay(date)}
</example>
</function>
</taglib>
</code></pre>
|
<p>Unfortunately there is no tag in the standard JSP/JSTL libraries that I know of that would allow you to do this date calculation.</p>
<p>The simplest, and most inelegant, solution is to just use some scriptlet code to do the calculation. You've already stated that you think this is a clunky solution, and I agree with you. I would probably write a custom JSP taglib to get this if I were you.</p>
| 9,991
|
<p>We have several wizard style form applications on our website where we capture information from the user on each page and then submit to a backend process using a web service.</p>
<p>Unfortunately we can't submit the information in chunks during each form submission so we have to store it the users session until the end of the process and submit it all at the same time.</p>
<p>Is the amount of server memory/sql server disk space the only constraint on how much I can store in users sessions or is there something else I need to consider?</p>
<p>Edit: The site is built on ASP.NET web forms.</p>
|
<p>Assuming the information is not sensitive then you could store the information in a cookie which would reduce the amount of information required to be stored server side. This would also allow you to access the information via JavaScript. </p>
<p>Alternatively you could use the viewstate to store the information although this can lead to large amounts of data being sent between the server and the client and not my preferred solution.</p>
<p>The amount of session information you should store varies wildly depending on the application, number of expected users, server specification etc. To give a more accurate answer would require more information :)</p>
<p>Finally, assuming that the information collected throughout the process is not required from page to page then you could store all the information in a database table and only store the records unique id in the session. As each page is submitted the db record is updated and then on the final page all the information is retrieved and submitted. This is not an idea solution if you need to retrieve previous information on each subsequent page due to the number of db reads required.</p>
|
<p>If you use a traditional HTTP model (i.e. don't use runat="server") you can post the data to another asp page and place the posted data into hidden form elements, you can do this for however many pages you need thus avoiding placing anything in a session variable. </p>
| 9,863
|
<p>At my company most inventory tracking is done via an ASP.NET web application. The application is poorly conceived, poorly designed, poorly implemented, and somewhat of a hassle for a user to work with. These are things that are my opinion though and management has its own thoughts on the matter.</p>
<p>Such luxuries as the browser's back button and bookmarking pages are already not an option because of heaps and heaps of ancient Ajax code and now one of my bosses has the idea that he would prefer for the URL bar and browser buttons not to appear at all.</p>
<p>At first I told him that it was impossible but after thinking about it I suppose it could work if you used Javascript to create a fullscreen pop-up and run the application in that.</p>
<p>I personally am against this idea though since I'm the one who would do the work my own subconscious motivations are suspect so I'd like to gather some opinions on running an application in such a manner.</p>
<p>In addition, has anyone had any experience with transferring a regular webapp to such a setup? I'd like to know how much work could be in store for me.</p>
|
<p>Next time, for the good of the world, keep these kinds of ideas to yourself. It sounds like your boss is not qualified to make such a call, so make the call for him.</p>
<p>If your boss believes the url bar and browser buttons are not suppose to be there, then convert it to a stand alone app. Don't try to cram it into a web platform if its not suppose to be one.</p>
<p>You know the issues, so fight for what you think is right. Don't implement anything you are not going to be proud of.</p>
|
<p>I'd be tempted to simply add a button that <em>allows</em> you to pop out the app, without removing the normal mode.</p>
<p>If necessary, sell it with some waffle about users getting confused or not being able to reopen it or something. Or even pretend its not possible to do it without it.</p>
<p>That goes some way towards user friendliness. Salve your conscience anyway</p>
| 36,607
|
<p>We've just been given the following code as a solution for a complicated search query in a new application provided by offshore developers. I'm skeptical of the use of dynamic SQL because I could close the SQL statement using '; and then excute a nasty that will be performed on the database!</p>
<p>Any ideas on how to fix the injection attack?</p>
<pre><code>ALTER procedure [dbo].[SearchVenues] --'','',10,1,1,''
@selectedFeature as varchar(MAX),
@searchStr as varchar(100),
@pageCount as int,
@startIndex as int,
@searchId as int,
@venueName as varchar(100),
@range int,
@latitude varchar(100),
@longitude varchar(100),
@showAll int,
@OrderBy varchar(50),
@SearchOrder varchar(10)
AS
DECLARE @sqlRowNum as varchar(max)
DECLARE @sqlRowNumWhere as varchar(max)
DECLARE @withFunction as varchar(max)
DECLARE @withFunction1 as varchar(max)
DECLARE @endIndex as int
SET @endIndex = @startIndex + @pageCount -1
SET @sqlRowNum = ' SELECT Row_Number() OVER (ORDER BY '
IF @OrderBy = 'Distance'
SET @sqlRowNum = @sqlRowNum + 'dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ') ' +@SearchOrder
ELSE
SET @sqlRowNum = @sqlRowNum + @OrderBy + ' '+ @SearchOrder
SET @sqlRowNum = @sqlRowNum + ' ) AS RowNumber,ID,RecordId,EliteStatus,Name,Description,
Address,TotalReviews,AverageFacilityRating,AverageServiceRating,Address1,Address2,Address3,Address4,Address5,Address6,PhoneNumber,
visitCount,referalCount,requestCount,imgUrl,Latitude,Longitude,
Convert(decimal(10,2),dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ')) as distance
FROM VenueAllData '
SET @sqlRowNumWhere = 'where Enabled=1 and EliteStatus <> 3 '
--PRINT('@sqlRowNum ='+@sqlRowNum)
IF @searchStr <> ''
BEGIN
IF (@searchId = 1) -- county search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address5 like ''' + @searchStr + '%'''
END
ELSE IF(@searchId = 2 ) -- Town search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address4 like ''' + @searchStr + '%'''
END
ELSE IF(@searchId = 3 ) -- postcode search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address6 like ''' + @searchStr + '%'''
END
IF (@searchId = 4) -- Search By Name
BEGIN
IF @venueName <> ''
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @venueName + '%'' OR Address like ''%'+ @venueName+'%'' ) '
ELSE
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @searchStr + '%'' OR Address like ''%'+ @searchStr+'%'' ) '
END
END
IF @venueName <> '' AND @searchId <> 4
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @venueName + '%'' OR Address like ''%'+ @venueName+'%'' ) '
set @sqlRowNum = @sqlRowNum + ' ' + @sqlRowNumWhere
--PRINT(@sqlRowNum)
IF @selectedFeature <> ''
BEGIN
DECLARE @val1 varchar (255)
Declare @SQLAttributes varchar(max)
Set @SQLAttributes = ''
Declare @tempAttribute varchar(max)
Declare @AttrId int
while (@selectedFeature <> '')
BEGIN
SET @AttrId = CAST(SUBSTRING(@selectedFeature,1,CHARINDEX(',',@selectedFeature)-1) AS Int)
Select @tempAttribute = ColumnName from Attribute where id = @AttrId
SET @selectedFeature = SUBSTRING(@selectedFeature,len(@AttrId)+2,len(@selectedFeature))
SET @SQLAttributes = @SQLAttributes + ' ' + @tempAttribute + ' = 1 And '
END
Set @SQLAttributes = SUBSTRING(@SQLAttributes,0,LEN(@SQLAttributes)-3)
set @sqlRowNum = @sqlRowNum + ' and ID in (Select VenueId from '
set @sqlRowNum = @sqlRowNum + ' CachedVenueAttributes WHERE ' + @SQLAttributes + ') '
END
IF @showAll <> 1
set @sqlRowNum = @sqlRowNum + ' and dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ') <= ' + convert(varchar,@range )
set @withFunction = 'WITH LogEntries AS (' + @sqlRowNum + ')
SELECT * FROM LogEntries WHERE RowNumber between '+ Convert(varchar,@startIndex) +
' and ' + Convert(varchar,@endIndex) + ' ORDER BY ' + @OrderBy + ' ' + @SearchOrder
print(@withFunction)
exec(@withFunction)
</code></pre>
|
<p>As an aside, I would not use <code>EXEC</code>; rather I would use <code>sp_executesql</code>. See this superb article, <a href="http://www.sommarskog.se/dynamic_sql.html" rel="noreferrer">The Curse and Blessings of Dynamic SQL</a>, for the reason and other info on using dynamic sql.</p>
|
<p>I like dynamic SQL for search.</p>
<p>Where I have used it in the past I have used .Net prepared statements with any user generated string being passed in as a parameter NOT included as text in the SQL. </p>
<p>To run with the existing solution you can do a number of thing to mitigate risk.</p>
<ol>
<li>White list input, validate input so that it can only contain a-zA-Z0-9\w (alpha numerics and white space) (bad if you need to support unicode chars)</li>
<li>Execute any dynamic sql as a restricted user. Set owner of stored proc to a user which has only read access to the tables concerned. deny write to all tables ect. Also when calling this stored proc you may need to do it with a user with similar restrictions on what they can do, as it appares MS-SQL executes dynamic sql within a storedproc as the calling user not the owner of the storedproc. </li>
</ol>
| 33,652
|
<p>Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?</p>
|
<p>You can <a href="https://web.archive.org/web/20090503090851/http://www.plope.org/Members/chrism/flymake-mode" rel="nofollow noreferrer">use Pyflakes together with Flymake</a> in order to get instant notification when your python code is valid (and avoids a few common pitfalls as well).</p>
|
<p>You can use <a href="http://www.logilab.org/857" rel="nofollow noreferrer">pylint</a> for such things and there seems to be a way to integrate it into <a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode#toc8" rel="nofollow noreferrer">emacs</a>, but I've never done the latter b/c I'm a vim user.</p>
| 25,202
|
<p>I have heard umpteen times that we 'should not mix business logic with other code' or statements like that. I think every single code I write (processing steps I mean) consists of logic that is related to the business requirements..</p>
<p>Can anyone tell me what exactly consists of business logic? How can it be distinguished from other code? Is there some simple test to determine what is business logic and what is not?</p>
|
<p>Simply define what you are doing in plain English. When you are saying things businesswise, like "make those suffer", "steal that money", "destroy this portion of earth" you are talking about business layer. To make it clear, things that get you excited go here.</p>
<p>When you are saying "show this here", "do not show that", "make it more beautiful" you are talking about the presentation layer. These are the things that get your designers excited.</p>
<p>When you are saying things like "save this", "get this from database", "update", "delete", etc. you are talking about the data layer. These are the things that tell you what to keep forever at all costs.</p>
|
<p>For me, " <em>business logic</em> " makes up all the entities that represent data applicable to the problem domain, as well as the logic that decides on "what do do with the data"..</p>
<p>So it should really consist of "data transport" (not access) and "data manipulation".. Actually data access (stuff hitting the DB) should be in a different layer, as should presentation code.</p>
| 6,034
|
<p>3D printer use stepper motors for moving print head and extruding filament. They need to have good torque and resolution.</p>
<p>Microstepping improves resolution as much as 32 fold (I think) but reduces torque the higher you microstep.</p>
<p>So...</p>
<ol>
<li><p>Why not rotate the motor with microstepping at high RPM (which also reduces torque) and increase the torque by heavy gear reduction using a worm gear?</p>
</li>
<li><p>Won't the movement of printhead be even smoother and small errors in microstepping and unevenness of gears be averaged out using high RPM and gear reduction approach?</p>
</li>
<li><p>Does microstepping indeed provide accurate divisions of steps?</p>
</li>
<li><p>Can we get by with weaker motors because torque will be increased by gear reduction?</p>
</li>
<li><p>Can we get by with 48 step stepper motors instead of 200 step because gear reduction provides increased resolution?</p>
</li>
<li><p>There are extruders that use flex shaft to turn worm gear in direct extruder while motor is mounted on frame which turns flex shaft (zesty nimble comes to mind). Why don't they just use smallest possible stepper motor to rotate worm gear directly, instead?</p>
</li>
</ol>
<p>Increasing motor RPM and using gear reduction should preserve the precision and torque, letting you use weaker, lighter motors, potentially reducing granularity of movement. I thought this was simpler approach and I wanted to understand what would I be losing as trade offs. I had considered more friction at worm gear and wear, higher heating of motor etc. But may be it's like "don't fix what ain't broken". 3D printers aren't that costly nowadays. I just wish they were even cheaper.</p>
|
<p>To answer each point:</p>
<ul>
<li><em>Microstepping improves resolution as much as 32 fold (I think) but reduces torque the higher you micro-step.</em></li>
</ul>
<p>Torque is not reduced by micro-stepping. Torque reduction only occurs when you are moving at high RPMs. The motor's phase resistance has to be conducive to the target RPM's (or step rate). Further, micro-stepping can go as has as 1/256, and I have personally used 1/128. Some will say that all higher micro-stepping does is improve smoothness not accuracy. I have personally tested 1/128 micro-stepping over a 17-inch long axis. I was able to achieve accuracy and repeatability to within 5 microns.</p>
<ul>
<li><em>Why not rotate the motor with micro-stepping at high RPM (which also reduces torque) and increase the torque by heavy gear reduction using a worm gear?</em></li>
</ul>
<p>Backlash! The whole point of stepper motors is that they produce backlash-free movement. Putting a transmission between the electromagnetic and the end effector will create backlash that has to be compensated for during the movement. Modern CNC systems account for this in their movement profiles and incorporate automatic backlash compensation (e.g. Mach3)</p>
<ul>
<li><em>Won't the movement of printhead be even smoother and small errors in microstepping and unevenness of gears be averaged out using high RPM and gear reduction approach?</em></li>
</ul>
<p>It is already smooth enough with 1/64th or greater micro-stepping. The extrusion nozzle only goes down to 2mm.</p>
<ul>
<li><em>Does microstepping indeed provide accurate divisions of steps?</em></li>
</ul>
<p>Yes. Yes, it does.</p>
<ul>
<li><em>Can we get by with weaker motors because torque will be increased by gear reduction?</em></li>
</ul>
<p>No, because it will just stall.</p>
<ul>
<li><em>Can we get by with 48 step stepper motors instead of 200 step because gear reduction provides increased resolution?</em></li>
</ul>
<p>Apart from the fact that no one makes 48 steps per revolution motors, using a gear reduction would be counterintuitive. Currently, there are 400 steps per revolution motors, which actually increase accuracy without any torque losses.</p>
<ul>
<li><em>There are extruders that use flex shaft to turn worm gear in direct extruder while motor is mounted on frame which turns flex shaft (zesty nimble comes to mind). Why don't they just use smallest possible stepper motor to rotate worm gear directly, instead?</em></li>
</ul>
<p>Torque! If they used a small motor to drive the extruder they would have to compensate for the torque loss with higher power (i.e. voltages). This would lead to cooling issues for that motor.</p>
<p>Bottom line is that if you size the motors and design the system correctly then a transmission is not needed. If you want more torque, get bigger motors. If the gantry needs to be light weight, then use a delta or corexy mechanism.</p>
|
<p>There's an old rule that says "If the question starts with 'Why don't they,' the answer is most likely 'money.'"</p>
<p>In this case, the issue is the cost of worm gears. Properly mating worm gears are much more expensive to make than common spur gears. That probably accounts for most of it -- not to mention the 200 step motors we see on most FDM printers are a very common item, and the more you make of something the less each one costs.</p>
<p>Beyond that, you can't back-drive most worm gears (especially those with a high reduction ratio). That wouldn't affect an extruder (or would it? I've seen a lot of Things for knobs to go on the extruder motor shaft), but if I couldn't back-drive my X or Y axes I'd be very annoyed (having to use the manual motion control in the firmware for everything like bed tramming) -- even the lead screw Z axis can be back-driven without undue effort.</p>
<p>So, bottom line, what we have now works well enough and making it (maybe a very little bit) better would cost more than what we gain would be worth. IMO.</p>
| 1,963
|
<p>Is it possible to access the Abstract Syntax Tree(AST) inside the javac.exe programmatically? Could you provide an example?</p>
|
<p>Yes, it is possible, but only since Java 6. <a href="http://java.sun.com/developer/Meet-Eng/vonderahe/" rel="nofollow noreferrer">Peter von der Ahé</a> talks about the two JSRs in <a href="http://www.artima.com/lejava/articles/compiler_api.html" rel="nofollow noreferrer">this interview</a>. Of JSR 199: </p>
<blockquote>
<p>The JSR 199 Compiler API consists of three things: The first one basically allows you to invoke a compiler via the API. Second, the API allows you to customize how the compiler finds and writes out files. I mean files in the abstract sense, since the files the compiler deals with aren't necessarily on the file system. JSR 199's file abstraction allows you to have files in a database, and to generate output directly to memory, for example. Finally, the JSR 199 API lets you collect diagnostics from the compiler in a structured way so that you can easily transform error messages, for instance, into lines in an IDE's editor.</p>
</blockquote>
<p>JSR 269 is the annotation processing API.</p>
<p><a href="http://today.java.net/pub/a/today/2008/04/10/source-code-analysis-using-java-6-compiler-apis.html" rel="nofollow noreferrer">This article</a> gives an excellent overview of accessing the <a href="http://java.sun.com/javase/6/docs/jdk/api/javac/tree/index.html" rel="nofollow noreferrer">Compiler Tree API</a>. The section "<a href="https://web.archive.org/web/20151023040328/http://today.java.net/pub/a/today/2008/04/10/source-code-analysis-using-java-6-compiler-apis.html#accessing-the-abstract-syntax-tree-the-compiler-tree-api" rel="nofollow noreferrer">Accessing the Abstract Syntax Tree: The Compiler Tree API</a>" seems particularly suitable for your question.</p>
<p>Depending on what you're doing, you may also want to look at the <a href="http://jackpot.netbeans.org/docs/rule-language.html" rel="nofollow noreferrer">Jackpot Rule Language</a>, which is a standalone refactoring engine that plugins into the Compiler Tree.</p>
|
<p>Compile and run this with <code>-cp tools.jar</code> (where you have to specify the location of your <code>tools.jar</code>, obviously).</p>
<pre><code>import com.sun.source.util.Trees;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class JCTreeTest {
private static final JavaCompiler javac
= ToolProvider.getSystemJavaCompiler();
public static void main(String[] args) {
final StandardJavaFileManager jfm
= javac.getStandardFileManager(null, null, null);
final JavaCompiler.CompilationTask task
= javac.getTask(null, jfm, null, null, null,
jfm.getJavaFileObjects(args));
final Trees trees = Trees.instance(task);
// Do stuff with "trees"
}
}
</code></pre>
<p>It compiles and runs for me, though I have not played with the trees stuff myself, so you'll have to <a href="http://java.sun.com/javase/6/docs/jdk/api/javac/tree/" rel="noreferrer">read the javadoc</a> yourself. :-) Good luck!</p>
| 23,955
|
<p>Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?</p>
<p>Note: I am rewriting an existing system that is painfully slow.</p>
|
<p>Use <a href="http://php.net/str_split" rel="nofollow noreferrer">str_split()</a>:</p>
<pre><code>$string = '0123456789012345';
$sets = str_split($string, 4);
print_r($sets);
</code></pre>
<p>The output:</p>
<pre><code>Array
(
[0] => 0123
[1] => 4567
[2] => 8901
[3] => 2345
)
</code></pre>
<p>Then of course to insert hyphens between the sets you just <a href="http://php.net/implode" rel="nofollow noreferrer">implode()</a> them together:</p>
<pre><code>echo implode('-', $sets); // echoes '0123-4567-8901-2345'
</code></pre>
|
<p>If you are looking for a more flexible approach (for e.g. phone numbers), try regular expressions:</p>
<pre><code>preg_replace('/^(\d{4})(\d{4})(\d{4})(\d{4})$/', '\1-\2-\3-\4', '0123456789012345');
</code></pre>
<p>If you can't see, the first argument accepts four groups of four digits each. The second argument formats them, and the third argument is your input.</p>
| 39,116
|
<p>I have two C++ processes (A and B), executing under Windows, where one launches the other. I would like to effectively single-thread their execution. For example:</p>
<ol>
<li>Start process A</li>
<li>A creates B</li>
<li>A suspends</li>
<li>B executes some fixed set of operations</li>
<li>B suspends and A is resumed</li>
<li>A executes some fixed set of operations</li>
<li>A suspends and B is resumed</li>
<li>(Repeat 4 - 7)</li>
</ol>
<p>Which Windows synchronization and IPC services would be best to implement this type of behavior?</p>
|
<p>Events would work in this case:</p>
<ul>
<li>A creates an event an starts Process B</li>
<li>A waits for the event to be signaled</li>
<li>B also creates an event, does it's first item, then signals A's event (which either has a well-known name or the handle can be passed to B when it starts or using some other mechanism</li>
<li>B waits on its event</li>
<li>when A resumes from waiting on its event, it does its work, signals B's event and waits on its own</li>
<li>so on...</li>
</ul>
<p>Just be sure you have error handling so each process can resume and do whatever is necessary if the other one hangs or terminates unexpectedly. Timeouts can handle the hang situation, and waiting on the other process's handle (using WaitForMultipleObjects() along with both the process and event handle) can determine if/when the other process terminates.</p>
|
<p>For interprocess synchronization you could use <a href="http://en.wikipedia.org/wiki/Semaphores" rel="nofollow noreferrer">semaphores</a>. Here is the <a href="http://msdn.microsoft.com/en-us/library/ms686946(VS.85).aspx" rel="nofollow noreferrer">documentation</a>.</p>
| 31,008
|
<p>The <code>JFileChooser</code> seems to be missing a feature: a way to suggest the file name when saving a file (the thing that usually gets selected so that it would get replaced when the user starts typing).</p>
<p>Is there a way around this?</p>
|
<p>If I understand you correctly, you need to use the <code>setSelectedFile</code> method.</p>
<pre><code>JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setSelectedFile(new File("fileToSave.txt"));
jFileChooser.showSaveDialog(parent);
</code></pre>
<p>The file doesn't need to exist.</p>
<p>If you pass a File with an absolute path, <code>JFileChooser</code> will try to position itself in that directory (if it exists).</p>
|
<p>If that doesn't work, here is a workaround:</p>
<pre><code>dialog.getUI().setFileName( name )
</code></pre>
<p>But you should check whether the selection mode is <code>FILES_ONLY</code> or <code>FILES_AND_DIRECTORIES</code>. If it's <code>DIRECTORIES_ONLY</code>, then <code>setSelectedFile()</code> will strip the file name.</p>
| 46,506
|
<p>Is it possible to verify which source safe project is bound to my vs.net solution?</p>
<p>When I checkout a file in vs.net, then look up the file in source safe, it seems to be checking out a file from another project. When I look at the directory in 'set working folder' it seems to be ok.</p>
|
<p><strong>File > Source Control > Change Source Control...</strong> shows the bindings for your code.</p>
|
<p>In visual studio, under the file or edit menu, (I think it's the the file menu) there's a menu item that says "Source control"... Under there, there's a submenu named "Change Source Control" It's in there... </p>
| 48,286
|
<p>Failed to create component 'User Control 1'. the error message follows:</p>
<blockquote>
<p>'System.NullReferenceException : Object reference not set to an instance of an object.
at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object Component, Object Value)
.............. etc..........</p>
</blockquote>
<p>What should I do to fix this error?</p>
|
<p>When a User Control won't load into the Visual Studio designer here is what you need to do. These instruction are for vb.net project but c# should be similar. Also, before doing this close all open windows (or at least the source and designer files of the control you are working on.)</p>
<p>One last thing. The FIRST thing you should do is ensure that restarting visual studio doesn't fix the problem. If not you can try the steps that follow. These instructions assume that the errant user controls are in control library project in visual studio. If not you should be able to adjust the directions a bit to get it to work but it is much easier when the control is in its own project.</p>
<p>Do the following:</p>
<ol>
<li>Make the control library your startup project. </li>
<li>Open the properties for the control library project and click on the debug tab. </li>
<li>Under Start Action click the Start external program option and browse to the Visual Studio executable.</li>
</ol>
<p>NOTE: what this means is that when you run your solution it will fire up another instance of Visual Studio instead of actually running your solution. The First Instance of Visual Studion (INSTANCE_1) will "host" a second instance of visual studio (INSTANCE_2) when you run it. </p>
<ol start="4">
<li>Run your solution. INSTANCE_2 will load.</li>
<li>Switch back to INSTANCE_1. </li>
<li>In INSTANCE_1 hit CTRL-ALT-E. This will open up the exceptions dialog box. Check On the THROWN column checkbox next to Common Language Runtime Exceptions.</li>
</ol>
<p>NOTE: This will ensure that INSTANCE_1 will BREAK at ANY runtime error even if it is hit in a try block.</p>
<ol start="7">
<li>Switch to INSTANCE_2. In Solution Explorer double-click to open the errant user control. </li>
</ol>
<p>You should find that INSTANCE_1 OF Visual Studio should have stopped at the line of code that caused the designer to not load the control. Fix the code (which usually means testing for IsNot Nothing before references an object properties...but could mean other things.)</p>
<p>Also, sometimes I find that the control WILL load in INSTANCE_2 instead of breaking on an error in INSTANCE_1. In that case just stop debugging...close INSTANCE_2. Save/Restart INSTANCE_1 and your problem will often have gone away. </p>
<p>The lesson is this. User Control MUST be able to load/reference all objects and their members in order to load it into the designer. So for User Controls that will be placed onto other containers I will usually design events to notify the parent rather than trying to push objects into the child control. </p>
<p>Hope this helps for future reference on this old question.</p>
<p>Seth</p>
|
<p>Thanks, Seth, for this post! Your solution helped me nail down the error. The only thing I would add to this is that when "INSTANCE_2" loads, you may need to actually load the project file in INSTANCE_2. I needed to because I wasn't dealing with a control library, but instead had custom User Controls defined in the same project that the forms were located in. Once I loaded the project in INSTANCE_2, I opened the erring form and that caused INSTANCE_1 to pop up to the line of offending code in the User Control.</p>
| 47,634
|
<p>I have a user table like this</p>
<pre><code>user_id | community_id | registration_date
--------------------------------------------
1 | 1 | 2008-01-01
2 | 1 | 2008-05-01
3 | 2 | 2008-01-28
4 | 2 | 2008-07-22
5 | 3 | 2008-01-11
</code></pre>
<p>For each community, I would like to get the time that the 3rd user registered. I can easily do this for a single community using MySql's 'limit' SQL extension. For example, for community with ID=2</p>
<pre><code>select registration_date
from user
order by registration_date
where community_id = 2
limit 2, 1
</code></pre>
<p>Alternatively, I can get the date that the first user registered for all communities via:</p>
<pre><code>select community_id, min(registration_date)
from user
group by 1
</code></pre>
<p>But I can't figure out how to get the registration date of the 3rd user for <em>all</em> communities in a single SQL statement.</p>
<p>Cheers,
Don</p>
|
<p>With an inner select:</p>
<pre><code>select
registration_date, community_id
from
user outer
where
user_id IN (
select
user_id
from
user inner
where
inner.community_id = outer.community_id
order by
registration_date
limit 2,1
)
order by registration_date
</code></pre>
<p>Selects the set of users where each user is the 3rd user in their community as returned by the limit clause in the inner select.</p>
|
<p>Is this what you mean?</p>
<pre><code>SELECT registration_date
FROM user
ORDER BY registration_date
LIMIT n
</code></pre>
<p>Where <em>n</em> is the user you are concerned about.</p>
| 45,540
|
<p>Is there a way to combine a previous translation when extracting the csv file from an application?
Or any other tool that could do this job for me? </p>
<p>I can’t really see how could i use locbaml if i had to translate everything from scratch every time i add a new control in my application.</p>
|
<p>You could use the <strong>last-child</strong> pseudo-class on the li element to achieve this</p>
<pre><code><html>
<head>
<style type="text/css">
ul li:last-child
{
font-weight:bold
}
</style>
</head>
<body>
<ul>
<li>IE</li>
<li>Firefox</li>
<li>Safari</li>
</ul>
</body>
</html>
</code></pre>
<p>There is also a first-child pseudo class available.</p>
<p>I am not sure the last-child element works in IE though.</p>
|
<p>Does jquery come bundled with drupal, if so you could use </p>
<pre><code>$('ul>li:last').addClass('last');
</code></pre>
<p>to achieve this</p>
| 13,882
|
<p>Here's my problem: I have to call a web service with a secure header from a classic ASP page that returns a complex data type. For various reasons concerning a 3rd party tool it has to be classic ASP. We decided that I should create an external dll to do this - which I did (in c#) so it returns a dataset (Something ASP can understand). However now I need to expose that function to the ASP page. Because this is classic ASP I think the only straightforward way to do this is to expose this class library as a COM object. I need to know the down and dirty easiest way to accomplish this task. What do I have to do to my dll?<br><br>
I have never created a COM object before only used. Somebody said my class has to be static and I can't have a constructor. Is this true? Can someone layout the steps for me?</p>
<p>HELP! (o:</p>
<p>Edit: This specific problem is now solved however as Robert Rossney noted I can't do anything with the DataSet in classic ASP. This has led me to post a second question <a href="https://stackoverflow.com/questions/301045/problem-implementing-xmltextwriter-in-new-xmlrecordsetwriter-for-streams">here</a> regarding implementing XmlTextWriter - Robert if you see this I think you could really help! </p>
|
<p>No, that (static/no ctor) isn't true. Quite the opposite, in fact, since COM will need to create an instance! You simply need to make the class COM visible. Mainly, this is just adding some attributes, and registering it as a COM dll (regasm).</p>
<p><a href="http://msdn.microsoft.com/en-us/library/zsfww439.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/zsfww439.aspx</a></p>
|
<blockquote>
<p>Somebody said my class has to be
static and I can't have a constructor.
Is this true? </p>
</blockquote>
<p>A COM class needs to have a default constructor, which will be used by clients when they call CoCreateInstance. After the object is created, you can set properties on it, or call other methods.</p>
<p>This is similar to the way that .Net treats serializable objects... you construct it with a default constructor, then set all its properties. (If you like RAII, you're out of luck with both COM and .Net. Get over it;)</p>
<p>As to the static comment, no, that isn't true, as Marc pointed out.</p>
| 37,214
|
<p>I found a bug in the Contains statement in Linq (not sure if it is really in Linq or Linq to SQL) and want to know if anyone else has seen this and if there is a fix or workaround.</p>
<p>If the querysource you do the contains with has more than 10 items in it, it does not pass the items correctly to the SQL query. It is hard to explain what it does, an example will show it best.</p>
<p>If you look at the raw query, the parameters look like this:</p>
<pre><code>@P0 = 'aaa'
@P1 = 'bbb'
@P2 = 'ccc'
... [@P3 through @P9]
@P10 = '111'
@P11 = '222'
... [@p12 through @P19]
@P20 = 'sss'
... [@P21 through @P99]
@P100 = 'qqq'
</code></pre>
<p>when the values are passed into the final query (all parameters resolved) it has resolved the parameters as if these were the values passed:</p>
<pre><code>@P0 = 'aaa'
@P1 = 'bbb'
@P2 = 'ccc'
...
@P10 = 'bbb'0
@P11 = 'bbb'1
...
@P20 = 'ccc'0
...
@P100 = 'bbb'00
</code></pre>
<p>So it looks like the parameter resolving looks at the first digit only after the <code>@P</code> and resolves that, then adds on anything left at the end of the parameter name.</p>
<p>At least that is what the Sql Server Query Visualizer plugin to Visual Studio shows the query doing.</p>
<p>Really strange.</p>
<p>So if any one has advice please share. Thanks!</p>
<p><strong>Update:</strong><br>
I have rewritten the original linq statement to where I now use a join instead of the Contains, but would still like to know if there is a way around this issue.</p>
|
<p>The more I look at it, and after running more tests, I'm thinking the bug may be in the Sql Server Query Visualizer plugin for Visual Studio, not actually in Linq to SQL itself. So it is not nearly as bad a situation as I thought - the query will return the right results, but you can't trust what the Visualizer is showing. Not great, but better than what I thought was going on.</p>
|
<p>Try actually looking at the output from your datacontext before you pass judgement.</p>
<p>DataContext.Log() will give you the generated SQL.</p>
| 8,460
|
<p>Our application exposes queries by way of web services, and what we've found is that our clients often want custom queries, either by way of further limiting the results returned by specifying additional criteria, or by asking for things that we don't already expose.</p>
<p>Now, we can take the approach of creating new methods for each of these new methods, but that's somewhat inconvenient; deployment of our application at a client site usually requires weeks of staged integration testing. We've proposed a named query mechanism, where the application administrator would define queries by name that are parameterized, and a corresponding web service that simply invokes these parameters. However, I can't help but think that someone has solved this problem before, so I'd like some input from the SO community on possible designs.</p>
<p>Thanks!</p>
<p><strong>Updates</strong></p>
<p>The specification pattern is a good one, but our application deals with enough data that we want to push as much of the querying work down into an RDBMS, which can do a better job of optimizing the query plan than we would ever want to. Moreover, we support three RDBMS backends, so we're stuck using a greatest-common-denominator approach: we use as much capability as the least functional database can provide.</p>
|
<p>I would also recommend to consider the "Specification Pattern" in this type of applications as a design decision for your backend. Check the following posts about "Specification Pattern":</p>
<p><a href="http://www.mattberther.com/2005/03/25/the-specification-pattern-a-primer/" rel="nofollow noreferrer">http://www.mattberther.com/2005/03/25/the-specification-pattern-a-primer/</a></p>
<p><a href="http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx" rel="nofollow noreferrer">http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx</a></p>
|
<p>Since we really don't know which how your users use your interface it seems a little premature to give a technical advice on something that feels a lot closer to "<a href="http://books.google.se/books?id=04cFCVXC_AUC&dq=Inmates+are+running+the+Asylum&pg=PP1&ots=jfvgZ3v_qK&source=bn&sig=i2Y92rSllNxflFMEksRjRWAuc5E&hl=sv&sa=X&oi=book_result&resnum=4&ct=result" rel="nofollow noreferrer">Inmates are running the Asylum</a>" problem.
There are some very good advice and common ways to solve this i technical aspects but do they work for your users? Maybe the really don't give a crap about your problem but rather have a fine working one button solution? (Or more like google?) </p>
| 32,069
|
<p>Does any know a good rule of thumb for the appropriate pagefile size for a Windows 2003 server running SQL Server?</p>
|
<p>Irrelevant of the size of the RAM, you still need a pagefile at least 1.5 times the amount of physical RAM. This is true even if you have a 1 TB RAM machine, you'll need 1.5 TB pagefile on disk (sounds crazy, but is true).</p>
<p>When a process asks MEM_COMMIT memory via VirtualAlloc/VirtualAllocEx, the requested size needs to be reserved in the pagefile. This was true in the first Win NT system, and is still true today see <a href="http://msdn.microsoft.com/en-us/library/ms810627.aspx" rel="noreferrer">Managing Virtual Memory in Win32</a>:</p>
<blockquote>
<p>When memory is committed, physical
pages of memory are allocated <strong>and
space is reserved in a pagefile</strong>.</p>
</blockquote>
<p>Bare some extreme odd cases, SQL Server will always ask for MEM_COMMIT pages. And given the fact that SQL uses a <a href="http://msdn.microsoft.com/en-us/library/ms178145.aspx" rel="noreferrer">Dynamic Memory Management</a> policy that reserves upfront as much buffer pool as possible (reserves and <em>commits</em> in terms of VAS), SQL Server will request at start up a huge reservation of space in the pagefile. If the pagefile is not properly sized errors 801/802 will start showing up in SQL's ERRORLOG file and operations. </p>
<p>This always causes some confusion, as administrators erroneously assume that a large RAM eliminates the need for a pagefile. In truth the contrary happens, a large RAM increases the need for pagefile, just because of the inner workings of the Windows NT memory manager. The reserved pagefile is, hopefully, never used. </p>
|
<p>If you're looking for high performance, you are going to want to avoid paging completely, so the page file size becomes less significant. Invest in as much RAM as feasible for the DB server.</p>
| 2,472
|
<p>Is there a good way to add a .swf programatically to a panel on an asp.net page - ie: I know i could just insert the html tags:</p>
<p>ie: </p>
<pre><code><object type="application/x-shockwave-flash" data="yourflash.swf" width="" height="">
<param name="movie" value="yourflash.swf">
</object>
</code></pre>
<p>But is there an existing .net or free FLASH component already that you just set the properties on, or do i need to create a custom web control myself (not preferred) so i dont have to continously do this?</p>
<p>Thank you. </p>
|
<p>The problem is having the groupbox as the controls' parent. Groupboxes are not supposed to have any children and using them as parents will cause all kinds of errors (including painting, keyboard navigation and message propagation). Just change the parent in the buttons' CreateWindow call from <strong>group_box</strong> to <strong>hwnd</strong> (i.e. the dialog).</p>
<p>I'm guessing you used the groupbox as the parent in order to position the other controls easily inside it. The proper way to do this is to get the position of the groupbox client area and map it to the client area of the dialog. Everything placed in the resulting RECT will then appear inside the groupbox. Since groupboxes don't actually have a client area, it can be calculated with something like this:</p>
<pre><code>// Calculate the client area of a dialog that corresponds to the perceived
// client area of a groupbox control. An extra padding in dialog units can
// be specified (preferably in multiples of 4).
//
RECT getClientAreaInGroupBox(HWND dlg, int id, int padding = 0) {
HWND group = GetDlgItem(dlg, id);
RECT rc;
GetWindowRect(group, &rc);
MapWindowPoints(0, dlg, (POINT*)&rc, 2);
// Note that the top DUs should be 9 to completely avoid overlapping the
// groupbox label, but 8 is used instead for better alignment on a 4x4
// design grid.
RECT border = { 4, 8, 4, 4 };
OffsetRect(&border, padding, padding);
MapDialogRect(dlg, &border);
rc.left += border.left;
rc.right -= border.right;
rc.top += border.top;
rc.bottom -= border.bottom;
return rc;
}
</code></pre>
<p>Note that the same applies to Tab controls. They too are not designed to be parents and will exhibit similar behavior.</p>
|
<p>Ahh yes the black background with radio buttons and group boxes. Although I'm not sure if this will work for VC++ 2008, but back-in-the-day the solution for VB6 themed apps was to put the radio controls on a PictureBox (a generic container really) first and then add that to the group box.</p>
<p>Its worth a shot!</p>
| 26,372
|
<p>Someone please correct me if I'm wrong, but parsing a yyyy/MM/dd (or other specific formats) dates in C# <strong>should</strong> be as easy as </p>
<pre><code>DateTime.ParseExact(theDate, "yyyy/MM/dd");
</code></pre>
<p>but no, C# forces you to create an IFormatProvider.</p>
<p>Is there an app.config friendly way of setting this so I don't need to do this each time?</p>
<pre><code>DateTime.ParseExact(theDate, "yyyy/MM/dd", new CultureInfo("en-CA", true));
</code></pre>
|
<p>The IFormatProvider argument can be null.</p>
|
<p>//Convert date to MySql compatible format</p>
<p>DateTime DateValue = Convert.ToDateTime(datetimepicker.text);</p>
<p>string datevalue = DateValue.ToString("yyyy-MM-dd");</p>
| 9,023
|
<p>Currently i have this method:</p>
<pre><code>static boolean checkDecimalPlaces(double d, int decimalPlaces){
if (d==0) return true;
double multiplier = Math.pow(10, decimalPlaces);
double check = d * multiplier;
check = Math.round(check);
check = check/multiplier;
return (d==check);
}
</code></pre>
<p>But this method fails for <code>checkDecmialPlaces(649632196443.4279, 4)</code> probably because I do base 10 math on a base 2 number.</p>
<p>So how can this check be done correctly?</p>
<p>I thought of getting a string representation of the double value and then check that with a regexp - but that felt weird.</p>
<p><strong>EDIT:</strong>
Thanks for all the answers. There are cases where I really get a double and for those cases I implemented the following: </p>
<pre><code>private static boolean checkDecimalPlaces(double d, int decimalPlaces) {
if (d == 0) return true;
final double epsilon = Math.pow(10.0, ((decimalPlaces + 1) * -1));
double multiplier = Math.pow(10, decimalPlaces);
double check = d * multiplier;
long checkLong = (long) Math.abs(check);
check = checkLong / multiplier;
double e = Math.abs(d - check);
return e < epsilon;
}
</code></pre>
<p>I changed the <code>round</code> to a truncation. Seems that the computation done in <code>round</code> increases the inaccuracy too much. At least in the failing testcase.<br>
As some of you pointed out if I could get to the 'real' string input I should use <code>BigDecimal</code> to check and so I have done: </p>
<pre><code>BigDecimal decimal = new BigDecimal(value);
BigDecimal checkDecimal = decimal.movePointRight(decimalPlaces);
return checkDecimal.scale() == 0;
</code></pre>
<p>The <code>double</code> value I get comes from the Apache POI API that reads excel files. I did a few tests and found out that although the API returns <code>double</code> values for numeric cells I can get a accurate representation when I immediately format that <code>double</code> with the <code>DecimalFormat</code>: </p>
<pre><code>DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMaximumIntegerDigits(Integer.MAX_VALUE);
// don't use grouping for numeric-type cells
decimalFormat.setGroupingUsed(false);
decimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
value = decimalFormat.format(numericValue);
</code></pre>
<p>This also works for values that can't be represented exactly in binary format.</p>
|
<p>The test fails, because you have reached the accuracy of the binary floating point representation, which is approximately 16 digits with <a href="http://en.wikipedia.org/wiki/Double_precision" rel="nofollow noreferrer">IEEE754 double precision</a>. Multiplying by 649632196443.4279 by 10000 will truncate the binary representation, leading to errors when rounding and dividing afterwards, thereby invalidating the result of your function completely.</p>
<p>For more details see <a href="http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems</a></p>
<p>A better way would be to check whether the <code>n+1</code> decimal places are below a certain threshold. If <code>d - round(d)</code> is less than <a href="http://en.wikipedia.org/wiki/Epsilon" rel="nofollow noreferrer"><code>epsilon</code></a> (see <a href="http://en.wikipedia.org/wiki/Limit_(mathematics)" rel="nofollow noreferrer">limit</a>), the decimal representation of <code>d</code> has no significant decimal places. Similarly if <code>(d - round(d)) * 10^n</code> is less than <code>epsilon</code>, d can have at most <code>n</code> significant places. </p>
<p>Use <a href="https://stackoverflow.com/users/22656/jon-skeet">Jon Skeet</a>'s <a href="http://pobox.com/~skeet/csharp/DoubleConverter.cs" rel="nofollow noreferrer"><code>DoubleConverter</code></a> to check for the cases where <code>d</code> isn't accurate enough to hold the decimal places you are looking for.</p>
|
<p>I'm not sure that this is really doable in general. For example, how many decimal places does <code>1.0e-13</code> have? What if it resulted from some rounding error while doing arithmetic and really is just <code>0</code> in disguise? If on, the other hand you are asking if there are any non-zero digits in the first <strong>n</strong> decimal places you can do something like:</p>
<pre><code> static boolean checkDecimalPlaces(double d, unsigned int decimalPlaces){
// take advantage of truncation, may need to use BigInt here
// depending on your range
double d_abs = Math.abs(d);
unsigned long d_i = d_abs;
unsigned long e = (d_abs - d_i) * Math.pow(10, decimalPlaces);
return e > 0;
}
</code></pre>
| 33,198
|
<p>How to take screenshot programmically of desktop area in Mac OS X ?</p>
|
<p>Two interesting options I have seen, but yet to use professionally, are the screencapture utility and a MacFuse demo.</p>
<p>The screencapture utility has been around since 10.2, according to the man page, and could be linked to a Cocoa application by use of NSTask.</p>
<p>The MacFuse demo worked by creating a new screenshot each time a folder was opened, or something like that. The idea being you could write a quick script to access the image when you needed it, without having to have the script actually run on that machine.</p>
<p>But seriously, Apple has some other sample code called "Son of Grab" which uses the new CGWindow API which is pretty awesome. </p>
<p><a href="http://developer.apple.com/samplecode/SonOfGrab/" rel="noreferrer">http://developer.apple.com/samplecode/SonOfGrab/</a></p>
|
<p>If you consider REALbasic, this is extremely easy to do with RB and the MBS Plugins. I've just written an application that does timed screenshots using RB and the MBS Plugins. You can read about it here: <a href="http://tektalkin.blogspot.com/2008/08/screenaudit-for-mac-osx.html" rel="nofollow noreferrer">http://tektalkin.blogspot.com/2008/08/screenaudit-for-mac-osx.html</a></p>
| 5,993
|
<p>On POSIX systems rename(2) provides for an atomic rename operation, including overwriting of the destination file if it exists and if permissions allow.</p>
<p>Is there any way to get the same semantics on Windows? I know about MoveFileTransacted() on Vista and Server 2008, but I need this to support Win2k and up.</p>
<p>The key word here is <em>atomic</em>... the solution must not be able to fail in any way that leaves the operation in an inconsistent state.</p>
<p>I've seen a lot of people say this is impossible on win32, but I ask you, is it really? </p>
<p>Please provide reliable citations if possible.</p>
|
<p>Win32 does not guarantee atomic file meta data operations. I'd provide a citation, but there is none - that fact that there's no written or documented guarantee means as much.</p>
<p>You're going to have to write your own routines to support this. It's unfortunate, but you can't expect win32 to provide this level of service - it simply wasn't designed for it.</p>
|
<p>There is <a href="https://en.cppreference.com/w/cpp/io/c/rename" rel="nofollow noreferrer">std::rename</a> and starting with <a href="https://en.wikipedia.org/wiki/C%2B%2B17" rel="nofollow noreferrer">C++17</a> <a href="https://en.cppreference.com/w/cpp/filesystem/rename" rel="nofollow noreferrer">std::filesystem::rename</a>.
It's unspecified what happens if destination exists with <code>std::rename</code>:</p>
<blockquote>
<p>If new_filename exists, the behavior is implementation-defined.</p>
</blockquote>
<p>POSIX <a href="https://pubs.opengroup.org/onlinepubs/009695399/functions/rename.html" rel="nofollow noreferrer">rename</a>, however, is <a href="https://pubs.opengroup.org/onlinepubs/009695399/functions/rename.html#tag_03_608_08" rel="nofollow noreferrer">required to replace existing files atomically</a>:</p>
<blockquote>
<p>This rename() function is equivalent for regular files to that defined
by the ISO C standard. Its inclusion here expands that definition to
include actions on directories and specifies behavior when the new
parameter names a file that already exists. That specification
requires that the action of the function be atomic.</p>
</blockquote>
<p>Thankfully, <code>std::filesystem::rename</code> requires that it behaves just like POSIX:</p>
<blockquote>
<p>Moves or renames the filesystem object identified by old_p to new_p as
if by the POSIX rename</p>
</blockquote>
<p>However, when I tried to debug, it appears that <code>std::filesystem::rename</code> as implemented by VS2019 (as of March 2020) simply calls <a href="https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexa" rel="nofollow noreferrer">MoveFileEx</a>, which isn't atomic in some cases.
So, possibly, when all bugs in its implementation are fixed, we'll see portable atomic <code>std::filesystem::rename</code>.</p>
| 20,218
|
<p>We have a .NET application that uses WMI to gather a wide range of information on machines throughout a network, such as reading the Win32_NTLogEvent to see if Symantec Antivirus has written anything. The queries work fine, but after repeatedly running a WMI query "Generic Failure" errors will start coming back. This happens very consistently after approx. 125 calls. Rebooting the machine that we are running the WMI query against, always fixes the error... that is until the next 125 queries are run. </p>
<p>It appears that the repository is fine and we can't locate any log file size issues.</p>
<p>More Info - Ran WMIDiag after getting the error and found -</p>
<p>25607 13:55:38 (1) !! ERROR: WMI ENUMERATION operation errors reported: 2 ERROR(S)!</p>
<p>25608 13:55:38 (0) ** - ROOT/CIMV2, SubClassesOf, '*', 0x80041006 - (WBEM_E_OUT_OF_MEMORY) Not enough memory for the operation.</p>
<p>25609 13:55:38 (0) ** MOF Registration: 'C:\WINNT\SYSTEM32\WBEM\SNMPREG.MOF
'
25610 13:55:38 (0) ** - Root/CIMv2, InstancesOf, 'Win32_PerfFormattedData_PerfProc_Thread', 0x8007000E - Not enough storage is available to complete this operation..</p>
<p>25611 13:55:38 (0) ** MOF Registration: 'C:\WINDOWS\SYSTEM32\WBEM\WMI.MOF'</p>
<p>Anyone ever see this? Ideas?</p>
|
<p>I believe we have found the issue. To simplify some of our queries we were adding something like 1=1 in the where clause to ease the building of the query. Removed the constant=constant and the one query I was testing with went from 40 seconds to .4 seconds and has run over 10,000 times without generating a generic failure (WBEM_E_OUT_OF_MEMORY).</p>
|
<p>Windows Remote Management (WinRM) may overcome all these problems.
WinRM is the Microsoft implementation of WS-Management Protocol, a standard Simple Object Access Protocol (SOAP)-based.</p>
| 25,108
|
<p>I would like to buy a 3D printer, but I'm concerned about the health risks that are associated with its operation. Some groups of scientists say it can be <a href="http://www.techworld.com/news/personal-tech/scientists-warn-of-3d-printing-health-effects-as-tech-hits-high-street-3460992/">harmful</a> for humans.</p>
<p>What do I need to consider before buying a 3D printer if I care about my health? Are there any safe printers?</p>
|
<p>There is very little information about safety available, as home 3D printers are relatively new. However, plastics such as ABS have a long history in making plastic products, and a study found that at traditional manufacturing methods (such as injection molding and hot wire cutting) <a href="http://annhyg.oxfordjournals.org/content/57/3/399">do not release dangerous levels of carcinogens and/or respiratory sensitizers in to the air</a>.</p>
<p>Of course, 3D printers are not among the processes covered in the study. In home 3D printing circles, <a href="http://www.sciencedirect.com/science/article/pii/S1352231013005086">this study</a> that looks at ultrafine particle (UFP) emissions, is often cited. It finds that printing ABS releases relatively high levels of UFP's and PLA releases significantly fewer (but still quite a large amount). However, it is unclear whether/how dangerous these UFP's are in the amounts emitted.</p>
<p>It is often suggested that PLA, partly because of the reduced UFP emissions is safer to print than ABS, partly because of its "natural" origins as it can be derived from materials such as cornstarch. I would caution against this line of reasoning since "natural" materials can still be poisonous (snake venom is natural, after all) and the cornstarch is heavily processed so it hardly resembles its original form. The lower UFP emissions may suggest it is safer, but the study is only quantitative, not qualitative.</p>
<p>That said, PLA does probably pose less of a risk (despite my earlier argumentation against "natural" materials, PLA does play quite nicely with the human body), but I contend the risk with ABS is not too large anyways, given that it has been safely used in factories for decades.</p>
<p><a href="http://fire.nist.gov/bfrlpubs/fire86/art017.html">Another study</a> is often miscited, supposedly saying that 3D printing ABS releases hydrogen cyanide. The study only looks at the thermal decomposition of ABS, which happens at significantly higher temperatures than are reached during printing (but a significantly malfunctioning printer might cause toxic gasses to be released, but I contend that at that point you should worry about your printer being on fire, rather than temporary exposure to some toxins).</p>
<p>There are no printers out there that are fundamentally safer than others. However, some printers have an enclosure (containing the fumes) and some even have a carbon filter and a fan for fume extraction. If you would like to err on the side of caution, this might be a good choice (but again, it is not clear if a carbon filter is totally effective).</p>
<p>Finally, as printers are generally quite noisy it tends to be preferrable to keep your printer in a separate room from where you usually work. In this case, fume exposure (during the few minutes that you go to check on your print) is minimal, and the potential advantages of a "safer" printers or using "safer" materials diminish.</p>
<p>Incidental exposure as a hobbyist is probably not a big deal; workers in factories are exposed to the fumes of melted plastic their entire lives and they don't seem to be dropping dead. On the other hand, if you are going to be printing structurally then it is probably preferable to move your printer to a separate room, if not because of health and safety because of the noise.</p>
|
<p>Apart from the inherent process itself and direct health hazards from that, many 3D printers also require some complementary technology to work.</p>
<p><a href="/questions/tagged/fdm" class="post-tag" title="show questions tagged 'fdm'" rel="tag">fdm</a> printers have a printing head that needs to move around in 3D space. <strong>Moving machinery parts can be a hazard</strong>. In a home/hobbyist environment with children for example, I would recommend to buy a printer with a housing. </p>
<p>"open" designs often feature <strong>bare electronics</strong> mounted directly to the printer structure. This rises the possibility of short circuits and electric shock.</p>
<p>The printers that heat material often do so at very high temperatures. <strong>Hot parts of the printer</strong> should not be touched.</p>
| 83
|
<p>I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them. </p>
<p>I think GUI design should be done in a separate text-based file in some markup format, which is read and rendered (e.g. HTML), so that the design of the interface is not tightly coupled with the rest of the code.</p>
<p>I've seen <a href="http://www.terrainformatica.com/htmlayout/" rel="nofollow noreferrer">HTMLayout</a> and I love the idea, but so far it seems be only in C++. </p>
<p>I'm looking for a python library (or even a WIP project) for doing markup-based gui.</p>
<p><strong>UPDATE</strong></p>
<p>The reason I can't accept QT's xml is the same reason I hate the programatic approach; you're assembling each widget separately, and specifying each property of it on a separate line. It doesn't provide any advantage over doing it the programatic way.</p>
|
<p>You can try Mozilla's XUL. It supports Python via XPCOM.</p>
<p>See this project: <a href="http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html" rel="noreferrer">pyxpcomext</a></p>
<p>XUL isn't compiled, it is packaged and loaded at runtime. Firefox and many other great applications use it, but most of them use Javascript for scripting instead of Python. There are one or 2 using Python though.</p>
|
<p>It's XML, not Python, but look at <a href="http://www.openlaszlo.org/" rel="nofollow noreferrer">Open Laszlo</a></p>
| 47,565
|
<p>I am developing an application using the ASP.NET MVC platform, which will be exposed as a service over the web (the <a href="http://en.wikipedia.org/wiki/Software_as_a_Service" rel="nofollow noreferrer">SaaS</a> model). I am trying to determine the best way to partition the URL namespace for each user account. The application will need to be accessed securely via SSL, so my main concerns have been around coming up with a URL design that works well with SSL certificates. Here are the options I have come up with. In each example <strong>bob</strong> and <strong>jane</strong> are two example user accounts:</p>
<h2>Option A: Each Account Has Unique Subdomain under Common Domain Name</h2>
<p>e.g.</p>
<pre><code>https://bob.example.com
https://jane.example.com
</code></pre>
<ul>
<li>This would require a wildcard SSL
certificate (e.g. mapped to
*.example.com) so each user can seamlessly access their account via
SSL. By seamless I mean without the
web browser warning the user about
SSL certificate problems. The only
drawback I can think of is that
wildcard certs seem to be
considerably more expensive than
normal fixed domain certs. The cost
difference will certainly be
negligible in grand scheme of
things, but it is something I am
keeping in mind if all else proves
to be equal.</li>
</ul>
<h2>Option B: Each Account has Unique Domain Name</h2>
<p>e.g.</p>
<pre><code>https://bobs-domain.com
https://domain-of-jane.com
</code></pre>
<ul>
<li><p>In this case, each user would have an SSL certificate tied
to their domain names. One big
drawback I can think of is that our
servers would have to maintain the
private keys for all the users'
certs, and we would have to design a
system that allowed users to
securely transmit their private keys
to our servers. Even if we had such
a system, I feel it would be too
much of a burden on users to have to
acquire a certificate then submit
the private keys to us.</p></li>
<li><p>Alternatively, we could
automatically issue and provision an
SSL certificate for each user when
they sign up, so they can start
accessing their app via SSL without
additional steps. This would
require that we become an issuer of
SSL certificates, which I haven't
looked into yet... likely we would
be a reseller for some other big
company like Verisign who
specializes in this sort of thing.</p></li>
<li><p>Despite the apparent pain of this
approach, this option does enable
some features that we may want to
provide in the future, i.e. allowing
user's to have their own branded
version of the app accessed via
their own company domain name.</p></li>
</ul>
<h2>Option C: Each Account has Unique Subdirectory under Common Domain Name</h2>
<p>e.g.</p>
<pre><code>https://example.com/bob
https://example.com/jane
</code></pre>
<ul>
<li><p>From the perspective of SSL
certificate maintenance, this is
probably the best option. We would
only need one fixed domain SSL cert
(e.g. example.com) which would be
used by all users.</p></li>
<li><p>Unfortunately this URL design does not work well
with other aspects of our current
application architecture, especially
around load balancing.</p></li>
</ul>
<h2>Need Feedback</h2>
<p>My question to you all is: what option would you choose, and why? I would especially love to hear real-world examples and experiences, but any other issues or concerns that I haven't already presented would be appreciated. </p>
|
<p>I would go with A. This solution is not very expensive, it scales well and it does not limit you to go with custom domains, if you decide this later on.</p>
<p>Wildcard certificates used to be quite expensive, but today you could get them around 200 USD annually at <a href="http://www.godaddy.com/gdshop/ssl/ssl.asp?ci=9039" rel="nofollow noreferrer" title="wildcard certificates by GoDaddy">GoDaddy</a> or <a href="http://www.rapidssl.com/ssl-certificate-products/rapidssl/usd/wildcard-ssl-certificate.htm" rel="nofollow noreferrer" title="wildcard certificates by RapidSSL">RapidSSL</a>, which I think is pretty cheap. These certificates works in (almost) any browser, but they doesn't come with the validation, VeriSign provides. I don't know whether you need this.</p>
<p>If you go with option B, you have to purchase a certificate per user, but with a wildcard certificate, the certificate will be paid after a few sign-ups and the rest will be pure revenue.</p>
<p>Aside from this the solution is really simple to implement, which also is a strength.</p>
|
<p>You're right Will, A and B are the same. However, I think that is true mainly from a coding perspective. With either option, the web server will determine the account based on the host name in the HTTP header. C is slightly different from a coding perspective because it would match the account based on the path under the domain name, and the ASP.NET MVC framework's URL routing capabilities would come in handy here.</p>
<p>From an administrative perspective each option is quite different. With option A we would have to manage the subdomains... which we can do because our DNS provider has an API to manage host records. With option B we would have to manage the private keys for all the different domain names, as I mentioned.</p>
<p>I'm guessing from the number of responses that this is not the best type of question to ask on this forum, probably because it is too open ended. I was just hoping that someone who has been there and done that would chime in, mainly so I know if I'm even on the right track, as I've never designed a system like this before.</p>
<p>Thanks</p>
| 37,587
|
<p>This probably has a simple answer, but I must not have had enough coffee to figure it out on my own:</p>
<p>If I had a comma delimited string such as:</p>
<pre><code>string list = "Fred,Sam,Mike,Sarah";
</code></pre>
<p>How would get each element and add quotes around it and stick it back in a string like this:</p>
<pre><code>string newList = "'Fred','Sam','Mike','Sarah'";
</code></pre>
<p>I'm assuming iterating over each one would be a start, but I got stumped after that.</p>
<p>One solution that is ugly:</p>
<pre><code>int number = 0;
string newList = "";
foreach (string item in list.Split(new char[] {','}))
{
if (number > 0)
{
newList = newList + "," + "'" + item + "'";
}
else
{
newList = "'" + item + "'";
}
number++;
}
</code></pre>
|
<pre><code>string s = "A,B,C";
string replaced = "'"+s.Replace(",", "','")+"'";
</code></pre>
<p>Thanks for the comments, I had missed the external quotes.</p>
<p>Of course.. if the source was an empty string, would you want the extra quotes around it or not ? And what if the input was a bunch of whitespaces... ? I mean, to give a 100% complete solution I'd probably ask for a list of unit tests but I hope my gut instinct answered your core question.</p>
<p><em>Update</em>: A LINQ-based alternative has also been suggested (with the added benefit of using String.Format and therefore not having to worry about leading/trailing quotes):</p>
<pre><code>string list = "Fred,Sam,Mike,Sarah";
string newList = string.Join(",", list.Split(',').Select(x => string.Format("'{0}'", x)).ToList());
</code></pre>
|
<p>The C# implementation of @<a href="https://stackoverflow.com/questions/254009/in-c-add-quotes-around-string-in-a-comma-delimited-list-of-strings#254026">PhiLho</a>'s JavaScript regular expression solution looks something like the following:</p>
<pre><code>Regex regex = new Regex(
@"\b",
RegexOptions.ECMAScript
| RegexOptions.Compiled
);
string list = "Fred,Sam,Mike,Sarah";
string newList = regex.Replace(list,"'");
</code></pre>
| 31,671
|
<p>For my small wiki application, I mostly need to have the textarea used to edit the contents to use soft (or virtual) wrapping. However, in some cases, not wrapping the content would be preferable. I thought I would do this by simply having a button to turn off wrapping. Here is the simplified code:</p>
<pre><code> <form name="wikiedit" action="[[script_name]]" method="post">
<textarea name="content" rows="25" cols="90" wrap="virtual">[[content]]</textarea>
<input type="button" onclick="document.wikiedit.content.wrap='off';" value="No Wrap"> &nbsp;
<input type="submit" value="Save">
</form>
</code></pre>
<p>It works with IE, but not with Firefox or Opera. How should I do this?</p>
|
<p>See bug 41464: <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=41464" rel="nofollow noreferrer">https://bugzilla.mozilla.org/show_bug.cgi?id=41464</a></p>
<p>Nasty workaround for now is to replace the textarea with a clone of itself:</p>
<pre><code>function setWrap(area, wrap) {
if (area.wrap) {
area.wrap= wrap;
} else { // wrap attribute not supported - try Mozilla workaround
area.setAttribute('wrap', wrap);
var newarea= area.cloneNode(true);
newarea.value= area.value;
area.parentNode.replaceChild(newarea, area);
}
}
</code></pre>
<p>Unrelated: try to avoid accessing elements straight out of the document object, it is unreliable on some browsers and causes name clash problems. ‘document.forms.wikiedit’ is better, and moving to ‘id’ on the form instead of ‘name’ and then using ‘document.getElementById('wikiedit')’ better still.</p>
<p>form.elements.content is also more reliable than form.content for similar reasons... or, indeed, you could give the textarea an ID and go straight to the textarea with getElementById without having to bother look at the form.</p>
|
<p>According to <a href="http://www.w3.org/TR/html4/interact/forms.html#edef-TEXTAREA" rel="nofollow noreferrer">the HTML 4.01 spec</a>, <code>wrap</code> isn't a valid attribute for <code><textarea></code>s which would explain why it's so difficult and strange. It looks as though Firefox actually does use the <code>wrap</code> attribute, but it won't let you change it.</p>
<p>I do have a solution though! It's pretty awful, but here it is. Completely replace the textarea with a new one.</p>
<pre><code>// this is the onclick handler for your button
document.getElementById("nowrapButton").onclick = function() {
var oldOne = this.form.content; // the old textarea
var newOne = document.createElement('textarea'); // the new textarea
var attrs = ['name', 'rows', 'cols']; // these are the attributes to keep
for (var i = 0; i < attrs.length; ++i) {
// copy the attributes to the new one
newOne.setAttribute(attrs[i], oldOne.getAttribute(attrs[i]));
}
// toggle the wrapping on and off
if (oldOne.getAttribute('wrap') != 'off') {
newOne.setAttribute('wrap', 'off');
}
// copy the text over
newOne.value = oldOne.value;
// add the new one
oldOne.parentNode.insertBefore(newOne, oldOne);
// get rid of the old one
oldOne.parentNode.removeChild(oldOne);
return false;
};
</code></pre>
<p>Here's a working version of this you can play with: <a href="http://jsbin.com/ugepa" rel="nofollow noreferrer">http://jsbin.com/ugepa</a></p>
<p>As usual, this'd be much nicer in jQuery. :)</p>
| 33,053
|
<p>OK, first let me state that I have never used this control and this is also my first attempt at using a web service.</p>
<p>My dilemma is as follows. I need to query a database to get back a certain column and use that for my autocomplete. Obviously I don't want the query to run every time a user types another word in the textbox, so my best guess is to run the query once then use that dataset, array, list or whatever to then filter for the autocomplete extender... </p>
<p>I am kinda lost any suggestions??</p>
|
<p>Why not keep track of the query executed by the user in a session variable, then use that to filter any further results?</p>
<p>The trick to preventing the database from overloading I think is really to just limit how frequently the auto updater is allowed to update, something like once per 2 seconds seems reasonable to me.</p>
<p>What I would do is this: Store the current list returned by the query for word A server side and tie that to a session variable. This should be basically the entire list I would think. Then, for each new word typed, so long as the original word A exists, you can filter the session info and spit the filtered results out without having to query again. So basically, only query again when word A changes.</p>
<p>I'm using "session" in a PHP sense, you may be using a different language with different terminology, but the concept should be the same.</p>
|
<p>While caching everything is certainly a good idea, your question about which data structure to use is an issue that wasn't fully answered here.
The best data structure for an autocomplete extender is a Trie.
You can find a good .NET article and code <a href="http://metalthought.blogspot.com/2009/05/enhanced-performance-for-aspnet-ajax.html" rel="nofollow noreferrer" title=".NET AutocompleteExtender Trie">here</a>.</p>
| 16,495
|
<p>What's the best way to output the public contents of an object to a human-readable file? I'm looking for a way to do this that would not require me to know of all the members of the class, but rather use the compiler to tell me what members exist, and what their names are. There have to be macros or something like that, right?</p>
<p>Contrived example: </p>
<pre><code>class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
int otherStuff;
};
Container myCollection;
</code></pre>
<p>I would like to be able to do something to see output along the lines of "myCollection: stuff = value, otherStuff = value".
But then if another member is added to Container, </p>
<pre><code>class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
string evenMoreStuff;
int otherStuff;
};
Container myCollection;</code></pre>
<p>This time, the output of this snapshot would be "myCollection: stuff = value, evenMoreStuff=value, otherStuff = value"</p>
<p>Is there a macro that would help me accomplish this? Is this even possible? (Also, I can't modify the Container class.)
Another note: I'm most interested about a potential macros in VS, but other solutions are welcome too.</p>
|
<p>Take a look at <a href="http://s11n.net" rel="nofollow noreferrer">this library</a> .</p>
|
<p>There's unfortunately no macro that can do this for you. What you're looking for is a reflective type library. These can vary from fairly simple to home-rolled monstrosities that have no place in a work environment.</p>
<p>There's no real simple way of doing this, and though you may be tempted to simply dump the memory at an address like so:</p>
<pre><code>char *buffer = new char[sizeof(Container)];
memcpy(buffer, containerInstance, sizeof(Container));
</code></pre>
<p>I'd really suggest against it unless all you have are simple types.</p>
<p>If you want something really simple but not complete, I'd suggest writing your own
<code>printOn(ostream &)</code> member method.</p>
| 35,667
|
<p>I am trying to create a simple page that enters data in to a database and my code is below.</p>
<pre><code><%@ LANGUAGE="VBSCRIPT" %>
<% Option Explicit %>
<!--#include FILE=dbcano.inc-->
<%
dim username,password,f_name,l_name,objConn,objs,query
username = Request.Form("user")
password = Request.Form("pass")
f_name = Request.Form("fname")
l_name = Request.Form("lname")
if((f_name <> null) or (f_name <> "")) then
response.redirect("patti_account.asp")
else
Set objConn = ConnectDB()
query = "INSERT INTO user (username,password,f_name,l_name) VALUES ('"& username &"','"& password &"','"& f_name &"','"& l_name &"')"
Set objs = objConn.Execute(query)
Response.Redirect ("thankyou.asp")
end if
%>
</code></pre>
<p>I am getting this error when I run my page:</p>
<blockquote>
<p>Microsoft OLE DB Provider for SQL
Server error '80040e14'</p>
<p>Incorrect syntax near the keyword
'user'.</p>
<p>create_account.asp, line 18</p>
</blockquote>
<p>I have checked everything, my field names exist and my table name is correct as well.</p>
<p>Any suggestions?</p>
|
<p><strong>User</strong> is a reserved word in SQL server. Put it into square brackets, e.g. <strong>[user]</strong>.</p>
|
<p>Try changing it to:</p>
<pre><code>query = "INSERT INTO [user] (username,password,f_name,l_name) VALUES ('"& username &"','"& password &"','"& f_name &"','"& l_name &"')"
</code></pre>
<p>(escape the table name since it is a reserved word)</p>
<p>Also, don't forget to validate keyboard input since this code is subject to SQL injection attacks.</p>
| 46,616
|
<p>Is anyone using Elmah to send exceptions via email? I've got Elmah logging set up via SQL Server, and can view the errors page via the Elmah.axd page, but I am unable to get the email component working. The idea here is to get the email notification so we can react more quickly to exceptions. Here is my web.config (unnecessary sectionss omitted), with all the sensitive data replaced by * * *. Even though I am specifying a server to connect to, does the SMTP service need to be running on the local machine?</p>
<pre><code><?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="elmah">
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/>
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/>
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings>
<add name="elmah-sql" connectionString="Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***" />
</connectionStrings>
<elmah>
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah-sql" >
</errorLog>
<errorMail from="test@test.com"
to="test@test.com"
subject="Application Exception"
async="false"
smtpPort="25"
smtpServer="***"
userName="***"
password="***">
</errorMail>
</elmah>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="CustomError.aspx">
<error statusCode="403" redirect="NotAuthorized.aspx" />
<!--<error statusCode="404" redirect="FileNotFound.htm" />-->
</customErrors>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
</httpModules>
</system.web>
</configuration>
</code></pre>
|
<p>You need the ErrorMail httpModule.</p>
<p>add this line inside the <httpModules> section</p>
<pre><code><add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
</code></pre>
<p>If you're using a remote SMTP server (which it looks like you are) you don't need SMTP on the server.</p>
|
<p>I have used Elmah myself in this configuration and I had to setup the server with SMTP locally. It is a straight-forward install on you local IIS server. This should do the trick.</p>
<p>Good point above, you need the errorMail module BUT if you are not using a remote SMTP server you need SMTP locally, just to clarify.</p>
| 5,464
|
<p>If I have a script tag like this:</p>
<pre><code><script
id = "myscript"
src = "http://www.example.com/script.js"
type = "text/javascript">
</script>
</code></pre>
<p>I would like to get the content of the "script.js" file. I'm thinking about something like <code>document.getElementById("myscript").text</code> but it doesn't work in this case.</p>
|
<p>Do you want to get the contents of the file <a href="http://www.example.com/script.js" rel="nofollow noreferrer">http://www.example.com/script.js</a>? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.</p>
|
<p>Not sure why you would need to do this?</p>
<p>Another way round would be to hold the script in a hidden element somewhere and use Eval to run it. You could then query the objects innerHtml property.</p>
| 17,886
|
<p>I have a interface that defines some methods with attributes. These attributes need to be accessed from the calling method, but the method I have does not pull the attributes from the interface. What am I missing?</p>
<pre><code>public class SomeClass: ISomeInterface
{
MyAttribute GetAttribute()
{
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
object[] attributes = methodBase.GetCustomAttributes(typeof(MyAttribute), true);
if (attributes.Count() == 0)
throw new Exception("could not find MyAttribute defined for " + methodBase.Name);
return attributes[0] as MyAttribute;
}
void DoSomething()
{
MyAttribute ma = GetAttribute();
string s = ma.SomeProperty;
}
}
</code></pre>
|
<p>The methodBase will be the method on the class, not the interface. You will need to look for the same method on the interface. In C# this is a little simpler (since it must be like-named), but you would need to consider things like explicit implementation. If you have VB code it will be trickier, since VB method "Foo" can implement an interface method "Bar". To do this, you would need to investigate the interface map:</p>
<pre><code>using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
interface IFoo
{
void AAA(); // just to push Bar to index 1
[Description("abc")]
void Bar();
}
class Foo : IFoo
{
public void AAA() { } // just to satisfy interface
static void Main()
{
IFoo foo = new Foo();
foo.Bar();
}
void IFoo.Bar()
{
GetAttribute();
}
void GetAttribute()
{ // simplified just to obtain the [Description]
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase classMethod = stackFrame.GetMethod();
InterfaceMapping map = GetType().GetInterfaceMap(typeof(IFoo));
int index = Array.IndexOf(map.TargetMethods, classMethod);
MethodBase iMethod = map.InterfaceMethods[index];
string desc = ((DescriptionAttribute)Attribute.GetCustomAttribute(iMethod, typeof(DescriptionAttribute))).Description;
}
}
</code></pre>
|
<p>While I will first confess that I have never tried to attach attributes to Interfaces but would something like the following work for you?</p>
<pre><code>public abstract class SomeBaseClass: ISomeInterface
{
[MyAttribute]
abstract void MyTestMethod();
}
public SomeClass : SomeBaseClass{
MyAttribute GetAttribute(){
Type t = GetType();
object[] attibutes = t.GetCustomAttributes(typeof(MyAttribute), false);
if (attributes.Count() == 0)
throw new Exception("could not find MyAttribute defined for " + methodBase.Name);
return attributes[0] as MyAttribute;
}
....
}
</code></pre>
| 31,371
|
<p>Is there a limitation in the length of a query that SQL Server can handle?</p>
<p>I have a normal SqlCommand object and pass a very long select statement as a string. </p>
<p>The query seems to be fine when running against an SQL Server 2005/2008 engine but doesn't execute against an SQL Server 2000 engine. </p>
<p>I don't have any error details as I only have this information 3rd hand but my application isn't working as expected. I could go to the trouble of installing an SQL Server 2000 instance but I was just wondering if anyone has a quick. Yes there is a 4K or 8K limit in SQL Server 2000 but not in 2005 type answer.</p>
<p>I'm aware that I could use stored procedures but lets assume I have a valid reason for not using them :-)</p>
|
<p>SqlServer 2000 has a 4000 character query limit for adhoc queries.</p>
<p>Can you abstract this into a stored procedure?</p>
|
<p>Do not to do this because of sql injections. Abandon this if the app's dynamic sql can be manipulated at all by the user.</p>
<p>also - consider SP's since its easier to maintain and it also helps with sql injection.</p>
| 43,574
|
<p>I am looking for a simple unpatented one-way encryption algorithm, preferably in c.
I would like to use it to validate passwords.</p>
|
<p><a href="http://en.wikipedia.org/wiki/SHA-1" rel="nofollow noreferrer">SHA-1 and the rest of its family</a> were patented by the US government which "has released the patent under a royalty free license". Many public-domain implementations <a href="http://www.google.ca/search?q=sha+c+implementation" rel="nofollow noreferrer">may be found through Google</a>. <code>:-)</code></p>
|
<p>MD5 has suited me fine so far.</p>
| 9,497
|
<p>I have a query that ran fine on SQL2005 but moving the database to SQL2008 gives me the error from the title.</p>
<p>The code that is the problem is a call to CONTAINS, CONTAINSTABLE or FREETEXT with an empty parameter. However I'm trying to only call or join when there is a value like such</p>
<pre><code>where (@search_term = '' or (FREETEXT(lst.search_text, @search_term)))
</code></pre>
<p>or</p>
<pre><code>left join containstable (listing_search_text, search_text, @search_term) ftb on l.listing_id = ftb.[key]
and len(@search_term) > 0
</code></pre>
<p>However I cannot find any workaround for this to work on SQL2008. Any ideas?</p>
<p>I know I can do dynamic SQL or have a if statement with two different cases (select with FT join, select without FT join. Any better workaround which doesn't require doing this?</p>
|
<p>I found the answer to this today when converting my own database from SQL 2005 to SQL 2008.</p>
<p>Pass <code>""</code> for your search term and change the @search_term = <code>''</code> test to be <code>@search_term = '""'</code>
SQL server will ignore the double quotes and not throw an error.</p>
<p>For example, the following would actually returns all records in the Users table:</p>
<pre><code>declare @SearchTerm nvarchar(250)
SET @SearchTerm = '""'
select UserId, U.Description, U.UserName
from dbo.Users U
WHERE ((@SearchTerm = '""') OR CONTAINS( (U.Description, U.UserName), @SearchTerm))
</code></pre>
<p>If you are using .Net, you might grab a copy of E. W. Bachtal's FullTextSearch class. His site is very informative: <a href="http://ewbi.blogs.com/develops/" rel="noreferrer">http://ewbi.blogs.com/develops/</a></p>
|
<p>I found that using "a" as the default works if SQL-Server is <a href="https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/transform-noise-words-server-configuration-option?view=sql-server-ver15" rel="nofollow noreferrer">configured to ignore "noise words".</a></p>
<pre><code>SET @SearchPhrase = coalesce(@SearchPhrase, 'a'); /* replace with 'a' if null parameter */
SELECT ... WHERE
(@SearchPhrase = 'a' OR contains(Search_Text, @SearchPhrase))
</code></pre>
| 23,019
|
<p>On a particular project we're working with a total of 10 team members. </p>
<p>After about a year working on the project (and using Mantis as a bug-/feature-tracker eversince), the bugtracker gets more and more difficult to use, as no standard has been setup that explains how to create new tasks, how to comment tasks etc. This leads to multiple entries for the same bugs, inability to easily find bugs when searching for them etc.</p>
<p>How do you organize your bugtracker? Do you use a lot of (sub)categories for different portions of your application (GUI, Backend etc), do you use tags in the title of tasks (i.e. "[GUI][OptionPage] The error")?</p>
<p>Is anyone in your team allowed to introduce new tasks or is this step channeled through a single "Mantis-master" (who would then know whether a new report is a duplicate or an entirely new entry)?</p>
|
<p>Always link a version control system commit to an issue and back so that you know which commits were made do solve which issue and why a certain commit was done.</p>
|
<p>What we did is to introduce a role for approve entries to the bug tracker. This role can be shared by different people. The process is either to approve, to approve with a small edit, or to reject the entry with the request for further editing or clarification.</p>
<p>It is better for the general understanding if the role is not given to people working in the (core) team.</p>
| 16,122
|
<p>I am using this code to verify a behavior of a method I am testing:</p>
<pre><code> _repository.Expect(f => f.FindAll(t => t.STATUS_CD == "A"))
.Returns(new List<JSOFile>())
.AtMostOnce()
.Verifiable();
</code></pre>
<p>_repository is defined as:</p>
<pre><code>private Mock<IRepository<JSOFile>> _repository;
</code></pre>
<p>When my test is run, I get this exception:</p>
<p><strong>Expression t => (t.STATUS_CD = "A") is not supported.</strong></p>
<p>Can someone please tell me how I can test this behavior if I can't pass an expression into the Expect method?</p>
<p>Thanks!!</p>
|
<p>This is a bit of a cheaty way. I do a .ToString() on the expressions and compare them. This means you have to write the lambda the same way in the class under test. If you wanted, you could do some parsing at this point</p>
<pre><code> [Test]
public void MoqTests()
{
var mockedRepo = new Mock<IRepository<Meeting>>();
mockedRepo.Setup(r => r.FindWhere(MatchLambda<Meeting>(m => m.ID == 500))).Returns(new List<Meeting>());
Assert.IsNull(mockedRepo.Object.FindWhere(m => m.ID == 400));
Assert.AreEqual(0, mockedRepo.Object.FindWhere(m => m.ID == 500).Count);
}
//I broke this out into a helper as its a bit ugly
Expression<Func<Meeting, bool>> MatchLambda<T>(Expression<Func<Meeting, bool>> exp)
{
return It.Is<Expression<Func<Meeting, bool>>>(e => e.ToString() == exp.ToString());
}
</code></pre>
|
<p>In Rhino Mocks you would do something like this...</p>
<p>Instead of using an Expect, use a Stub and Ignore the arguments. Then have --</p>
<pre><code>Func<JSOFile, bool> _myDelegate;
_repository.Stub(f => FindAll(null)).IgnoreArguments()
.Do( (Func<Func<JSOFile, bool>, IEnumerable<JSOFile>>) (del => { _myDelegate = del; return new List<JSOFile>();});
</code></pre>
<p><em>Call Real Code</em></p>
<p>*Setup a fake JSOFile object with STATUS_CD set to "A" *</p>
<pre><code>Assert.IsTrue(_myDelegate.Invoke(fakeJSO));
</code></pre>
| 36,714
|
<p>So I'm about to start of a small project for my sporting club for member registrations and I'm trying to decide between WebForms or MVC.</p>
<p>Allit will be is a user login and data capture forms (or and data retrieval), so I was initally thinking WebForms with FBA but I've wanted to have a play with MVC for a while and I was thinking that it wouldn't be too bad a choice.</p>
<p>But not really having a lot of knowledge of MVC I don't know if it'd be a wrong fit.</p>
<p>So what's a good way to decide if WebForms or MVC is the right choice?</p>
|
<p>Is this a critical, production level application or a small one-off? Can you deal with the extra time that the learning curve of MVC will take or do you need to have it done right-away? Can you afford to scrap the whole thing and start over if MVC doesn't work out? Are you willing to have the platform change (probably not much now that it's in beta) while you are developing? Is there another project that is less critical that you could use MVC on to learn it.</p>
<p>Depending on how you answer these questions, learning MVC on this project might be worth it. Personally, I think it is a better architecture, but a less mature technology at this point. It has certainly increased the testability of my web code. I expect to move all of my development in this direction over the next year or so, though I doubt if I will change gears in any of the projects that I have had under development for awhile. I've just started my first new project in MVC. I wasn't willing to commit to it until it went into beta and I think that it will be in production before I'm finished with the project.</p>
|
<p>Based on your comments to tvanfosson, it sounds like MVC would be a good choice for you as you listed your desire to learn as a reason to choose that technology. I doubt MVC will change <em>drastically</em> from its beta. So, this could be a good opportunity to learn a new tool. As for as WebForms being the "quick and nasty" solutions, I worry that is MVC propaganda.</p>
| 42,559
|
<p>I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:</p>
<pre><code>>>> foo = 'baz "\"'
>>> foo
'baz ""'
</code></pre>
<p>So instead of <code>baz "\"</code> like I want I'm getting <code>baz ""</code>. If I then try to escape the backslash, it doesn't help either:</p>
<pre><code>>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
</code></pre>
<p>Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?</p>
|
<p>You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)</p>
<pre><code>>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"
</code></pre>
<p>Incidentally, there's another string form which might be a bit clearer:</p>
<pre><code>>>> print(r'baz "\"')
baz "\"
</code></pre>
|
<p>Another way to end a string with a backslash is to end the string with a backslash followed by a space, and then call the <code>.strip()</code> function on the string. </p>
<p>I was trying to concatenate two string variables and have them separated by a backslash, so i used the following:</p>
<pre><code>newString = string1 + "\ ".strip() + string2
</code></pre>
| 38,606
|
<p>We have a PageRoles xml file which contains the page path and the user role that can access that page.</p>
<p>We are maintaining a Dictionary in a static class, which gets loaded int static constructor for the class.
The class has a method CheckIfRoleAllowed that takes in a page path and returns a bool.</p>
<p>Each page call the CheckIfRoleAllowed on Page Init.</p>
<pre><code>static class PageAccessChecker
{
static Dictionary<string, UserRoleType[]> _PageAccessPermissions;
static FileSystemWatcher _XmlWatcher;
static PageAccessChecker()
{
// Load page access permissions from xml
// Set FileSystemWatcher watcher to watch for changes
}
public static CheckIfRoleAllowed(string pagePath)
{
}
}
</code></pre>
<p>Would we be better off doing this using the singleton pattern?
If yes, why?</p>
<p>Kind regards.</p>
|
<p>You do use a singleton. Simply, there are 2 usual implementations for singletons, the other being instantiating the class and having a static member referencing this instance.</p>
<p>Your implementation makes calls simpler IMO :</p>
<pre><code>PageAccessChecker.CheckIfRoleAllowed(path);
</code></pre>
<p>instead of:</p>
<pre><code>PageAccessChecker._default.CheckIfRoleAllowed(path);
</code></pre>
|
<p>If you keep the class constructor private, there's no real difference - they are both global variables that can be lazily initialized.</p>
<p>If you keep the class constructor public or protected and only use the pattern to create a global (not to enforce a single instance), you can at least test your singleton class.</p>
<p>But what you should really try is to avoid singletons and use dependency injection instead. See <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/" rel="nofollow noreferrer">Singletons are Pathological Liars</a> by Miško Hevery.</p>
| 43,192
|
<p>Please give me some insight on how to get the best start on applying Aspect Oriented Programming to my C#.net applications?</p>
|
<p>PostSharp has the added advantage that it does it's AOP by doing IL weaving. In fact it adds code to the Il when/or just after compiling. Which makes the builds slower but it should be faster at runtime.</p>
<p>Some other do this at runtime (the castle project and I think it's windsor in there that does the AOP) which is slower at runtime but faster to build.</p>
|
<p>I recommend trying <a href="http://www.springframework.net/" rel="nofollow noreferrer">Spring.NET</a>. It lets you create "Interceptor" classes that can be wrapped around calls into business objects simply by adding entries into the application's config file.</p>
<p>We've used it to do connection/transaction handling, error logging and authentication. Which keeps all of those "aspects" out of the business logic code.</p>
| 31,039
|
<p>I've got a direct drive extruder printer, that I have equipped with a Bowden-tube to give it a nice and defined filament path from my spool and to protect it from moisture when it exits my drybox. I've noticed that this 1 m Bowden tube adds quite a bit of friction to the system. I am keenly aware of it as feeding filament form the drybox into the tube by hand is quite a chore already, especially with high friction materials like PETG. Also I notice that I can sustain only lower volumetric flow without skipping or underextrusion after adding the tube.</p>
<p>So I figured, why not have a motor on both sides of the bowden tube? A big and heavy one at the entrance, providing a baseline pressure on the filament. And a comparatively light one on the other end, adding that fine control you want for your retraction, rather than trying to implement that via a 1 m wet noodle full of static friction.</p>
<p>Seems like it would give you the best of both worlds. Not quite as light as a full Bowden system, but you could have all the control of a direct drive system, with much less of the weight/flow rate tradeoff.</p>
<p>Anyone aware of this being done before? Or any good arguments as to why it is a stupid idea? Seems like a fairly straightforward mod; in the simplest implementation, just add an additional extruder of the same spec on the other side of your Bowden tube, and split the control signal to be the same amongst both motors.</p>
|
<p>A Bowden tube is by design fairly small diameter to match the filament within, constraining the forces applied by the remote extruder mechanism. As you've noted, friction is a consideration.</p>
<p>For your application, you would not have to have such a tightly constrained diameter. You could use a Bowden tube for 2.85 mm filament, if your direct drive extruder is made for 1.75 mm filament.</p>
<p>You'd have the environmental control of the smaller tube, the path control and all of the other benefits, but none (or little) of the friction.</p>
<p>Additionally, you would not have the complexity of managing retraction or synchronizing feed that a dual motor system presents.</p>
|
<p>I have a similar setup with one of my printers (that is using 1.75 mm filament), this answer is therefore my own experience with guiding tubes from spool to extruder (my previous was a direct drive extruder, the latter uses a Bowden setup, but both with a tube leading up to the extruder).</p>
<p>Initially I used smaller diameter tubing (inner diameter of 2 and 3 mm, that is commonly used for Bowden setups for respectively for 1.75 mm and 2.85 mm filament), but when I changed to 4 mm inner diameter (and 6 mm outer diameter) all friction was gone. The benefit of using 4 mm inner diameter is that it fits over the 2/4 mm ID/OD tubes, and as such I slide the larger inner diameter tube over a piece of 4 mm outer diameter, forme, this also simplifies feeding the filament to the extruder.</p>
| 1,741
|
<p>I'd like to play mp3 files (b/c they compress smaller than .wav's) from a vb6 app but without needing any other player installed.</p>
<p>Any suggestions?</p>
|
<p>The easiest way to play an MP3 in VB6 is using the MCI in windowsmultimedia (winmm) functions. These are available in all versions of windows that can play MP3s in windows media player (by default in 2000, XP and I believe 98, needed to install Windows media player for NT4 and 95). Add the following to your header:</p>
<pre><code>Declare Function mciSendString Lib "winmm" Alias "mciSendStringA" (ByVal _
lpstrCommand As String, ByVal lpstrReturnString As String, _
ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long
</code></pre>
<p>Then add the following in your subroutine:</p>
<pre><code>CommandString = "open """ & FileName & """ type mpegvideo alias " & FileName
RetVal = mciSendString(CommandString, vbNullString, 0, 0)
</code></pre>
<p>The file type should mpegvideo not wavfile or sequencer, I guess because it uses the mpegvideo codec to play the file back. Legal questions relating to use of the MP3 codec and whether or not you are using windows to play it back or not is left up to your legal department if you plan to distribute your application. </p>
|
<p>Add reference to ActiveMovie control type library and use <a href="http://msdn.microsoft.com/en-us/library/ms787569(VS.85).aspx" rel="nofollow noreferrer">FilgraphManager.RenderFile</a>. Take a look at <a href="http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=37779&lngWId=1" rel="nofollow noreferrer">VbAmp Player</a>'s docPlayer.pvLoadMediaFile for sample and check out the usage of IBasicAudio thoughout the source -- volume control, etc.</p>
| 49,837
|
<p>I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure?</p>
<pre><code>CREATE PROCEDURE getOrder (@orderId as numeric) AS
BEGIN
select order_address, order_number from order_table where order_id = @orderId
select item, number_of_items, cost from order_line where order_id = @orderId
END
</code></pre>
<p>I need to be able to iterate through both result sets individually.</p>
<p>EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option.</p>
<p>The result sets returned by the procedures are not the same data types or number of columns.</p>
|
<p>The short answer is: you can't do it.</p>
<p>From T-SQL there is no way to access multiple results of a nested stored procedure call, without changing the stored procedure as others have suggested.</p>
<p>To be complete, if the procedure were returning a single result, you could insert it into a temp table or table variable with the following syntax:</p>
<pre><code>INSERT INTO #Table (...columns...)
EXEC MySproc ...parameters...
</code></pre>
<p>You can use the same syntax for a procedure that returns multiple results, but it will only process the first result, the rest will be discarded.</p>
|
<p>You could select them into temp tables or write table valued functions to return result sets. Are asking how to iterate through the result sets?</p>
| 8,341
|
<p>Let's say I checked in a changelist (in Perforce) with lots of files and I'd like to revert the entire changelist. Is there an easy way to "revert" the entire changelist in one fell swoop?</p>
<p>Currently I do something like this for each file in the changelist:</p>
<ul>
<li>p4 sync //path/to/file#n (where "n" is the previous version of the file)</li>
<li>cp file file#n</li>
<li>p4 sync //path/to/file</li>
<li>p4 edit //path/to/file</li>
<li>cp file#n file</li>
<li>rm file#n</li>
</ul>
<p>As you can imagine, this is quite cumbersome for a large changelist.</p>
|
<p>The posted answers provide correct answers, but note also that there is an actual menu option in P4V to do this for you now. It's in the latest 2008.2 Beta, and so should be officially released the the next week or three.</p>
<p>This <a href="http://www.perforce.com/perforce/downloads/beta/index.html" rel="noreferrer">link</a> gives details. </p>
<p>It should be a lot simpler to use than the earlier answers, but I've not had the opportunity to try it myself yet.</p>
<p><strong>Update</strong> This has now been fully released. See <a href="http://www.perforce.com/perforce/downloads/index.html" rel="noreferrer">Perforce downloads</a>.</p>
|
<p>I have the same problem when I want to delete an entire changelist. so I use the following script (notice that it also deletes the changelist's shelve and the changelist itself. if you only want to revert, copy the relevant lines).
Also, make sure the sed applies to your version of p4.</p>
<pre><code>#!/bin/bash
set -e
if [[ $# -ne 1 ]]; then
echo "usage: $(basename $0) changelist"
exit 1
fi
CHANGELIST=$1
#make sure changelist exist.
p4 describe -s $CHANGELIST > /dev/null # set -e will exit automatically if fails
p4 shelve -d -c $CHANGELIST 2> /dev/null || true # changelist can be shelveless
files_to_revert=$(p4 opened 2> /dev/null | grep "change $CHANGELIST" | sed "s/#.*//g")
if [[ -n "$files_to_revert" ]]; then
p4 revert $files_to_revert
fi
p4 change -d $CHANGELIST
</code></pre>
| 42,985
|
<p>I have 2 databases, and <strong>I want to transport an existing table containing a CHAR column from database A to database B.</strong></p>
<p>Database A is Oracle 9i, has encoding WE8ISO8859P1, and contains a table "foo" with at least 1 column of type CHAR(1 char). I can not change the table on database A because it is part of a third party setup.</p>
<p>Database B is my own Oracle 10g database, using encoding AL32UTF8 for all kinds of reasons, and I want to copy foo into this database.</p>
<p>I setup a database link from database B to database A. Then I issue the following command:</p>
<p>*create table bar as select * from #link#.foo;*</p>
<p>The data gets copied over nicely, but when I check the types of the columns, I notice that CHAR(1 char) has been converted into CHAR(3 char), and when querying the data in database B, it is all padded with spaces.</p>
<p>I think somewhere underwater, Oracle confuses it's own bytes and chars. CHAR(1 byte) is different from CHAR(1 char) etc. I've read about all that.</p>
<p><strong>Why does the datatype change into a padded CHAR(3 char) and how do I stop Oracle from doing this?</strong></p>
<p><em>Edit: It seems to have to do with transfering CHAR's between two specific patchlevels of Oracle 9 and 10. It looks like it is really a bug. as soon as I find out I'll post an update. Meanwhile: don't try to move CHAR's between databases like I described. VARCHAR2 works fine (tested).</em></p>
<p><em>Edit 2: <strong>I found the answer and posted it here:</strong> <a href="https://stackoverflow.com/questions/253971/why-does-char1-change-to-char3-when-copying-over-an-oracle-dblink#263467">Why does Char(1) change to Char(3) when copying over an Oracle DBLINK?</a>
Too bad I can not accept my own answer, because my problem is solved.</em></p>
|
<p>This problem is caused by the way Oracle (mis)handles character conversions between different character sets based on the original column length definition. When you define the size of a character type column in bytes, Oracle does not know how to do a conversion and bodges it. <strong>The solution is to always define the length of a character type in characters</strong>.</p>
<p>For a more in-depth explanation of the problem and how I figured this out have a look at
<a href="http://www.rolfje.com/2008/11/04/transporting-oracle-chars-over-a-dblink/" rel="nofollow noreferrer">http://www.rolfje.com/2008/11/04/transporting-oracle-chars-over-a-dblink/</a></p>
|
<p>The first thing I would try is Creating the table NOT as a CTAS but with a list of column definitions and try to perform an insert of the first few thousand rows. If that didn't succeed then it would be very clear why... and you'd have quick confirmation that Thomas Low is dead on accurate.</p>
| 31,665
|
<p>Java and C# support the notion of classes that can't be used as base classes with the <code>final</code> and <code>sealed</code> keywords. In C++ however there is no good way to prevent a class from being derived from which leaves the class's author with a dilemma, should every class have a virtual destructor or not?</p>
<hr>
<p><strong>Edit:</strong> Since C++11 this is no longer true, you can specify that a class is <a href="http://en.cppreference.com/w/cpp/language/final" rel="noreferrer"><code>final</code></a>.</p>
<hr>
<p>On the one hand giving an object a virtual destructor means it will have a <code>vtable</code> and therefore consume 4 (or 8 on 64 bit machines) additional bytes per-object for the <code>vptr</code>.</p>
<p>On the other hand if someone later derives from this class and deletes a derived class via a pointer to the base class the program will be ill-defined (due to the absence of a virtual destructor), and frankly optimizing for a pointer per object is ridiculous. </p>
<p>On the <a href="http://en.wikipedia.org/wiki/Gripping_hand" rel="noreferrer">gripping hand </a> having a virtual destructor (arguably) advertises that this type is meant to be used polymorphically.</p>
<p>Some people think you need an explicit reason to not use a virtual destructor (as is the subtext of <a href="https://stackoverflow.com/questions/300986">this question</a>) and others say that you should use them only when you have reason to believe that your class is to be derived from, what do <em>you</em> think?</p>
|
<p>Every abstract class should either have a,</p>
<ul>
<li>protected destructor, or,</li>
<li>virtual destructor.</li>
</ul>
<p>If you've got a public non-virtual destructor, that's no good, since it allows users to delete through that pointer a derived object. Since as we all know, that's undefined behavior. </p>
<p>For an abstract class, you already need a virtual-table pointer in the object, so making the destructor <code>virtual</code> doesn't (as far as I'm aware) have a high cost in terms of space or runtime performance. And it has the benefit that derived classes automatically have their destructors <code>virtual</code> (see @Aconcagua's comment). Of course, you can also make the destructor <code>protected virtual</code> for this case.</p>
<p>For a non-abstract class not intended to be deleted through a pointer to it, I don't think there's good reason to have a virtual destructor. It would waste resources, but more importantly it would give users a wrong hint. Just think about what weird sense it would make to give <code>std::iterator</code> a virtual destructor.</p>
|
<p>I'll add that there have been times when I have scratched my head for a while on destructors not getting called when I forgot a virtual in the parent or child class. I guess I know to look for that now though. :)</p>
<p>Someone might argue that there are times the parent class does something in its destructor that a child should not do... but that's probably an indicator of something wrong with your inheritance structure anyway.</p>
| 46,091
|
<p>Applications like CCTray allow one to specify a sound clip to indicate that a build is successful or that a build failed. I'm interested to hear what set of sounds different teams are using.</p>
<p>Here are two sets that we use:</p>
<ul>
<li>Homer Simpson: "d'oh" for a build failure, "woohoo!" for success</li>
<li>Mario bros: power down sound for a build failure, power up for a build success, 1-up for a build fixed</li>
</ul>
|
<p>South Park:</p>
<ul>
<li>"Oh my God, they've killed Kenny!" for a build failure.</li>
<li>"Kickass!" (Cartman) for a success.</li>
</ul>
|
<p>In earlier versions of the Microsoft C/C++ compilers, I've used sounds from the pinball game that came with Windows XP and the Windows 95 Plus! pack. I used sounds that the game used for successful actions for successful build events; and I used sounds that the game used for failure events (like losing the ball) I used for build failure or warning events. I also used pinball sounds for events like hitting a breakpoint in the debugger. Sadly, the latest versions of MS Visual Studio don't expose nearly as many events to the Sounds control panel anymore. :-(</p>
| 41,443
|
<p>If you launch Emacs using the <code>-nw</code> flag to force a console session (rather than an X session if you have X windows running), how do you get to the menu?</p>
<p>There are some items held in the menus that are infrequently-enough used on my part that I don't recall the escape or control sequence to do them.</p>
|
<p><code>M-x menu-bar-open</code>, which is usually bound to <code>F10</code>. This works with and without <code>menu-bar-mode</code> (which just shows the names of the menus at the top of the screen).</p>
|
<pre><code>M-x menu-bar-mode
</code></pre>
| 23,230
|
<p>I'm using C# and connecting to a WebService via an auto-generated C# proxy object. The method I'm calling can be long running, and sometimes times out. I get different errors back, sometimes I get a <code>System.Net.WebException</code> or a <code>System.Web.Services.Protocols.SoapException</code>. These exceptions have properties I can interrogate to find the specific type of error from which I can display a human-friendly version of to the user.</p>
<p>But sometimes I just get an <code>InvalidOperationException</code>, and it has the following Message. Is there any way I can interpret what this is without digging through the string for things I recognize, that feels very dirty, and isn't internationalization agnostic, the error message might come back in a different language.</p>
<pre><code>Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.
The request failed with the error message:
--
<html>
<head>
<title>Request timed out.</title>
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Lucida Console";font-size: .9em}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/PerformanceManager' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Request timed out.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
<br><br>
<b> Exception Details: </b>System.Web.HttpException: Request timed out.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[HttpException (0x80004005): Request timed out.]
</pre></code>
</td>
</tr>
</table>
<br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.312; ASP.NET Version:2.0.50727.833
</font>
</body>
</html>
<!--
[HttpException]: Request timed out.
-->
--.
</code></pre>
<p>Edit:
I have a try-catch around the method on the web-server. I have debugged it, and the web-server method returns (after a minute or so) without any exception. I also added an unhandled exception handler in the web service and a breakpoint there wasn't hit. As soon as the web-service returns, I get this error in the client instead of the result I expected.</p>
|
<p>This is happening because there is an unhandled exception in your Web service, and the .NET runtime is spitting out its HTML yellow screen of death server error/exception dump page, instead of XML.</p>
<p>Since the consumer of your Web service was expecting a text/xml header and instead got text/html, it throws that error.</p>
<p>You should address the cause of your timeouts (perhaps a lengthy SQL query?).</p>
<p>Also, checkout <a href="http://blog.codinghorror.com/throwing-better-soap-exceptions/" rel="noreferrer">this blog post</a> on Jeff Atwood's blog that explains implementing a global unhandled exception handler and using SOAP exceptions.</p>
|
<p>The problem I had was related to SOAP version. The <code>asmx</code> service was configured to accept both versions, 1.1 and 1.2, so, I think that when you are consuming the service, the client or the server doesn't know what version resolve.</p>
<p>To fix that, is necessary add:</p>
<pre><code>using (wsWebService yourService = new wsWebService())
{
yourService.Url = "https://myUrlService.com/wsWebService.asmx?op=someOption";
yourService.UseDefaultCredentials = true; // this line depends on your authentication type
yourService.SoapVersion = SoapProtocolVersion.Soap11; // asign the version of SOAP
var result = yourService.SomeMethod("Parameter");
}
</code></pre>
<p>Where <code>wsWebService</code> is the name of the class generated as a reference.</p>
| 14,062
|
<p>Which MVC-framework is the best option (performance/ease of development) for a web application, that will have + 2 million visits per week.</p>
<p>Basically the site is a search engine,but also there will be large amounts of XML parsing, and high db traffic.</p>
<p>We are using Java, over Jboss 4.2.3x, with PG as DB, and Solr for the searches.</p>
<p>We were thinking on code JSPs with taglibs, and Servlets, but we were feeling like there would be a better alternative, which don't know yet, as we are starting on the Java Web applications world.</p>
<p>Any opinions, and shares of your experience will be appreciated!<br>
Thanks in advance!</p>
|
<p>Give all of your <code>#fade</code>X elements a class (say .faders) and then use:</p>
<pre><code>$('.faders').stop();
</code></pre>
<p>Or give the container div an id like <code>#faderbox</code> and say:</p>
<pre><code>$('#faderbox div').stop();
</code></pre>
|
<p>I'm not sure exactly what you want to happen with regards to your fadeIn and fadeOut effects in your fadeEngine, however, I can give you two pieces of advice:</p>
<p>You can use the jQuery effect <code>stop()</code> to stop all current jQuery animations on selected elements. For example:</p>
<pre><code>$("#fade"+y).stop();
</code></pre>
<p>Will stop the fading animation for that element in its current state. You can then reset the CSS if you wish.</p>
<p>To stop a function from being called that you previously queued with <code>setTimeout</code>, you must obtain the return value and call <code>clearTimeout()</code>. For example:</p>
<pre><code>var timeout = setTimeout('fadeEngine('+y+')',3000);
// later...
clearTimeout(timeout);
</code></pre>
<p>This will clear the pending timeout event and prevent it from occurring.</p>
| 49,455
|
<p>Not sure if this is possible or if I'm expressing correctly what I'm looking for, but I have the following piece of code in my library repeatedly and would like to practice some DRY.
I have set of SQL Server tables that I'm querying based on a simple user-supplied search field ala Google. I'm using LINQ to compose the final query based on what's in the search string. I'm looking for a way to use generics and passed in lambda functions to create a reusable routine out of this: </p>
<pre><code>string[] arrayOfQueryTerms = getsTheArray();
var somequery = from q in dataContext.MyTable
select q;
if (arrayOfQueryTerms.Length == 1)
{
somequery = somequery.Where<MyTableEntity>(
e => e.FieldName.StartsWith(arrayOfQueryTerms[0]));
}
else
{
foreach(string queryTerm in arrayOfQueryTerms)
{
if (!String.IsNullOrEmpty(queryTerm))
{
somequery = somequery
.Where<MyTableEntity>(
e => e.FieldName.Contains(queryTerm));
}
}
}
</code></pre>
<p>I was hoping to create a generic method with signature that looks something like:</p>
<pre><code>private IQueryable<T> getQuery(
T MyTableEntity, string[] arrayOfQueryTerms, Func<T, bool> predicate)
</code></pre>
<p>I'm using the same search strategy across all my tables, so the only thing that really differs from usage to usage is the MyTable & MyTableEntity searched and the FieldName searched. Does this make sense? Is there a way with LINQ to dynamically pass in the name of the field to query in the where clause? Or can I pass in this as a predicate lambda?</p>
<pre><code>e => e.FieldName.Contains(queryTerm)
</code></pre>
<p>I realize there a million and a half ways to do this in SQL, probably easier, but I'd love to keep everything in the LINQ family for this one. Also, I feel that generics should be handy for a problem like this. Any ideas?</p>
|
<p>It sounds like you're looking for Dynamic Linq. Take a look <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="noreferrer">here</a>. This allows you to pass strings as arguments to the query methods, like:</p>
<pre><code>var query = dataSource.Where("CategoryID == 2 && UnitPrice > 3")
.OrderBy("SupplierID");
</code></pre>
<p>Edit: Another set of posts on this subject, using C# 4's Dynamic support: <a href="http://weblogs.asp.net/davidfowler/archive/2010/08/04/dynamic-linq-a-little-more-dynamic.aspx" rel="noreferrer">Part 1</a> and <a href="http://weblogs.asp.net/davidfowler/archive/2010/08/19/dynamic-linq-part-2-evolution.aspx" rel="noreferrer">Part 2</a>.</p>
|
<p>I recently had to do this same thing. You will need <a href="http://talesfromthebleedingedge.blogspot.com/2008/10/linq-to-entities-dynamic-linq-to.html" rel="nofollow noreferrer">Dynamic Linq</a> <a href="http://talesfromthebleedingedge.blogspot.com/2008/10/linq-to-entities-dynamic-linq-to.html" rel="nofollow noreferrer">here</a> is a way to keep this strongly typed. </p>
| 15,243
|
<p>I am working on a Sharepoint Server 2007 State machine Workflow. Until now I have a few states and a custom Association/InitiationForm which I created with InfoPath 2007. In Addition I have a few modification forms. I have a Problem with the removing of the modification link in the state-page of my workflow. </p>
<p>I have a state and in the initialize block of this state my EnableWorkflowModification Activity appears. So at the beginning of the state the modification is active. In the same state I have an OnWorkflowModification activity, which catches the event raised by the EnableWorkflowModification activity. After this state my modification is over and the link should disappear in the state-page. But this is not the case.
Both activities have the same correlation token (modification) and the same owner (the owning state).
Has anybody an idea why the link is not removed and how to remove the modification link?</p>
<p>Thank you in advance, Stefan!</p>
|
<p>You can automate the process of closing all the files prior to closing a solution by adding a handler for the BeforeClosing event of EnvDTE.SolutionEvents -- this will get invoked when VS is exiting.</p>
<p>In VS2005, adding the following to the EnvironmentEvents macro module will close all open documents:</p>
<pre>
Private Sub SolutionEvents_BeforeClosing() Handles SolutionEvents.BeforeClosing
DTE.ExecuteCommand("Window.CloseAllDocuments")
End Sub
</pre>
<p>Visual Studio 2008 appears to support the same events so I'm sure this would work there too.</p>
<p>I'm sure you could also delete the .suo file for your project in the handler if you wanted, but you'd probably want the AfterClosing event.</p>
|
<p>I dont think there is an option for this (or I couldnt find one) but you could probably write a macro to do this for you on project open. </p>
<p>This link has some code to close open files which you could adapt:
<a href="http://blogs.msdn.com/djpark/" rel="nofollow noreferrer">http://blogs.msdn.com/djpark/</a></p>
<p>I couldnt find the answer to this particular question but a good link for ide tips and tricks is:
<a href="http://blogs.msdn.com/saraford/default.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/saraford/default.aspx</a></p>
| 17,851
|
<p>Is there a library/software which can accept a number of keypoints and matches of them between images and produce a morph? Or any ideas/algorithms on how to do it?</p>
|
<p><a href="http://xmorph.sourceforge.net/" rel="nofollow noreferrer">Xmorph and GTK morph</a> can do that -- although the key points must be parts of equivalent rectangle grids. The underlying algorithm can be accessed through a C API.</p>
|
<p>An older piece of software by <a href="http://en.wikipedia.org/wiki/Gryphon_Software_Morph" rel="nofollow noreferrer">Gryphon Software</a> could do image morphing. I saw an article about it from 1994. I couldn't find a company site, so they may be abandon ware now.</p>
<p>Her is a quote from a Wikipedia article about a film editing <a href="http://en.wikipedia.org/wiki/Dissolve_(film)" rel="nofollow noreferrer">technique called Dissolve</a>.</p>
<blockquote>
<p>In non-linear video editing, a dissolve is done in software, by interpolating gradually between the RGB values of each pixel of the image.</p>
</blockquote>
<p>Hope that helps.</p>
| 19,892
|
<p>The LCD resin printers I've looked at have pretty standard resolutions like for a smartphone and I understand they use the same technology. However, color LCD screens have three RGB sub-pixels for each color pixel. Check for example this magnified picture of an S-IPS LCD screen:
<a href="https://i.stack.imgur.com/bml7t.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bml7t.jpg" alt="enter image description here"></a>
It seems like they could just omit the color filter and have three grayscale pixels for each color pixel.</p>
<p>3D printing just uses one color - UV. So why don't they have resolutions that are multiples of three of the usual resolutions?</p>
<p>All results about sub-pixels that I could find are about anti-aliasing, which is different (using the existing pixels better vs. having more pixels).</p>
|
<p>If what Thomas Sanladerer states is correct, the Mars 2 Pro (monochrome LCD, no color filter) has a layer time approximately 1/3 as long as the Mars/Pro printers (where color LCDs are used):</p>
<p><div class="youtube-embed"><div>
<iframe width="640px" height="395px" src="https://www.youtube.com/embed/0yZ4KiK_pl0?start=0"></iframe>
</div></div></p>
<p>This would indicate that the light passing through the LCD, when the color filter is present, is 1/3. Put it in other words, only ONE subpixel is capable of transmitting UV light.</p>
<p>Consequently, using all of them would not improve resolution because the other subpixels are always opaque.</p>
|
<p>It should be as simple as using a monochrome LCD. You don't actually want any color filters to interfere with the UV light.</p>
<p>Do we know that LCD printers are not using monochrome LCD panels? It always seemed so obvious that I assumed it was the practice. All you need are the front and back polarizer layer and the LCD itself to rotate the light.</p>
| 1,420
|
<p>Is there a secure way of logging into a Gmail account on a web browser, from an external Java program? I know the following works, but is there a safer alternative?</p>
<pre><code>Desktop.getDesktop().browse(new URI(
"https://www.google.com/accounts/ServiceLoginAuth?continue=http://mail.google.com/gmail" +
"&service=mail&Email=LOGIN&Passwd=PASSWORD&null=Sign+in"));
</code></pre>
<p><strong>Clarification</strong>: The external Java program is <a href="http://gmailassistant.sourceforge.net/" rel="nofollow noreferrer">GmailAssistant</a>, a Gmail notifier that already uses the IMAP capabilities of JavaMail. I just need a way of allowing the user to access the account directly in a web browser.</p>
|
<p>Depending of how much you want to integrate, you can check Google single sign-on (SSO) api. I'm studing how to use it and the best way to integrate it</p>
<p><a href="http://code.google.com/apis/apps/sso/saml_reference_implementation.html" rel="nofollow noreferrer">http://code.google.com/apis/apps/sso/saml_reference_implementation.html</a></p>
<p>Victor</p>
<p>UPDATED:</p>
<p>As a better option, you should check this link as well <a href="http://esoeproject.org/" rel="nofollow noreferrer">http://esoeproject.org/</a></p>
|
<p>I used google's IMAP access with the JavaMail API, and it was very simple.</p>
| 13,725
|
<p>How do I create an rss feed in ASP.Net? Is there anything built in to support it? If not, what third-party tools are available?</p>
<p>I'm thinking webforms, not MVC, though I suppose since this isn't a traditional page the difference may be minimal.</p>
|
<p>For built-in, there's nothing stopping you from using XmlDocument or XDocument (3.5) to build up the required XML for RSS. It's more work than it's worth though.</p>
<p>I use the <a href="http://www.codeplex.com/Argotic" rel="nofollow noreferrer">Argotic Syndication Framework</a> and serve the feeds through Generic Handlers (.ashx) with the content type set to text/xml.</p>
<p>The <a href="http://www.codeplex.com/ASPNETRSSToolkit" rel="nofollow noreferrer">RSSToolkit</a> is also nice. It comes with an RSSDataSource control if you're into that sort of thing. It also includes a control that will automatically insert the meta tag required for feed autodiscovery in browsers. I found the build provider for creating feeds to be a little kludgey however.</p>
|
<p>Create an HTTP Handler to create a RSS feed</p>
| 8,149
|
<p>Has anyone been able to implement the JQuery grid plugin, jqGrid? I'm trying to implement the JSON paging, and I feel like I'm getting close, but that I am also being swamped by inconsequential details. If anyone could post some sample code, I would greatly appreciate it.</p>
|
<p>Found your post while I was trying to do this for my project. I got it working. For anyone who needs it in the future, jqGrid won't work out of the box with JSON and ASP.NET. You need to make a couple of small modifications to grid.base.js. Around line 829, replace the json case section with the following:</p>
<pre><code>case "json":
gdata = JSON.stringify(gdata); //ASP.NET expects JSON as a string
$.ajax({ url: ts.p.url,
type: ts.p.mtype,
dataType: "json",
contentType: "application/json; charset=utf-8", //required by ASP.NET
data: gdata,
complete: function(JSON, st) { if (st == "success") { addJSONData(cleanUp(JSON.responseText), ts.grid.bDiv); if (loadComplete) { loadComplete(); } } },
error: function(xhr, st, err) { if (loadError) { loadError(xhr, st, err); } endReq(); },
beforeSend: function(xhr) { if (loadBeforeSend) { loadBeforeSend(xhr); } } });
if (ts.p.loadonce || ts.p.treeGrid) { ts.p.datatype = "local"; }
break;
</code></pre>
<p>Then add the following function:</p>
<pre><code>function cleanUp(responseText) {
var myObject = JSON.parse(responseText); //more secure than eval
return myObject.d; //ASP.NET special
}
</code></pre>
<p>You will also need to include the <a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js" rel="nofollow noreferrer">JSON parser and stringifier</a>. Along with working with ASP.NET, this revised code is also <a href="http://www.json.org/js.html" rel="nofollow noreferrer">more secure</a> because the eval statement is gone.</p>
<p><strong>EDIT:</strong> I should have also noted that you might have to make similar edits to grid.celledit.js, grid.formedit.js, grid.inlinedit.js, and grid.subgrid.js.</p>
|
<p>I'm just floundering trying to pull everything together. My first concern is simply generating a correct JSON response. My returned class appears to be serialised as a property named 'd' - is this a JQuery thing, or ASP.Net web method convention? I'm afraid that jqGrid will be looking for the data to be top-level, whereas asp.net will put it in a property called 'd':</p>
<pre><code> [WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object GetData() {
TestClass tc = new TestClass() { One = "Hello", Two = "World" };
return tc;
}
$("#divResults").click(function() {
$.ajax({
type: "POST",
url: "GridData_bak.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(test) {
// Replace the div's content with the page method's return.
$("#divResults").text(test.d.One);
},
error: function(msg) {
$("#divResults").text(msg);
}
});
});
</code></pre>
| 21,840
|
<p>The company has the traditional complex organizational structure, defining the amount of levels using the letter 'n' rather than an actual number. I will try and express the structure I'm trying to achieve in mono-spaced font: </p>
<pre><code> Alice
,--------|-------,------,------,
Bob Fred Jack Kim Lucy
| |
Charlie Greg
Darren Henry
Eric
</code></pre>
<p>As you can see it's not symmetrical, as Jack, Kim and Lucy report to Alice but have no reports of their own. </p>
<p>Using a <code>TreeView</code> with an <code>ItemsPanel</code> containing a <code>StackPanel</code> and <code>Orientation="Horizontal"</code> is <a href="http://www.codeproject.com/KB/WPF/CustomTreeViewLayout.aspx" rel="nofollow noreferrer">easy enough</a>, but this can result in a very large <code>TreeView</code> once some people have 20 others reporting to them! You can <a href="http://www.codeproject.com/KB/WPF/AdvancedCustomTreeViewLyt.aspx" rel="nofollow noreferrer">also use</a> <code>Triggers</code> to peek into whether a <code>TreeViewItem</code> has children with <code>Property="TreeViewItem.HasItems"</code>, but this is not in the same context as the before-mentioned <code>ItemsPanel</code>. <em>Eg: I can tell that Fred has reports, but not whether they have reports of their own.</em> </p>
<p>So, can you conditionally format <code>TreeViewItems</code> to be Vertical if they have no children of their own?</p>
|
<p>Josh Smith has a excecllent CodeProject article about TreeView. Read it <a href="http://www.codeproject.com/KB/WPF/AdvancedCustomTreeViewLyt.aspx" rel="nofollow noreferrer">here</a></p>
|
<p>I did end up using tips from the linked article, which I'd already read through but didn't think would help me. </p>
<p>The meat of it happens here, in a converter: </p>
<pre><code><ValueConversion(GetType(ItemsPresenter), GetType(Orientation))> _
Public Class ItemsPanelOrientationConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, _
ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) _
As Object Implements System.Windows.Data.IValueConverter.Convert
'The 'value' argument should reference an ItemsPresenter.'
Dim itemsPresenter As ItemsPresenter = TryCast(value, ItemsPresenter)
If itemsPresenter Is Nothing Then
Return Binding.DoNothing
End If
'The ItemsPresenter''s templated parent should be a TreeViewItem.'
Dim item As TreeViewItem = TryCast(itemsPresenter.TemplatedParent, TreeViewItem)
If item Is Nothing Then
Return Binding.DoNothing
End If
For Each i As Object In item.Items
Dim element As StaffMember = TryCast(i, StaffMember)
If element.IsManager Then
'If this element has children, then return Horizontal'
Return Orientation.Horizontal
End If
Next
'Must be a stub ItemPresenter'
Return Orientation.Vertical
End Function
</code></pre>
<p>Which in turn gets consumed in a style I created for the TreeView: </p>
<pre><code> <Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate >
<ItemsPanelTemplate.Resources>
<local:ItemsPanelOrientationConverter x:Key="conv" />
</ItemsPanelTemplate.Resources>
<StackPanel IsItemsHost="True"
Orientation="{Binding
RelativeSource={x:Static RelativeSource.TemplatedParent},
Converter={StaticResource conv}}" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</code></pre>
| 9,536
|
<p>Scott Gu just posted about a new set of charting controls being distributed by the .NET team. They look incredible: <a href="http://weblogs.asp.net/scottgu/archive/2008/11/24/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt.aspx" rel="noreferrer">http://weblogs.asp.net/scottgu/archive/2008/11/24/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt.aspx</a></p>
<p>The million dollar question is ... will they work with MVC, and if so, when?</p>
|
<p>You can use the chart controls in two ways:</p>
<p><strong>Generating the Image from a Controller</strong></p>
<p>By generating the chart and returning it as an image from an action (as Chatuman is referring to I think):</p>
<pre><code>Chart chart = new Chart();
chart.BackColor = Color.Transparent;
chart.Width = Unit.Pixel(250);
chart.Height = Unit.Pixel(100);
Series series1 = new Series("Series1");
series1.ChartArea = "ca1";
series1.ChartType = SeriesChartType.Pie;
series1.Font = new Font("Verdana", 8.25f, FontStyle.Regular);
series1.Points.Add(new DataPoint {
AxisLabel = "Value1", YValues = new double[] { value1 } });
series1.Points.Add(new DataPoint {
AxisLabel = "Value2", YValues = new double[] { value2 } });
chart.Series.Add(series1);
ChartArea ca1 = new ChartArea("ca1");
ca1.BackColor = Color.Transparent;
chart.ChartAreas.Add(ca1);
using (var ms = new MemoryStream())
{
chart.SaveImage(ms, ChartImageFormat.Png);
ms.Seek(0, SeekOrigin.Begin);
return File(ms.ToArray(), "image/png", "mychart.png");
}
</code></pre>
<p><strong>WebForms Style</strong></p>
<p>This way you just include the chart in your .aspx views (just like with traditional web forms). For this you'll have to hook up the relevant bits in your web.config</p>
<pre><code><controls>
...
<add tagPrefix="asp"
namespace="System.Web.UI.DataVisualization.Charting"
assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
<httpHandlers>
...
<add path="ChartImg.axd"
verb="GET,HEAD"
validate="false"
type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</httpHandlers>
<handlers>
...
<add name="ChartImageHandler"
preCondition="integratedMode"
verb="GET,HEAD"
path="ChartImg.axd"
type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
</code></pre>
<p>You can't run code inside the DataPoint elements when building the chart, so to hook up your data you'll need a method in the View class. This works ok for me. Working this way makes the control render a URL to an image generated by the chart control http handler. In your deployment you'll need to provide a writable folder for it to cache the images.</p>
<p><strong>* VS 2010 / .NET 4 Support *</strong></p>
<p>To get this working in .NET 4 you need to change the chart references to version 4.0.0.0 with the appropriate public key token.</p>
<p>Also it seems that the chart control now generates urls to the current request path rather than the request route. For me this meant that all the chart requests resulted in 404 errors because <code>/{Controller}/ChartImg.axd</code> and equivalents were blocked by routes. To fix this I added extra IgnoreRoute calls that cover my usages - a more general solution would be better:</p>
<pre><code>public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("ChartImg.axd/{*pathInfo}");
routes.IgnoreRoute("{controller}/ChartImg.axd/{*pathInfo}");
routes.IgnoreRoute("{controller}/{action}/ChartImg.axd/{*pathInfo}");
...
</code></pre>
|
<p>I have been testing with MVC and so far it looks like it is working with MVC.</p>
| 41,360
|
<p>I have a query in which I am pulling the runtime of an executable. The database contains its start time and its end time. I would like to get the total time for the run.
So far I have:</p>
<pre><code>SELECT startTime, endTime,
cast(datediff(hh,starttime,endtime) as varchar)
+':'
+cast(datediff(mi,starttime,endtime)-60*datediff(hh,starttime,endtime) as varchar) AS RUNTIME
FROM applog
WHERE runID = 33871
ORDER BY startTime DESC
</code></pre>
<p>When I execute this I get expected values and also some unexpected.
For example, if starttime = 2008-11-02 15:59:59.790 and endtime = 2008-11-02 19:05:41.857 then the runtime is = 4:-54.
How do I get a quere in MS SQL SMS to return the value 3:06 for this case?</p>
<p>Thanks.</p>
<p>Eoin Campbell's I selected as the answer is the most bulletproof for my needs. David B's is do-able as well.</p>
|
<p>Try these</p>
<p>Assuming 2 declared dates.</p>
<pre><code>declare @start datetime
set @start = '2008-11-02 15:59:59.790'
declare @end datetime
set @end = '2008-11-02 19:05:41.857'
</code></pre>
<p>This will return the hours / mins / seconds</p>
<pre><code>select
(datediff(ss, @start, @end) / 3600),
(datediff(ss, @start, @end) / 60) % 60,
(datediff(ss, @start, @end) % 60) % 60
--returns
----------- ----------- -----------
3 5 42
</code></pre>
<p>This is the zero-padded concatenated string version</p>
<pre><code>select
RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 3600)), 2) + ':' +
RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 60) % 60), 2) + ':' +
RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) % 60) % 60), 2)
--------
03:05:42
</code></pre>
|
<p>You should separate your calculation and presentation logic:</p>
<pre><code>DECLARE @applog TABLE
(
runID int,
starttime datetime,
endtime datetime
)
INSERT INTO @applog (runID, starttime, endtime)
SELECT 33871, '2008-11-02 15:59:59.790', '2008-11-02 19:05:41.857'
-------------------
SELECT
SUBSTRING(convert(varchar(30), DateAdd(mi, duration, 0), 121),
12, 5) as prettyduration
FROM
(
SELECT starttime, DateDiff(mi, starttime, endtime) as duration
FROM @applog
WHERE runID = 33871
) as sub
</code></pre>
<p>If you need to represent more than 24 hours, you would use a different presentation logic. This is just what I could think of fastest.</p>
| 32,516
|
<p>What's the performance penalty on defining classes in an aspx/ascx codebehind rather than compiling them into a dll beforehand? I know that this isn't a best practice and that there are numerous problems with this (e.g. difficult to unit test, code is not reusable, etc.), but it does come in very handy when you're dealing with classes that need to be modified on the fly several times a day since those modifications will not require any sort of app restart (e.g. App_Code changes, updating dlls in bin folder).</p>
|
<p>"None." The codebehind classes are compiled into a DLL on the fly, and then that DLL is kept around. So basically the first time you load the page there will be a short delay, but afterwards the speed should be the same as with precompiled classes.</p>
|
<p>I don't believe there really is a performance penalty after the initial dynamic compilation (which will occur on the first hit to the page whose code-behind was modified). How did you end up having to change classes several times a day? That would suck!</p>
<p><strong>EDIT:</strong>
I should've added that this shouldn't affect unit tests or the code-reusability like you stated. There's nothing stopping you from deploying a non-pre-compiled site for maintainability purposes while still being able to run unit tests, deploying compiled assemblies for other projects (if needed), etc. during a check-in/build.</p>
<p>However, if you're not using source control and don't have an automated build, then there's a whole new problem. Our team members used to edit CODE files directly on production servers. <em>shivers</em></p>
| 15,890
|
<p>What is the best way (in C++) to set up a container allowing for double-indexing? Specifically, I have a list of objects, each indexed by a key (possibly multiple per key). This implies a multimap. The problem with this, however, is that it means a possibly worse-than-linear lookup to find the location of an object. I'd rather avoid duplication of data, so having each object maintain it's own coordinate and have to move itself in the map would be bad (not to mention that moving your own object may indirectly call your destructor whilst in a member function!). I would rather some container that maintains an index both by object pointer and coordinate, and that the objects themselves guarantee stable references/pointers. Then each object could store an iterator to the index (including the coordinate), sufficiently abstracted, and know where it is. Boost.MultiIndex seems like the best idea, but it's very scary and I don't wany my actual objects to need to be const.</p>
<p>What would you recommend?</p>
<p>EDIT: Boost Bimap seems nice, but does it provide stable indexing? That is, if I change the coordinate, references to other elements must remain valid. The reason I want to use pointers for indexing is because objects have otherwise no intrinsic ordering, and a pointer can remain constant while the object changes (allowing its use in a Boost MultiIndex, which, IIRC, does provide stable indexing).</p>
|
<p>I'm making several assumptions based on your writeup:</p>
<ul>
<li>Keys are cheap to copy and compare</li>
<li>There should be only one copy of the object in the system</li>
<li>The same key may refer to many objects, but only one object corresponds to a given key (one-to-many)</li>
<li>You want to be able to efficiently look up which objects correspond to a given key, and which key corresponds to a given object</li>
</ul>
<p>I'd suggest:</p>
<ul>
<li>Use a linked list or some other container to maintain a global list of all objects in the system. The objects are allocated on the linked list.</li>
<li>Create one <code>std::multimap<Key, Object *></code> that maps keys to object pointers, pointing to the single canonical location in the linked list.</li>
<li>Do one of:
<ul>
<li>Create one <code>std::map<Object *, Key></code> that allows looking up the key attached to a particular object. Make sure your code updates this map when the key is changed. (This could also be a <code>std::multimap</code> if you need a many-to-many relationship.)</li>
<li>Add a member variable to the <code>Object</code> that contains the current <code>Key</code> (allowing O(1) lookups). Make sure your code updates this variable when the key is changed.</li>
</ul></li>
</ul>
<p>Since your writeup mentioned "coordinates" as the keys, you might also be interested in reading the suggestions at <a href="https://stackoverflow.com/questions/72128/fastest-way-to-find-if-a-3d-coordinate-is-already-used#72178">Fastest way to find if a 3D coordinate is already used</a>.</p>
|
<p>Its difficult to understand what exactly you are doing with it, but it seems like boost <a href="http://www.boost.org/doc/libs/1_36_0/libs/bimap/doc/html/index.html" rel="nofollow noreferrer">bimap</a> is what you want. It's basically boost multi-index except a specific use case, and easier to use. It allows fast lookup based on the first element or the second element. Why are you looking up the location of an object in a map by its address? Use the abstraction and let it do all the work for you. Just a note: iteration over all elements in a map is O(N) so it would be guaranteed O(N) (not worse) to look up the way you are thinking of doing it.</p>
| 12,035
|
<p>The glorified global variable - becomes a gloried global class. Some say breaking object-oriented design.</p>
<p>Give me scenarios, other than the good old logger where it makes sense to use the singleton.</p>
|
<p>On my quest for the truth I discovered that there are actually very few "acceptable" reasons to use a Singleton.</p>
<p>One reason that tends to come up over and over again on the internets is that of a "logging" class (which you mentioned). In this case, a Singleton can be used instead of a single instance of a class because a logging class usually needs to be used over and over again ad nauseam by every class in a project. If every class uses this logging class, dependency injection becomes cumbersome.</p>
<p>Logging is a specific example of an "acceptable" Singleton because it doesn't affect the execution of your code. Disable logging, code execution remains the same. Enable it, same same. Misko puts it in the following way in <a href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/" rel="nofollow noreferrer">Root Cause of Singletons</a>, "The information here flows one way: From your application into the logger. Even though loggers are global state, since no information flows from loggers into your application, loggers are acceptable."</p>
<p>I'm sure there are other valid reasons as well. Alex Miller, in "<a href="https://web.archive.org/web/20120603233658/http://tech.puredanger.com/2007/07/03/pattern-hate-singleton" rel="nofollow noreferrer">Patterns I Hate</a>", talks of service locators and client side UI's also being possibly "acceptable" choices.</p>
<p><a href="https://web.archive.org/web/20201022020333/http://geekswithblogs.net/AngelEyes/archive/2013/09/08/singleton-i-love-you-but-youre-bringing-me-down-re-uploaded.aspx" rel="nofollow noreferrer">Read more at Singleton I love you, but you're bringing me down.</a></p>
|
<p>An example with code, perhaps.</p>
<p>Here, the ConcreteRegistry is a singleton in a poker game that allows the behaviours all the way up the package tree access the few, core interfaces of the game (i.e., the facades for the model, view, controller, environment, etc.):</p>
<p><a href="http://www.edmundkirwan.com/servlet/fractal/cs1/frac-cs40.html" rel="nofollow noreferrer">http://www.edmundkirwan.com/servlet/fractal/cs1/frac-cs40.html</a></p>
<p>Ed.</p>
| 28,237
|
<p>I need a tool to automatically convert simple HTML into an image. I will be controlling the HTML input which will consist of simple text formatting tags and possibly image links--I don't need to be able to render arbitrary HTML. Is there a simple way to do this? </p>
<p>I've looked at the HTML layout engines like Gecko and Webkit, but frankly I'm overwhelmed by the number of options they have--I don't need a complete web browser! Is it possible to use these engines in this way? Can someone steer me in the right direction?</p>
<p>Other possibilities like browsershots, rely on screenshots of real browsers, but I'm going to be running this application on a web server with potentially many users so performance is important and I'm afraid this kind of solution won't scale.</p>
<p>Ideas?</p>
<p>EDIT: Sorry forget to mention that my server is running Linux, so Windows solutions won't help. :)</p>
|
<p>Answering, my own question I found this useful tool which uses WebKit to render a page and then captures the output as an image or even in PDF format! </p>
<p><a href="http://cutycapt.sourceforge.net/" rel="noreferrer">http://cutycapt.sourceforge.net/</a></p>
<p>The idea is similar to khtml2png mentioned by Jay, but I liked this implementation better. Also, for future reference, running an X virtual frame-buffer through Xvfb is not nearly as memory intensive as I had feared.</p>
|
<p>Perhaps you can convert the HTML to another format which is more readily convertable to an image? In Google I found something called html2ps and html2pdf. From PS it's just one step away to EPS, and that can be rendered as an image already. Or something like that.</p>
| 44,429
|
<p>We are looking at various options in porting our persistence layer from Oracle to another database and one that we are looking at is MS SQL. However we use Oracle sequences throughout the code and because of this it seems moving will be a headache. I understand about @identity but that would be a massive overhaul of the persistence code. </p>
<p>Is it possible in SQL Server to create a function which could handle a sequence? </p>
|
<p>That depends on your current use of sequences in Oracle. Typically a sequence is read in the Insert trigger.</p>
<p>From your question I guess that it is the persistence layer that generates the sequence before inserting into the database (including the new pk)</p>
<p>In MSSQL, you can combine SQL statements with ';', so to retrieve the identity column of the newly created record, use INSERT INTO ... ; SELECT SCOPE_IDENTITY()</p>
<p>Thus the command to insert a record return a recordset with a single row and a single column containing the value of the identity column.</p>
<p>You can of course turn this approach around, and create Sequence tables (similar to the dual table in Oracle), in something like this:</p>
<pre><code>INSERT INTO SequenceTable (dummy) VALUES ('X');
SELECT @ID = SCOPE_IDENTITY();
INSERT INTO RealTable (ID, datacolumns) VALUES (@ID, @data1, @data2, ...)
</code></pre>
|
<p>If you have a lot of code, you're going to want to do a massive overhaul of the code anyway; what works well in Oracle is not always going to work well in MSSQL. If you have a lot of cursors, for instance, while you could convert them line for line to MSSQL, you're not going to get good performance. </p>
<p>In short, this is not an easy undertaking.</p>
| 41,979
|
<p>I'm an experienced programmer but just starting out with Flash/Actionscript. I'm working on a project that for certain reasons requires me to use Actionscript 2 rather than 3.</p>
<p>When I run the following (I just put it in frame one of a new flash project), the output is a 3 rather than a 1 ? I need it to be a 1.</p>
<p>Why does the scope of the 'ii' variable continue between loops?</p>
<pre><code>var fs:Array = new Array();
for (var i = 0; i < 3; i++){
var ii = i + 1;
fs[i] = function(){
trace(ii);
}
}
fs[0]();
</code></pre>
|
<p>Unfortunately, AS2 is not that kind of language; it doesn't have that kind of closure. Functions aren't exactly first-class citizens in AS2, and one of the results of that is that a function doesn't retain its own scope, it has to be associated with some scope when it's called (usually the same scope where the function itself is defined, unless you use a function's <code>call</code> or <code>apply</code> methods). </p>
<p>Then when the function is executed, the scope of variables inside it is just the scope of wherever it happened to be called - in your case, the scope outside your loop. This is also why you can do things like this:</p>
<pre><code>function foo() {
trace( this.value );
}
objA = { value:"A" };
objB = { value:"B" };
foo.apply( objA ); // A
foo.apply( objB ); // B
objA.foo = foo;
objB.foo = foo;
objA.foo(); // A
objB.foo(); // B
</code></pre>
<p>If you're used to true OO languages that looks very strange, and the reason is that AS2 is ultimately a <a href="http://en.wikipedia.org/wiki/Prototype-based_programming" rel="nofollow noreferrer">prototyped language</a>. Everything that looks object-oriented is just a coincidence. ;D</p>
|
<p>Unfortunately Actionscript 2.0 does not have a strong scope... especially on the time line.</p>
<pre><code>var fs:Array = new Array();
for (var i = 0; i < 3; i++){
var ii = i + 1;
fs[i] = function(){
trace(ii);
}
}
fs[0]();
trace("out of scope: " + ii + "... but still works");
</code></pre>
| 17,185
|
<p>I have a RVDS project for a certain video decoder (its all C code),
created for ARM926EJ-S target, executed using the RVDS 2.2 simulator.
I am not using any scatterload / <configuration file> / <map file> to
mention the various memory segments in the code like Stack segment,
Heap, Data segment, Code Segment for RVDS Simulator environment.</p>
<ul>
<li>When I add or comment some code (redundant/dead code), then compile the project and execute it, the decoder exits gracefully after mentioning that an error condition has occured , which should not have been the case, as the commented/added code is redundant and does not affect the functionality at all.</li>
<li>Now if i do the operation opposite to that done in 1.) i.e. uncomment code that was commented in step 1.) and compile and execute, the decoder works perfectly fine till its logically end.</li>
<li>Same C source/header files work in a MSVC workspace just fine.</li>
</ul>
<p>I tried to debug a lot through this behaviour but i am not able to pinpoint the cause and the fix for it.</p>
<ul>
<li>Is it a case of stack corruption as i add/remove code?</li>
<li>Is any segment getting overwritten, like Stack segment overflowing into the Data segment, or code segment overflowing into the Data segment?</li>
</ul>
|
<p>Define the constructor for A AFTER the definition of struct B.</p>
|
<p>Interestingly, I've bumped into the same problem with the page 293 ('11.12 A String Class') mentioned in the Stroustrup book.</p>
<p>The example provided in the printed book seems to be at fault, providing the following methods as inline, instead of defining them after the definition of struct Srep</p>
<pre><code>class String {
// ...
void check(int i) const { if (i<0 || rep->sz <=i) throw Range(); }
char read(int i) const { return rep->s[i]; }
void write(int i, char c) { rep=rep->get_own_copy(); rep->s[i]=c; }
...etc...
</code></pre>
<p>I googled a bit, and found the author's latest implementation of this String Class, available here:
<a href="http://www2.research.att.com/~bs/string_example.c" rel="nofollow">http://www2.research.att.com/~bs/string_example.c</a></p>
<p>He seems to have modified it so that these methods are no longer inline, to avoid the problem mentioned in this thread.</p>
| 40,013
|
<p>I receive some arguments into a stored procedure. These arguments are NVARCHAR's.</p>
<p>I have a problem, when I need to cast some of these values to FLOATS, because they are being received as e.g.</p>
<p>@VALUE1 NVARCHAR(100)</p>
<p>DECLARE @ChangedValue
SET @ChangedValue = CAST(@Value1 AS FLOAT)</p>
<p>E.g. @Value1 = "0,001"</p>
<p>Gives me a problem, as it expects "0.001"</p>
<p>I can't change the format of the input, but can I somehow change it on the SQL-server side? By changing all "," to "." instead?</p>
<p>Best regards, Kenn</p>
|
<p>You could use <code>@VALUE1 = REPLACE(@VALUE1, ',', '.')</code></p>
<p>This does seem a horrible thing to do though!</p>
|
<p>As Mitch said it does not sound that good and it would be much better it the provided parameter was of type float in first place. He gave you the solution that solves your problem for now but as he pointed out you may get into some trouble in the future.</p>
<p>I assume that the procedure is called by some application code, and I would suspect that those numbers are user input. If that is the case then the conversion should happen on the application level as that would take care of locale settings and that is the only place that has control over the format of the user input.</p>
| 39,183
|
<p>I'm just getting started/familar with Subversion and was wondering
which protocol gives the best performance file:// or svn://, when accessing a Subversion repository over the network? If we don't use the svn:// protocol, will be missing out on any features that we couldn't mitgate using the file:// protocol? We're all on the same NT domain & plan on using Windows Auth and use NTFS/UNC security.</p>
<p>TIA!</p>
|
<p>The SVN Book recommends that you <i>do not</i> use the file:// protocol for multiple users</p>
<p><a href="http://svnbook.red-bean.com/en/1.8/svn.serverconfig.choosing.html" rel="nofollow noreferrer">Choosing a Server Configuration</a>:</p>
<blockquote>
<p>Do not be seduced by the simple idea of having all of your users access a repository directly via file:// URLs. Even if the repository is readily available to everyone via a network share, this is a bad idea. It removes any layers of protection between the users and the repository: users can accidentally (or intentionally) corrupt the repository database, it becomes hard to take the repository offline for inspection or upgrade, and it can lead to a mess of file permission problems (see the section called “Supporting Multiple Repository Access Methods”). Note that this is also one of the reasons we warn against accessing repositories via svn+ssh:// URLs—from a security standpoint, it's effectively the same as local users accessing via file://, and it can entail all the same problems if the administrator isn't careful</p>
</blockquote>
|
<p>As Paul de Vrieze states the protocol used by SVN is not going to impact performance as much as other factors. If you are on a small local area network then the SVN protocol may be satisfactory for you. In all other cases it seems to be best to use HTTPs:// with Apache. I've been on LANs where the performance of SVN:// is worse than HTTPS:// connections to the internet.</p>
<p>You will also find the Apache is probably a more manageable solution too in terms of security, or SVN repository viewing.</p>
| 48,700
|
<p>I was just about to start using my 3D printers heated bed to warm a chemical reaction in a container and was thinking it would be great to be able to get the bed stepping back and forth to stir the pot.
Can anyone already up to speed in programming G-code walk me through a quick and dirty way to get the X-axis on my old Printrbot metal doing a couple of micro-steps either way in an endless loop? Or suggest some software out there that could achieve the same effect? </p>
|
<p>Basically you need to write a G-code file yourself. This is a plain text file with a <code>.g</code> extension.</p>
<p>You need to home the printer with <code>G28</code>, then move the Y axis all the way forward (for a Prusa style printer) with <code>G1 F1500 Y{ymax}</code> (where <code>{ymax}</code> is the length of the bed). Now raise the head with a similar command <code>G1 F500 Z{zmax}</code> (where <code>{zmax}</code> is the height of the printer volume).</p>
<p>Heating the bed is done with <a href="https://reprap.org/wiki/G-code#M190:_Wait_for_bed_temperature_to_reach_target_temp" rel="nofollow noreferrer"><code>M190 S60</code></a> (set and wait to reach 60 °C).</p>
<p>You can now rock the Y axis by moving it fast, e.g. with <code>G1 F5000 Y{ymax-5}</code>, <code>G1 Y{ymax-1}</code>, <code>Y{ymax-5}</code>, <code>Y{ymax-1}</code>, etc.</p>
|
<p>Never mind, figured the quickest dirtiest way myself - created a tall thin cylinder shape model in Blender and positioned it in Repetier so the printer head will be clear of the table as it moves. Then just broke off the filament that was currently in the printer so it will stop feeding once the current piece gets to the end of the feeder wheel. - not an endless loop but should give me a good 10 or 20 minutes of agitation before I need to restart the print if necessary.</p>
| 1,647
|
<p>I am using a 3rd party API which is defined in 2 DLLs. I have included those DLLs in my project and set references to them. So far so good. </p>
<p>However, these DLLs have at least one dependent DLL which cannot be found at runtime. I copied the missing DLL into the project and set the 'Copy to output' flag but without success.</p>
<p>What should I be doing here to tell the project where it should find the dependent DLL?</p>
<p><strong>Clarification</strong>
I tried adding a reference to the missing DLL but as it wasn't recognised as a .Net component. In desperation, I added it directly to the output folder but without success.</p>
<p>Finally, I installed the API on the PC and it all worked. The installation sets the PATH variable and the DLL is found in the installation folder. <em>But how to tell the project to look in one of its internal folders?</em></p>
|
<p>It sounds like you need to better understand the third-party library and how it uses its own dependencies. If the installation of the API solves the problem, but copying the files manually does not, then you're missing something. There's either a missing file, or some environment variable or registry entry that's required. Two things that will really help you in this is the depends tool (which is part of the C++ installation) and procmon, which will tell you all the registry keys and files that get used at runtime.</p>
<p>If you're lucky, it's just a file that you're missing. If that's all it is, you can use the "Build Events" section of the project to copy the needed files to the right location on a successful build. If not, you're going to have to solve this some other way - either by requiring the API be installed, or rolling your own installation project.</p>
|
<p>How are you deploying? Just flat files? If so, it should work as long as the file ends up in the project output directory. Does it?</p>
<p>If you are using another deployment, you will need to tell that engine to include it. This is different for each of msi/ClickOnce/etc.</p>
| 29,691
|
<p>I have a Java app running on Tomcat, and I would like to monitor counters using Windows Performance Monitor. Is this possible using a JMX adapter for the Java MBeans or by some other means?</p>
|
<p>Since you tagged this with JMX and MBeans, I assume your counters are accessible from a Java MBean. If so you could use jconsole, provided with the Java SDK, to monitor the counters. Once you find your MBean in the MBeans tab, double click on the value and it will draw a nice line graph for easy monitoring.</p>
<p>See <a href="http://java.sun.com/javase/6/docs/technotes/guides/management/jconsole.html" rel="nofollow noreferrer">JConsole Guide</a> for more info.</p>
|
<p>This seems to be exactly what you're looking for, but it's not free:
<a href="http://www.adventnet.com/products/snmpadaptor/faqs/general.html" rel="nofollow noreferrer">http://www.adventnet.com/products/snmpadaptor/faqs/general.html</a></p>
| 46,699
|
<p>Can someone show me how to fix the width of a column in a datatable with JSF?</p>
<p>My code currently reads:</p>
<pre><code><h:column>
<f:facet name="header">
<h:outputText value="Data Field 1" />
</f:facet>
<h:commandLink id="dataLink" action="#{pc_SearchResultsFragment.setField1}">
<h:outputText value="#{(qi.data1 != null) ? '' : qi.data1}"/>
</h:commandLink>
</h:column>
</code></pre>
<p>Thanks!</p>
|
<p>Well usually you use h:column in a dataTable context.</p>
<p>What you could do is set the width in CSS. If you have the code:</p>
<pre><code><h:dataTable value="#{action.items}" var="name"
styleClass="tableClass" columnClasses="first,second">
</code></pre>
<p>And in the CSS file you do:</p>
<pre><code>.first {
width: 250px;
}
</code></pre>
<p>That is assuming you have 2 columns.</p>
<p>Check the dataTable properties <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/tlddocs/h/dataTable.html" rel="noreferrer">here</a>, also you can find there all kind of CSS related properties.</p>
|
<pre><code><h:column>
<f:facet name="header">
<h:outputText value="Data Field 1" />
</f:facet>
<h:commandLink id="dataLink" action="#{pc_SearchResultsFragment.setField1}">
<h:outputText value="#{(qi.data1 != null) ? '' : qi.data1}"/>
</h:commandLink>
<%-- <f:attribute name="width" value="20" /> fixed width --%>
<%-- or --%>
<%-- <f:attribute name="width" value="20%" /> percentage --%>
<%-- also available (not a complete list, just some of the more
common supported attributes) --%>
<%-- <f:attribute name="align" value="left" /> --%>
<%-- <f:attribute name="height" value="20" /> --%>
<%-- <f:attribute name="nowrap" value="true" /> --%>
<%-- <f:attribute name="valign" value="top" /> --%>
<%-- <f:attribute name="bgcolor" value="red" /> --%>
<%-- <f:attribute name="style" value="color:White;" /> --%>
</h:column>
</code></pre>
| 42,293
|
<p>Is there a way in C# or .NET in general to create an attribute on a method which triggers an event when the method is invoked? Ideally, I would be able to run custom actions before and after the invocation of the method.</p>
<p>I mean something like this:</p>
<pre><code>[TriggersMyCustomAction()]
public void DoSomeStuff()
{
}
</code></pre>
<p>I am totally clueless how to do it or if it possible at all, but <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx" rel="noreferrer">System.Diagnostic.ConditionalAttribute</a> might do a similar thing in the background. I am not sure though.</p>
<p><strong>EDIT</strong>: I forgot to mention that due to the circumstances of my specific case, performance is not really an issue.</p>
|
<p>The only way I know how to do this is with <a href="https://www.postsharp.net/" rel="noreferrer">PostSharp</a>. It post-processes your IL and can do things like what you asked for.</p>
|
<p>I don't think there is a way to do it with just an attribute, but using <a href="http://www.codeproject.com/KB/cs/dynamicproxy.aspx" rel="nofollow noreferrer">proxy classes</a> and reflection you could have a class that knows to intercept instantiations of the classes in which you have attributed methods. </p>
<p>Then the proxy class can trigger an event whenever the attributed methods are called.</p>
| 27,997
|
<p>I've created a simple httpModule, registered it on GAC and added it to the global web.config.</p>
<p>I've made some changes to the module, updated the version and changed it also on the web.config.</p>
<p>What happens is that i keep getting the old version. I've restarted the computer, removed it from the GAC, deleted the consumer app .net temp files, but still the consumer app render the old html code from the httpModule.</p>
<p>Any thoughts on what the hell is happening?</p>
<p>Thanks,
Bruno Figueiredo
<a href="http://www.brunofigueiredo.com" rel="nofollow noreferrer">http://www.brunofigueiredo.com</a></p>
|
<p>Is it possible you have an older version lying around in your bin folder? Another alternative is that some other code is comipled against the older version. If all else fails you can use <a href="http://nayyeri.net/blog/redirect-assembly-versions-using-bindingredirect-element/" rel="nofollow noreferrer">bindingRedirect</a> to force your new version.</p>
|
<p>Is it possible you have an older version lying around in your bin folder? Another alternative is that some other code is comipled against the older version. If all else fails you can use <a href="http://nayyeri.net/blog/redirect-assembly-versions-using-bindingredirect-element/" rel="nofollow noreferrer">bindingRedirect</a> to force your new version.</p>
| 34,226
|
<p>I'm wondering, and in need, of strategies that can be applied to reducing low-level locking.
However the catch here is that this is not new code (with tens of thousands of lines of C++ code) for a server application, so I can't just rewrite the whole thing.</p>
<p>I fear there might not be a solution to this problem by now (too late). However I'd like to hear about good patterns others have used.</p>
<p>Right now there are too many lock and not as many conflicts, so it's a paranoia induced hardware performance issue.
The best way to describe the code is as single threaded code suddenly getting peppered with locks.</p>
|
<p>Why do you need to eliminate the low-level locking? Do you have deadlock issues? Do you have performance problems? Or scaling issues? Are the locks generally contended or uncontended?</p>
<p>What environment are you using? The answers in C++ will be different to the ones in Java, for example. E.g. uncontended synchronization blocks in Java 6 are actually relatively cheap in performance terms, so simply upgrading your JRE might get you past whatever problem you are trying to solve. There might be similar performance boosts available in C++ by switching to a different compiler or locking library.</p>
<p>In general, there are several strategies that allow you to reduce the number of mutexes you acquire.</p>
<p>First, anything only ever accessed from a single thread doesn't need a mutex.</p>
<p>Second, anything immutable is safe provided it is 'safely published' (i.e. created in such a way that a partially constructed object is never visible to another thread).</p>
<p>Third, most platforms now support atomic writes - which can help when a single primitive type (including a pointer) is all that needs protecting. These work very similarly to optimistic locking in a database. You can also use atomic writes to create lock-free algorithms to replace more complex types, including Map implementations. However, unless you are very, very good, you are much better off borrowing somebody else's debugged implementation (the java.util.concurrent package contains lots of good examples) - it is notoriously easy to accidentally introduce bugs when writing your own algorithms.</p>
<p>Fourth, widening the scope of the mutex can help - either simply holding open a mutex for longer, rather than constantly locking and unlocking it, or taking a lock on a 'larger' item - the object rather than one of its properties, for example. However, this has to be done extremely carefully; you can easily introduce problems this way.</p>
|
<p>You may find some of the answers <a href="https://stackoverflow.com/questions/92455/how-can-i-write-a-lock-free-structure">here</a> and <a href="https://stackoverflow.com/questions/120937/what-is-test-and-set-used-for#120976">here</a> helpful as you look for ways to atomically update shared state without explicit locks.</p>
| 15,291
|
<p>I've been quite used to working on small projects which I coded with 1,000 lines or less (pong, tetris, simple 3d games, etc). However as my abilities in programming are increasing, my organization isn't. I seem to be making everything dependent on one one another, so it's very hard for me to change the implementation of something. </p>
<p>Any ideas for keeping my code organized and being able to tackle large projects?</p>
|
<p>Sketch out an architectural design ahead of time. It doesn't have to be too detailed, but imagine how you want things to fit together in general terms.</p>
|
<p>Use of design patterns is a good first step.</p>
<p>Also, spend a little time writing good documentation regarding system architecture and requirements for the application.</p>
<p>Using source control will help if you are not already doing this.</p>
<p>Look for libraries that may do want you want before you decide to roll your own.</p>
| 12,400
|
<p>When creating an index over a column that is going to be UNIQUE (but not the primary key of the table), SQL server let's me choose a few options:</p>
<p>1) I can choose for it to be a Constraint or an Index.<br>
I'm guessing this means that if I set it as constraint, it won't use it when querying, only when writing. However, the only efficient way I can think of for SQL Server to enforce that constraint is by actually building an index. What is the use for this option?</p>
<p>2) Also, if I set it as "index", it let's me specify that it should ignore duplicate keys.
This is the most puzzling for me...<br>
I again guess it means the opposite of constraint. It probably means "use it when querying, but don't even check when writing".<br>
But then why would I set it as UNIQUE?<br>
I'm guessing there are some optimizations SQL Server can do, but i'd like to understand it better.</p>
<p>Does anyone know what exactly SQL Server does with these options?<br>
What's the use case for setting an index to be Unique, but ignore duplicate keys?</p>
<p>NOTE: This is for SQL Server 2000</p>
<hr />
<p><strong>EDIT:</strong> According to what you said, however... If I create a Constraint, will it be used to speed up queries that filter using the fields in the constraint?</p>
<p>Thanks!</p>
|
<p>A <code>UNIQUE</code> constraint is part of the ISO/ANSI SQL standard, whereas indexes are not because the Standard is implementation agnostic. SQL Server, in common with most SQL DBMSs, will use an index to implement a <code>UNIQUE</code> constraint.</p>
<p>Arguably, using <code>UNIQUE</code> rather than index in a SQL script is <em>slightly</em> more portable but as always the proprietary syntax should not be ruled out if it provids opportunities for optimization etc.</p>
|
<p>There is no practical difference between a unique constraint and a unique index other than the fact that the unique constraint is also listed as a constraint object in the database. </p>
| 27,389
|
<p>I have a simple page with my <code>ScriptManager</code> and my <code>UpdatePanel</code>, and my <code>ContentTemplate</code> has one <code>ListBox</code> and one Label. I am just trying to catch its <code>OnSelectionChanged</code> so I can update the text in the <code>Label</code>. No matter what settings I try to tweak, I always get a full-page postback.</p>
<p>Is this really not going to work, or am I just screwing this up?</p>
|
<p>You need to have Sharepoint 2007 service pack 1 -- or else there's no chance.
(Sharepoint 2007 predates ajax 1.0 -- they built some support into service pack 1)</p>
<p>Next, from a trouble shooting point of view, test that the <strong>exact</strong> same code functions as expected when hosted in a regular asp.net page. (Literally copy and paste your code across into a fresh page, to rule out any typographical errors). Ruling sharepoint in or out of the problem area will help narrow down the solution space.</p>
|
<p>There's a specific problem with mixing doPostback, UpdatePanel and SharePoint -- and the symptom is exactly what you're seeing: a full-page postback instead of an asynchronous postback. See this KB article for a workaround: <a href="http://support.microsoft.com/kb/941955" rel="nofollow noreferrer">http://support.microsoft.com/kb/941955</a></p>
| 2,524
|
<p>When I download the zip file from the website it contains files with the following extensions:</p>
<p>.dbf
.prj
.sbn
.sbx
.shp
.shp.xml
.shx</p>
<p>Is this is a common data file format that I download or purchase a converter?
I think this is some kind of mapping data file but I all need are the addresses it contains to push into our existing database.</p>
<p>Specifically and related to programming. How can I setup a .NET Datasource to this group of files or just the .dbf file that actually contains the information?</p>
|
<p>Much thanks to everyone who provided information. I found a CodePlex C# project that was exactly what I needed. I did have to make one small modification which I posted back on the project discussion board which was for an unknown column type of "F". But the command line program DBF2CSV worked beautifully to create a well formated csv from the dbf file. After a few minutes with Excel I had it ready to import to our MySQL database.</p>
<p><strong><em>The following project has a command line program that will convert a DBF file to CSV</em></strong>
<a href="http://www.codeplex.com/fastdbf" rel="nofollow noreferrer">http://www.codeplex.com/fastdbf</a></p>
|
<p>The format for the dbf files is like the old DBase III format. The shp files contains the shapes and the shx are some kind of indices.</p>
| 18,111
|
<p>I'm managing an established site which is currently in the process of being upgraded (completely replaced anew), but I'm worried that I'll lose all my Google indexing (that is, there will be a lot of pages in Google's index which won't exist in that place any more).</p>
<p>The last time I upgraded a (different) site, someone told me I should have done <em>something</em> so that my SEO isn't adversely affected. The problem is, I can't remember what that <em>something</em> was.</p>
<hr>
<p><em>Update for some clarification:</em> Basically I'm looking for some way to map the old paths to the new ones. For example:</p>
<ul>
<li>User searches for "awesome page"</li>
<li>Google returns <code>mysite.com/old_awesome_page.php</code>, user clicks it.</li>
<li>My site takes them to <code>mysite.com/new_awesome_page.php</code></li>
</ul>
<p>And when Google gets around to crawling the site again...</p>
<ul>
<li>Google crawls my site, refreshing the existing indexes.</li>
<li>Requests <code>old_awesome_page.php</code></li>
<li>My site tells Google that the page has now moved to <code>new_awesome_page.php</code>.</li>
</ul>
<p>There won't be a simple 1:1 mapping like that, it'll be more like <code>(old) index.php?page=awesome --> (new) index.php/pages/awesome</code>, so I can't just replace the contents of the existing files with redirects.</p>
<p><em>I'm using PHP on Apache</em></p>
|
<p>You need to put some rewrite rules in an .htaccess file.</p>
<p>You can find lots of good information <a href="http://httpd.apache.org/docs/1.3/misc/rewriteguide.html" rel="nofollow noreferrer">here</a>. It's for Apache 1.3, but it works for Apache 2, too.</p>
<p>From that article, a sample for redirecting to files that have moved directories:</p>
<pre><code>RewriteEngine on
RewriteRule ^/~(.+) http://newserver/~$1 [R,L]
</code></pre>
<p>This reads:</p>
<ul>
<li>Turn on the rewrite engine.</li>
<li>For anything that starts with /~, followed by one or more of "anything", rewrite it to <a href="http://newserver/~" rel="nofollow noreferrer">http://newserver/~</a> followed by that "anything".</li>
<li>The [L] means that the rewriting should stop after this rule.</li>
</ul>
<p>There are additional directives that you can use to set a [301] redirect</p>
<p>You could do:</p>
<pre><code>RewriteEngine on
RewriteRule old_page.php new_page.php [L]
</code></pre>
<p>But you'd have to have a rule for every page. To avoid this, I'd look at using Regular Expressions, as in the first example.</p>
|
<p>You can tune Google's view of your site, and probably notify its changes, from within <a href="http://www.google.com/webmasters/tour/tour1.html" rel="nofollow noreferrer">Google Webmaster Tools</a>. I think you should build a sitemap of your current site, and have it verified when the site changes. </p>
| 41,754
|
<p>What's the recommended source control system for a very small team (one developer)?<BR><BR>
Price does not matter. Customer would pay :-)<BR>
I'm working on Vista32 with VS 2008 in C++ and later in C# and with WPF. Setting up an extra (physical) server for this seems overkill to me. <BR><BR>Any opinions?</p>
|
<p>I would use Subversion (in fact I use it) [<strong>update</strong>: Jul 2014 -- I use Git -- see end of the answer].
SVN is:</p>
<ul>
<li>free, </li>
<li>good enough (see disadvantages below), </li>
<li>simple, </li>
<li>works fine on Windows (and Linux too), </li>
<li>a lot of people use it so it's easy to get help, </li>
<li>can integrate with most of IDEs i.e. <strong>Visual Studio</strong> (i.e. <a href="http://ankhsvn.open.collab.net/" rel="nofollow noreferrer">ankhsvn</a> or <a href="http://www.visualsvn.com/" rel="nofollow noreferrer">VisualSVN</a> -- <a href="https://stackoverflow.com/questions/453481/subversion-plugin-to-visual-studio">more info</a>) or <strong>Eclipse</strong> (i.e. <a href="http://sourceforge.net/projects/subclipse/" rel="nofollow noreferrer">Subclipse</a> -- <a href="https://stackoverflow.com/questions/185486/which-eclipse-subversion-plugin-should-i-use">here</a> someone asked about that).</li>
</ul>
<p>I would <strong>strongly</strong> recommended separate machine to source control server. At best somewhere <em>on the cloud</em>. Advantages:</p>
<ul>
<li>You don't lost your source control repositories if your development box dies.</li>
<li>You don't have to worry about maintenance of one more box.</li>
</ul>
<p>There are companies which <a href="http://www.svnhostingcomparison.com/" rel="nofollow noreferrer">host SVN repositories</a>.</p>
<p><a href="http://subversion.apache.org/packages.html" rel="nofollow noreferrer">Here</a> are links to SVN (client and server) packages for various operating systems.</p>
<h1>Disadvantages of SVN</h1>
<p>I am using SVN on Windows machine for about 5 years and found that SVN has a few disadvantages :).</p>
<h2>It is slow on large repositories</h2>
<p>SVN (or its client -- TortoiseSVN) has one <strong>big</strong> disadvantage -- it terrible slow (while updating or committing) on large (thousands of files) repositories unless you have <a href="http://en.wikipedia.org/wiki/Solid-state_drive" rel="nofollow noreferrer">SSD</a> drive.</p>
<h2>Merging can be difficult</h2>
<p>Many people complain about how hard merging is with SVN.</p>
<p>I do merging for about 4 years (including about 2 years in CVS -- that was terrible, but doable) and about 2 years with SVN.</p>
<p>And personally I don't find it hard -- on the other hand -- any merge is easy after merging branches in CVS :).</p>
<p>I do merge of large repository (two repositories in fact) once a week and rarely I have conflicts which are hard to solve (most of conflicts are solved automatically with <em>diff</em> software which I use).</p>
<p>However in case of project of a few developers merging should not be problem at all if you keep a few simple rules:</p>
<ul>
<li>merge changes often,</li>
<li>avoid active development in various branches simultaneously.</li>
</ul>
<h2>Added in July 2011</h2>
<p>Many devs recommended <a href="http://en.wikipedia.org/wiki/Distributed_revision_control_system" rel="nofollow noreferrer">Distributed Version Control</a> like <a href="http://git-scm.com/" rel="nofollow noreferrer">Git</a> or <a href="https://www.mercurial-scm.org/" rel="nofollow noreferrer">Mercurial</a>.</p>
<p>From <strong>single developer</strong> perspective there are only a few important advantages of DVCS over SVN:</p>
<ul>
<li>DVCS can be faster.</li>
<li>You can commit to local repository without access to central one.</li>
<li>DVCS is hot thing and fancy to use/learn (if someone pay for your learning).</li>
</ul>
<p>And I don't think merging is a problem in case of single developer.</p>
<p>Joel Spolsky wrote <a href="http://hginit.com/" rel="nofollow noreferrer">tutorial about Mercurial</a> which is definitively worth to read.</p>
<p>So, despite of many advantages of DVCS I would stay with SVN if merging or speed is not a problem.</p>
<p>Or try Mercurial, which according to <a href="https://stackoverflow.com/questions/995636/popularity-of-git-mercurial-bazaar-vs-which-to-recommend">this</a> and <a href="https://stackoverflow.com/questions/2550091/best-support-now-on-windows-mercurial-or-git">this</a> SO questions, is better supported (in July 2011) on Windows.</p>
<h2>Added in July 2014</h2>
<p>For about a year I use Git (Git Bash mainly) for my pet-projects (i.e. solving Euler problems) and local branches for each Euler problem are really nice feature -- exactly as it is described as advantage of DVCS. </p>
<p>Today Git tooling on Windows is much, much better then 2 or more years ago.
You can use remote repo (like GitHub or ProjectLocker and many others) to keep
copy of your project away from your workstation with no extra effort/money.</p>
<p>However I use GUI client only to looks at diffs (and sometimes to choose files to commit),
so it's better to not afraid of command line -- it's really nice.</p>
<p>So as of today I would go with Git.</p>
|
<p>I dont see why the fact that your one developer changes anything on the source control issue. I would follow the same system (in fact I do on my solo projects). I use <a href="http://wush.net/" rel="nofollow noreferrer">wush.net</a> (svn and trac) in those cases. It's fast to set up and dont require that you yourself do or know any server issues. I recommend you use something like this. </p>
| 6,725
|
<p>Let me first say that being able to take 17 million records from a flat file, pushing to a DB on a remote box and having it take 7 minutes is amazing. SSIS truly is fantastic. But now that I have that data up there, how do I remove duplicates?</p>
<p>Better yet, I want to take the flat file, remove the duplicates from the flat file and put them back into another flat file.</p>
<p>I am thinking about a:</p>
<p><strong><code>Data Flow Task</code></strong></p>
<ul>
<li>File source (with an associated file connection)</li>
<li>A for loop container</li>
<li>A script container that contains some logic to tell if another row exists</li>
</ul>
<p>Thak you, and everyone on this site is incredibly knowledgeable.</p>
<p><strong><code>Update:</code></strong> <a href="http://rafael-salas.blogspot.com/2007/04/remove-duplicates-using-t-sql-rank.html" rel="noreferrer">I have found this link, might help in answering this question</a></p>
|
<p>Use the Sort Component.</p>
<p>Simply choose which fields you wish to sort your loaded rows by and in the bottom left corner you'll see a check box to remove duplicates. This box removes any rows which are duplicates based on the sort criteria only
so in the example below the rows would be considered duplicate if we only sorted on the first field:</p>
<pre><code>1 | sample A |
1 | sample B |
</code></pre>
|
<p>I would recommend loading a staging table on the destination server and then merge the results into a target table on the destination server. If you need to run any hygiene rules, then you could do this via stored procedure since you are bound to get better performance than through SSIS data flow transformation tasks. Besides, deduping is generally a multi-step process. You may want to dedupe on:</p>
<ol>
<li>Distinct lines.</li>
<li>Distinct groups of columns like First Name, Last Name, Email Address, etc.</li>
<li>You may want to dedupe against an existing target table. If that's the case, then you may need to include NOT EXISTS or NOT IN statements. Or you may want to update the original row with new values. This usually is best served with a MERGE statement and a subquery for the source.</li>
<li>Take the first or last row of a particular pattern. For instance, you may want the last row entered in the file for each occurrence of an email address or phone number. I usually rely on CTE's with ROW_NUMBER() to generate sequential order and reverse order columns like in the folling sample:</li>
</ol>
<p>.</p>
<pre><code>WITH
sample_records
( email_address
, entry_date
, row_identifier
)
AS
(
SELECT 'tester@test.com'
, '2009-10-08 10:00:00'
, 1
UNION ALL
SELECT 'tester@test.com'
, '2009-10-08 10:00:01'
, 2
UNION ALL
SELECT 'tester@test.com'
, '2009-10-08 10:00:02'
, 3
UNION ALL
SELECT 'the_other_test@test.com'
, '2009-10-08 10:00:00'
, 4
UNION ALL
SELECT 'the_other_test@test.com'
, '2009-10-08 10:00:00'
, 5
)
, filter_records
( email_address
, entry_date
, row_identifier
, sequential_order
, reverse_order
)
AS
(
SELECT email_address
, entry_date
, row_identifier
, 'sequential_order' = ROW_NUMBER() OVER (
PARTITION BY email_address
ORDER BY row_identifier ASC)
, 'reverse_order' = ROW_NUMBER() OVER (
PARTITION BY email_address
ORDER BY row_identifier DESC)
FROM sample_records
)
SELECT email_address
, entry_date
, row_identifier
FROM filter_records
WHERE reverse_order = 1
ORDER BY email_address;
</code></pre>
<p>There are lots of options for you on deduping files, but ultimately I recommend handling this in a stored procedure once you have loaded a staging table on the destination server. After you cleanse the data, then you can either MERGE or INSERT into your final destination.</p>
| 18,178
|
<p>What is the best python framework to create distributed applications? For example to build a P2P app.</p>
|
<p>You could checkout <a href="http://pyprocessing.berlios.de/" rel="nofollow noreferrer">pyprocessing</a> which will be included in the standard library as of 2.6. It allows you to run tasks on multiple processes using an API similar to threading.</p>
|
<p>You could download the source of BitTorrent for starters and see how they did it.</p>
<p><a href="http://download.bittorrent.com/dl/" rel="nofollow noreferrer">http://download.bittorrent.com/dl/</a></p>
| 11,997
|
<p>I have a CheckedListBox, and I want to automatically tick one of the items in it.</p>
<p>The <code>CheckedItems</code> collection doesn't allow you to add things to it.</p>
<p>Any suggestions?</p>
|
<p>You need to call <strong><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.setitemchecked.aspx" rel="noreferrer"><code>SetItemChecked</code></a></strong> with the relevant item.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.objectcollection.aspx" rel="noreferrer">documentation for <code>CheckedListBox.ObjectCollection</code></a> has an example which checks every other item in a collection.</p>
|
<p>Use:</p>
<pre><code>string[] aa = new string[] {"adiii", "yaseen", "salman"};
foreach (string a in aa)
{
checkedListBox1.Items.Add(a);
}
</code></pre>
<p>Now code where you want to check all:</p>
<pre><code>private void button5_Click(object sender, EventArgs e)
{
for(int a=0; a<checkedListBox1.Items.Count; a++)
checkedListBox1.SetItemChecked(a, true);
}
</code></pre>
<p>To uncheck all:</p>
<pre><code>private void button_Click(object sender, EventArgs e)
{
for(int a=0; a<checkedListBox1.Items.Count; a++)
checkedListBox1.SetItemChecked(a, false);
}
</code></pre>
| 48,454
|
<p>I'm trying to implement a data compression idea I've had, and since I'm imagining running it against a large corpus of test data, I had thought to code it in C (I mostly have experience in scripting languages like Ruby and Tcl.) </p>
<p>Looking through the O'Reilly 'cow' books on C, I realize that I can't simply index the bits of a simple 'char' or 'int' type variable as I'd like to to do bitwise comparisons and operators. </p>
<p>Am I correct in this perception? Is it reasonable for me to use an enumerated type for representing a bit (and make an array of these, and writing functions to convert to and from char)? If so, is such a type and functions defined in a standard library already somewhere? Are there other (better?) approaches? Is there some example code somewhere that someone could point me to?</p>
<p>Thanks - </p>
|
<p>Following on from what Kyle has said, you can use a macro to do the hard work for you.</p>
<blockquote>
<p>It is possible.</p>
<p>To set the nth bit, use OR:</p>
<p>x |= (1 << 5); // sets the 6th-from
right</p>
<p>To clear a bit, use AND:</p>
<p>x &= ~(1 << 5); // clears
6th-from-right</p>
<p>To flip a bit, use XOR:</p>
<p>x ^= (1 << 5); // flips 6th-from-right</p>
</blockquote>
<p><strong>Or...</strong></p>
<pre><code>#define GetBit(var, bit) ((var & (1 << bit)) != 0) // Returns true / false if bit is set
#define SetBit(var, bit) (var |= (1 << bit))
#define FlipBit(var, bit) (var ^= (1 << bit))
</code></pre>
<p>Then you can use it in code like:</p>
<pre><code>int myVar = 0;
SetBit(myVar, 5);
if (GetBit(myVar, 5))
{
// Do something
}
</code></pre>
|
<p>IF you want to index a bit you could:</p>
<pre><code>bit = (char & 0xF0) >> 7;
</code></pre>
<p>gets the msb of a char. You could even leave out the right shift and do a test on 0.</p>
<pre><code>bit = char & 0xF0;
</code></pre>
<p>if the bit is set the result will be > 0;</p>
<p>obviousuly, you need to change the mask to get different bits (NB: the 0xF is the bit mask if it is unclear). It is possible to define numerous masks e.g.</p>
<pre><code>#define BIT_0 0x1 // or 1 << 0
#define BIT_1 0x2 // or 1 << 1
#define BIT_2 0x4 // or 1 << 2
#define BIT_3 0x8 // or 1 << 3
</code></pre>
<p>etc...</p>
<p>This gives you:</p>
<pre><code>bit = char & BIT_1;
</code></pre>
<p>You can use these definitions in the above code to sucessfully index a bit within either a macro or a function.</p>
<p>To set a bit:</p>
<pre><code>char |= BIT_2;
</code></pre>
<p>To clear a bit:</p>
<pre><code>char &= ~BIT_3
</code></pre>
<p>To toggle a bit</p>
<pre><code>char ^= BIT_4
</code></pre>
<p>This help?</p>
| 8,819
|
<p>Is there any way to find out if the user pressed the delete key or dot? It has the same keycode in FireFox.</p>
|
<p>According to <a href="http://www.quirksmode.org/js/keys.html" rel="nofollow noreferrer">Detecting keystrokes</a>, it is possible, provided that:</p>
<ul>
<li>you search for the keyCode (<strong>8</strong> for delete) onkeydown/up, and </li>
<li>ignore both onkeypress and charCode (Especially if you consider the fact that IE does not fire keypressed event, only key up/down).</li>
</ul>
|
<p>According to <a href="http://www.quirksmode.org/js/keys.html" rel="nofollow noreferrer">Detecting keystrokes</a>, it is possible, provided that:</p>
<ul>
<li>you search for the keyCode (<strong>8</strong> for delete) onkeydown/up, and </li>
<li>ignore both onkeypress and charCode (Especially if you consider the fact that IE does not fire keypressed event, only key up/down).</li>
</ul>
| 37,738
|
<p>I want to use RSpec mocks to provide canned input to a block.</p>
<p>Ruby:</p>
<pre><code>class Parser
attr_accessor :extracted
def parse(fname)
File.open(fname).each do |line|
extracted = line if line =~ /^RCS file: (.*),v$/
end
end
end
</code></pre>
<p>RSpec:</p>
<pre><code>describe Parser
before do
@parser = Parser.new
@lines = mock("lines")
@lines.stub!(:each)
File.stub!(:open).and_return(@lines)
end
it "should extract a filename into extracted" do
linetext = [ "RCS file: hello,v\n", "bla bla bla\n" ]
# HELP ME HERE ...
# the :each should be fed with 'linetext'
@lines.should_receive(:each)
@parser.should_receive('extracted=')
@parser.parse("somefile.txt")
end
end
</code></pre>
<p>It's a way to test that the internals of the block work correctly by passing fixtured data into it. But I can't figure out how to do the actual feeding with RSpec mocking mechanism.</p>
<p><strong>update:</strong> looks like the problem was not with the linetext, but with the:</p>
<pre><code>@parser.should_receive('extracted=')
</code></pre>
<p>it's not the way it's called, replacing it in the ruby code with self.extracted= helps a bit, but feels wrong somehow.</p>
|
<p>I don't have a computer with Ruby & RSpec available to check this, but I suspect you need to add a call to <code>and_yields</code> call [1] on the end of the <code>should_receive(:each)</code>. However, you might find it simpler not to use mocks in this case e.g. you could return a <code>StringIO</code> instance containing <code>linetext</code> from the <code>File.open</code> stub.</p>
<p>[1] <a href="http://rspec.rubyforge.org/rspec/1.1.11/classes/Spec/Mocks/BaseExpectation.src/M000104.html" rel="nofollow noreferrer">http://rspec.rubyforge.org/rspec/1.1.11/classes/Spec/Mocks/BaseExpectation.src/M000104.html</a></p>
|
<p>This should do the trick:</p>
<pre><code>describe Parser
before do
@parser = Parser.new
end
it "should extract a filename into extracted" do
linetext = [ "RCS file: hello,v\n", "bla bla bla\n" ]
File.should_receive(:open).with("somefile.txt").and_return(linetext)
@parser.parse("somefile.txt")
@parser.extracted.should == "hello"
end
end
</code></pre>
<p>There are some bugs in the Parser class (it won't pass the test), but that's how I'd write the test.</p>
| 49,569
|
<p>What are the basic steps to compile an OpenGL application using <em>GLUT (OpenGL Utility Toolkit)</em> under Visual C++ Express Edition?</p>
|
<ol>
<li>If you don't have Visual C++ Express Edition (VCEE), download and install <a href="http://msdn.microsoft.com/vstudio/express/visualc/default.aspx" rel="nofollow noreferrer">VCEE</a>.</li>
<li>The default install of Visual C++ Express Edition builds for the .Net platform. We'll need to build for the Windows platform since OpenGL and GLUT are not yet fully supported under .Net. For this we need the Microsoft Platform SDK. (If you're using an older version of VCEE, download and install the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=A55B6B43-E24F-4EA3-A93E-40C0EC4F68E5" rel="nofollow noreferrer">Microsoft Platform SDK</a>. Visual C++ Express Edition will need to be configured to build for Windows platform. All these instructions are available <a href="http://msdn.microsoft.com/en-us/library/ms235626(VS.80).aspx" rel="nofollow noreferrer">here</a>.)</li>
<li>If you don't have GLUT, download and unzip Nate Robin's <a href="http://www.xmission.com/~nate/glut.html" rel="nofollow noreferrer">Windows port of GLUT</a>.</li>
<li>Add <strong>glut.h</strong> to your <em>Platform SDK/include/GL/</em> directory</li>
<li>Link the project with <strong>glut.lib</strong>. (Go to VCEE <em>Project Properties -> Additional Linker Directories</em> and add the directory which has <strong>glut.lib</strong>.</li>
<li>Add <strong>glut.dll</strong> to the <em>Windows/System32</em> directory, so that all programs using GLUT
can find it at runtime.</li>
</ol>
<p>Your program which uses GLUT or OpenGL should compile under Visual C++ Express Edition now.</p>
|
<p>The GLUT port on Nate Robin's site is from 2001 and has some incompatibilities with versions of Visual Studio more recent than that (.NET 2003 and up). The incompatibility manifests itself as errors about redefinition of <code>exit()</code>. If you see this error, there are two possible solutions:</p>
<ol>
<li>Replace the <code>exit()</code> prototype in <code>glut.h</code> with the one in your <code>stdlib.h</code> so that they match. This is probably the best solution.</li>
<li>An easier solution is to <code>#define GLUT_DISABLE_ATEXIT_HACK</code> before you <code>#include <gl/glut.h></code> in your program.</li>
</ol>
<p>(Due credit: I originally saw this advice on the <a href="http://helpdesk.cs.tamu.edu/docs/glut_Visual_Studio2003" rel="noreferrer">TAMU help desk website</a>.)</p>
<p>I've been using approach #1 myself since .NET 2003 came out, and have used the same modified <code>glut.h</code> with VC++ 2003, VC++ 2005 and VC++ 2008.</p>
<p>Here's the diff for the glut.h I use which does #1 (but in appropriate <code>#ifdef blocks</code> so that it still works with older versions of Visual Studio):</p>
<pre><code>--- c:\naterobbins\glut.h 2000-12-13 00:22:52.000000000 +0900
+++ c:\updated\glut.h 2006-05-23 11:06:10.000000000 +0900
@@ -143,7 +143,12 @@
#if defined(_WIN32)
# ifndef GLUT_BUILDING_LIB
-extern _CRTIMP void __cdecl exit(int);
+/* extern _CRTIMP void __cdecl exit(int); /* Changed for .NET */
+# if _MSC_VER >= 1200
+extern _CRTIMP __declspec(noreturn) void __cdecl exit(int);
+# else
+extern _CRTIMP void __cdecl exit(int);
+# endif
# endif
#else
/* non-Win32 case. */
</code></pre>
| 3,503
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.