instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm currently working at a small web development company, we mostly do campaign sites and other promotional stuff. For our first year we've been using a "server" for sharing project files, a plain windows machine with a network share. But this isn't exactly future proof. </p> <p>SVN is great for code (it's what we use now), but I want to have the comfort of versioning (or atleast some form of syncing) for all or most of our files. </p> <p><em>What I essentially want is something that does what subversion does for code, but for our documents/psd/pdf files.</em> </p> <p>I realize subversion handles binary files too, but I feel it might be a bit overkill for our purposes. It doesn't necessarily need all the bells and whistles of a full version control system, but something that that removes the need for incremental naming (Notes_1.23.doc) and lessens the chance of overwriting something by mistake. </p> <p>It also needs to be multiplatform, handle large files (100 mb+) and be usable by somewhat non technical people. </p>
<p>SVN is great for binaries, too. If you're afraid you can't compare revisions, I can tell you that it is possible for Word docs, using Tortoise.<br> But I do not know, what you mean with "expanding the versioning". SVN is no document management system. </p> <p>Edit:</p> <blockquote> <p>but I feel it might be a bit overkill for our purposes </p> </blockquote> <p>If you are already using SVN and it fulfils your purposes, why bother with a second system?</p>
<p>You might want to consider using a Mac as your server and using <a href="http://www.apple.com/macosx/features/timemachine.html" rel="nofollow noreferrer">Time Machine</a> to backup your shared folders. Doing this gives you automatic backups and allows you to share through Samba so everyone can have a <a href="http://support.microsoft.com/kb/308582" rel="nofollow noreferrer">network drive</a> on their computer. A Mac server is probably overkill. A Mac Mini would do for a small office or a repurposed desktop machine.</p> <p>You might also consider <a href="http://www.amazon.com/gp/browse.html?node=16427261" rel="nofollow noreferrer">Amazon's S3 service</a> to do offline backups. Since it's a pay-as-you-go service this can scale with use, and if you feel you want to move to something else you can always download your data and take it somewhere else.</p>
3,508
<p>binary question :)</p>
<p>The answer is 4 bits. 2 nibbles make a byte.</p> <p><a href="http://www.geneziegler.com/clocktower/DrSeuss.html" rel="nofollow noreferrer">See here</a> for a cute poem.</p>
<p>4 bits = 1 nibble</p> <p>8 bits = 1 byte</p>
12,673
<p>I have been printing toy cars for about a month now and my Ender 3 has stopped extruding plastic even when I insert filament, it has been about a day since it stopped working. Is there any tips for getting it working again?</p> <p>I tried manual feeding which worked.</p>
<p>You need to figure out what is not working</p> <ul> <li>Is the hotend getting hot? If not, melted filament won't come out.</li> <li>Is the nozzle clogged? In your toolkit was a bit of thin wire for poking into the nozzle - try that and see what happens.<br> You may need to heat the hotend, extract the filament, wait for it to cool, remove the bowden tube and push the wire up from below, if the obstruction is too big to come through the 0.4mm nozzle.</li> <li>Is the extruder pushing/feeding filament? Undo the bowden tube at the top, tell the control panel to extrude and observe if plastic moves. An Ender3 V2 has the round handle on top, you should see it slowly revolving.<br> If you can see the gears turning and the filament is not coming through, try snipping that piece off and inserting a fresh end. Also clean inside the pushing gears of the extruder, could be simple plastic detris laying about.</li> <li>Are you having reel problems? Can you tug on the filament and have the reel turn? If not, it might be binding on the roll, or knotted/tangled.</li> </ul>
<p>My comment refuses to upload so I think it’ll be ok if I just put it here:</p> <p>Thanks this fixed it I had to replace my hot end as the one had broken for some reason but now it is fully working again, thank you so much!</p> <p>Sorry for all the mistakes in formatting, I am new I joined 3 days ago.</p>
2,033
<p>I am writing a little application to download files over http (as, for example, described <a href="https://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776">here</a>).</p> <p>I also want to include a little download progress indicator showing the percentage of the download progress.</p> <p>Here is what I came up with:</p> <pre> sys.stdout.write(rem_file + "...") urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("%2d%%" % percent) sys.stdout.write("\b\b\b") sys.stdout.flush() </pre> <p>Output: MyFileName... 9%</p> <p>Any other ideas or recommendations to do this? </p> <p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p> <p><strong>EDIT:</strong></p> <p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p> <pre> global rem_file # global variable to be used in dlProgress urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("\r" + rem_file + "...%d%%" % percent) sys.stdout.flush() </pre> <p>Output: MyFileName...9% </p> <p>And the cursor shows up at the END of the line. Much better.</p>
<p>There's a text progress bar library for python at <a href="http://pypi.python.org/pypi/progressbar/2.2" rel="noreferrer">http://pypi.python.org/pypi/progressbar/2.2</a> that you might find useful:</p> <blockquote> <p>This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway.</p> <p>The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line.</p> <p>The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when available.</p> </blockquote>
<p>For small files you may need to had this lines in order to avoid crazy percentages:</p> <p>sys.stdout.write("\r%2d%%" % percent)</p> <p>sys.stdout.flush()</p> <p>Cheers</p>
7,420
<p>I have an aspx page with 1 table containing 2 rows:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;style&gt; html, body { height: 100%; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server"&gt; &lt;/asp:ScriptManager&gt; &lt;table style="height:100%; width:100%"&gt; &lt;tr&gt; &lt;td&gt; &lt;img src="img/Logo.png" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style="height:100%;"&gt; &lt;asp:Silverlight ID="sllUI" runat="server" Source="~/ClientBin/My.Silverlight.UI.xap" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" OnPluginLoaded="sllUI_OnPluginLoaded" PluginBackground="Transparent" Windowless="true"&gt; &lt;/asp:Silverlight&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/form&gt; &lt;body&gt; &lt;/html&gt; </code></pre> <p>The table fills the page correctly, and the bottom row fills grows to the remaining height of the table that the top row doesn't fill, which is what I want. The problem is that the silverlight control takes on the height of the page, not the height of the row that it is in, which causes my page to get scroll bars because the top of the silver light control is at the top of the row it's in, but it's hight is 100% of the browser. I don't know if this is caused by my html or by silverlight. All my silverlight user controls are set to auto height &amp; width. I've also tried using divs instead of the table and I get the same result. How can I fix this?</p> <p>I've found that (at least in IE7) the doctype I've specified causes it to use standards mode IE6, but if I take the doctype out it goes into quirks mode IE5 (I find the mode by using DebugBar v5.1.1). Quirks mode causes it to display properly, but I think I'd rather avoid quirks mode if I can get the display correct in standard mode.</p>
<p>Try removing the 'Height' and 'Width' properties in your control, if you've defined the internal XAP's height and width correctly to scale (i.e. you've used "Auto"), then it should respect what DOM boundaries it's contained within on the page.</p>
<p>Try to use some kind of script to determine the total height of your page... something like this:</p> <pre><code> function getWindowHeight() { var windowHeight = 0; if (typeof(window.innerHeight) == 'number') { windowHeight = window.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else { if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } } } return windowHeight; } </code></pre> <p>So you can subtract your logo height and set the height your 'body' properly, adjusting it to avoid scrolls.</p>
49,176
<p>I re-image one of my machines regularly; and have a script that I run after the OS install completes to configure my machine; such that it works how I like.</p> <p>I happen to have my data on another drive...and I'd like to add code to my script to change the location of the Documents directory from "C:\Users\bryansh\Documents" to "D:\Users\bryansh\Documents".</p> <p>Does anybody have any insight, before I fire up regmon and really roll up my sleeves?</p>
<p>in the aspx page:</p> <pre><code>&lt;asp:FileUpload ID="FileUpload1" runat="server" /&gt; </code></pre> <p>in the codebehind (c#):</p> <pre><code>string contentType = FileUpload1.PostedFile.ContentType </code></pre>
<p>Get MIME type from a file in ASP.NET Core</p> <pre><code>public string GetMimeType(string filePath) { var provider = new FileExtensionContentTypeProvider(); if (!provider.TryGetContentType(filePath, out var contentType)) contentType = &quot;application/octet-stream&quot;; // fallback: unknown binary type return contentType; } </code></pre>
10,689
<p>I am trying to generate a Sandcastle help file for a website. In the properties window for project, there aren't any options for creating the XML Documentation File required for Sandcastle.</p> <p>The Build tab in the property pages only contains options for: Start Action, Build Solution Action, and Accessibility validation. I don't have any options for Output, or XML documentation file, like my other projects have.</p> <p>The website I'm working with does not have an actual .proj file, which could be the problem. If this is the problem, what is the best way of creating one for a project that is under source control and being worked on by many people with minimal disruption?</p> <p>This is using Visual Studio 2005 professional.</p>
<p>The problem with websites in VS2k5 is that, when they get compiled, the resulting dlls are a mess. No namespaces, weird names, etc. </p> <p>If you truly want to generate a Sandcastle Help File, look at converting your website into a web application. You can definitely generate source code docs for that.</p>
<p>I haven't tried it yet, but you might want to try the following <a href="http://www.ewoodruff.us/shfbdocs/html/94c7f744-9b90-4254-93ab-9b15f47d9f42.htm" rel="nofollow">Documenting Web Sites / Projects</a> from Eric Woodruff's site. It gives the specifics on how it can be done. </p> <p>Update: I did try it and it works for regular websites. The only issue I can see is that the websites don't have namespaces. So when I run it I get a topic by FolderName_WebPage Class format without any logical grouping. So it is alhpabetical by folder and page name. Once you got the content created, you can edit the help file using a helpcompiler / builder and group the topics as needed.</p>
12,854
<p>Is there an event like onLoad? </p> <p>just at closing the Site (onClose)?</p>
<p>Not in the sense that I suspect you're thinking. All your code in ASP.net runs on the server which doesn't inherently "know" when the site is closed by the user. To achieve what you're after, you'd need to use Javascript to handle the window.onunload / window.onbeforeunload events and trigger some form of request to the server.</p> <p>Take a look at <a href="http://developer.mozilla.org/en/DOM/window.onunload" rel="nofollow noreferrer">http://developer.mozilla.org/en/DOM/window.onunload</a> for more information on the window.onunload event.</p> <p>Update: If you're using/able to use ASP.net AJAX, there's some quite tidy wrappers there that provide you with a similar set of events/beahviours to the server-side page lifecycle. There's a pretty decent tutorial from Stephen Walther <a href="http://weblogs.asp.net/stephenwalther/archive/2008/03/07/asp-net-ajax-in-depth-application-events.aspx" rel="nofollow noreferrer">on his blog</a>.</p>
<p>The closest you can get it UnLoad.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms178472.aspx</a></p>
22,545
<p>I have a Delphi 7 app using <code>ADO/MSDASQL.1</code> provider and I wonder if it is possible to "log" the SQL queries sent to the DB in a easy way? Just like the SQL profiler in SQL Server?</p>
<p>Inside your application you can log the commands in TADOConnection.OnWillExecute event, you only have to save the CommandText, but you can also log a lot of other options.</p> <pre><code>procedure TForm23.ADOConnection1WillExecute(Connection: TADOConnection; var CommandText: WideString; var CursorType: TCursorType; var LockType: TADOLockType; var CommandType: TCommandType; var ExecuteOptions: TExecuteOptions; var EventStatus: TEventStatus; const Command: _Command; const Recordset: _Recordset); begin LogToFile( CommandText ); end; </code></pre>
<p>I do something similar, but all my queries go through a single point. It was a simple change to add logging at this point. Another option would be to create a TLogADOQuery class which descends from TADOQuery, and override <strong>ExecuteSQL</strong> and <strong>Open</strong> to log the SQL going to the database. You then replace all references to TADOQuery, with your new class.</p>
45,030
<p>If a person is looking to batch convert a large number of raster images into vector graphics, are there any tools out there that do that well?</p> <p>For an example, think of just about any diagram that has standard shapes (ellipses, rectangles) and text.</p>
<p><a href="http://www.inkscape.org/doc/tracing/tutorial-tracing.html" rel="noreferrer">Inkscape uses</a> the Potrace engine to trace raster graphics. You usually have to play with it a bit to get useful output, but it does surprisingly well and is easy to use.</p>
<p>As of today 2021.1.13,</p> <p>I think Vector Magic is still the best tool on the market, they are pround to declare that on their website:</p> <p><a href="https://i.stack.imgur.com/Dkz7w.png" rel="nofollow noreferrer">&quot;Simply the Best Auto-Tracer in the World&quot;</a><br> You can test out their online raster to vector conversion for free. <a href="https://vectormagic.com/" rel="nofollow noreferrer">https://vectormagic.com/</a><br></p> <p>But there are, Indeed, so many techniques in Lab seems quite appearing, Like this one:<br> <a href="https://i.stack.imgur.com/01cu8.jpg" rel="nofollow noreferrer">Perception-Driven Semi-Structured Boundary Vectorization</a></p> <p>You can get their tech details and demo software here: <a href="http://www.cs.ubc.ca/labs/imager/tr/2018/PerceptionDrivenVectorization/" rel="nofollow noreferrer">http://www.cs.ubc.ca/labs/imager/tr/2018/PerceptionDrivenVectorization/</a></p> <p>The result turn out to be so good, quite impressive, but the speed of conversion is quite impressive too, way too slow.</p> <p>Authors of that paper are from:<br> 1 University of British Columbia, 2 Adobe, 3 National Taiwan University</p> <p>I don't know why they not do some speed optimization, build an better UI and make an awesome tool from that work.</p>
22,879
<p>I was using a CASE called <a href="http://www.magicsoftware.com/" rel="nofollow noreferrer">MAGIC</a> for a system I'm developing, I've never used this kind of tool before and at first sight I liked, a month later I had a lot of the application generated, I felt very productive and ... I would say ... satisfied.</p> <p>In some way a felt uncomfortable, cause, there is no code and everything I was used to, but in the other hand I could speed up my developing. The fact is that eventually I returned to use C# because I find it more flexible to develop, I can make unit testing, use CVS, I have access to more resources and basically I had "all the control". I felt that this tool didn't give me confidence and I thought that later in the project I could not manage it due to its forced established rules of development. And also a lot of things like sending emails, using my own controls, and other things had their complication, it seemed that at some point it was not going to be as easy as initially I thought and as initially the product claims. This reminds me a very nice article called "<a href="http://www.virtualschool.edu/mon/SoftwareEngineering/BrooksNoSilverBullet.html" rel="nofollow noreferrer">No Silver Bullet</a>".</p> <p>This CASE had its advantages but on the other hand it doesn't have resources you can consult and actually the license and certification are very expensive. For me another dissapointing thing is that because of its simplistic approach for development I felt scared on first hand cause of my unexperience on these kind of tools and second cause I thought that if I continued using it maybe it would have turned to be a complex monster that I could not manage later in the project.</p> <p>I think it's good to use these kind of solutions to speed up things but I wonder, why aren't these programs as popular as VS.Net, J2EE, Ruby, Python, etc. if they claim to enhance productivity better than the tools I've pointed?</p>
<p>We use a CASE tool at my current company for code generation and we are trying to move away from it.</p> <p>The benefits that it brings - a graphical representation of the code making components 'easier' to pick up for new developers - are outweighed by the disadvantges in my opinion.</p> <p>Those main disadvantages are:</p> <ol> <li><p>We cannot do automatic merges, making it close to impossible for parallel development on one component.</p></li> <li><p>Developers get dependant on the tool and 'forget' how to handcode.</p></li> </ol>
<p>Just a couple questions for you:</p> <p>How much productivity do you gain compared to the control that you use? How testable and reliant is the code you create? How well can you implement a new pattern into your design?</p> <p>I can't imagine that there is a CASE out there that I could write a test first and then use a CASE to generate the code I need. I'd rather stick to resharper which can easily do my mundane tasks and retain full control of my code.</p>
3,448
<p>In asp.net mvc, I want to create a action for login.</p> <p>So this is how I am doing it:</p> <ol> <li><p>create a action/view named login that simply displays the view.</p></li> <li><p>create another action, named login2 that will be the page that handles the form post and checks the database if the username/password are correct. If it is, redirect to somepage, if not, redirect back to the login page with the appropriate error message.</p></li> </ol> <p>Is this the best way to do this?</p>
<p>You can create two Login actions one for viewing and one for form posting. Then decorate them with AcceptVerbs attribute to describe which method they will accept. See here for an example <a href="http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx</a></p>
<p>I agree with Craig; however, if you want to do it some other way you should come up with some naming conventions to differentiate your ActionMethods and stick to them.</p> <p>Before preview 5 i used </p> <p>login => authenticate create => insert edit => update</p> <p>etc.</p>
36,765
<p>I am looking for any and all suggestions of the <strong>best and effective resources</strong> that the StackOverflow community has used to better learn <strong>MSBuild with an emphasis on integrating unit tests</strong> and later static code analysis tools such as FxCop and StyleCop into the build process.</p> <p>I have tried to find good clear documentation on adding unit tests into my build but I still am searching - even Google searches have come up empty or with just bits and pieces. Ideally I want to add unit tests, report results, and eventually add code coverage statistics, etc into the build results.</p> <p>I know it has to be in MSDN somewhere but I seem unable to find anything which explains and teaches well. I am using Visual Studio Team System 2008.</p>
<p><a href="http://dotnet.org.za/cjlotz/archive/2008/01/15/continuous-integration-from-theory-to-practice-2nd-edition.aspx" rel="nofollow noreferrer">Continuous Integration From Theory to Practice</a> by Carel Lotz. It covers the entire scope of your problem, and then some. Well written, complete, and a full sample are all there.</p> <p>Hands down best resource. Use it as a tutorial first, then use it as a guide, then use it as a reference.</p> <p>MSDN and others are good for clarifying (or confusing) the details.</p> <p><strong>Edit:</strong> The guide by Carel Lotz uses MBUnit for unit tests (see his earlier document version for NUnit, though you can replace the MBUnit with NUnit pretty easily if you follow the NUnit help files). </p> <p>Also, it is written to use Cruise Control.NET to run the MSBuild script in various configurations.</p> <p>Personally, I run unit tests in a secondary MSBuild script, but have found that wrapping the NUnit calls in MSBuild gives more flexibility than running from CCNet directly.</p>
<p>I guess I need to ask if you are <em>sure</em> you want to use MSBuild directly? Might want to check out <a href="http://wix.sourceforge.net/" rel="nofollow noreferrer">WIX</a> as the MSI producing tool - there is an extensive manual and it is built on top of MSBuild.</p> <p>As for the automating of your tests with reporting and integrating with NUnit, FxCop, NCover, FitNesse, etc - I think the best (free) tool out there is <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET" rel="nofollow noreferrer">CruiseControl .Net</a>. It works with all of these tools and more. Can do versioning, automated builds with automated testing, creates the reports for each... </p> <p>Here is a sample of one of my builds... </p> <p><a href="http://img84.imageshack.us/img84/3664/cruisecontrolnetsamplezn0.jpg" rel="nofollow noreferrer">http://img84.imageshack.us/img84/3664/cruisecontrolnetsamplezn0.jpg http://img84.imageshack.us/img84/3664/cruisecontrolnetsamplezn0.jpg</a></p>
32,930
<p>I'm trying to figure out the best way to insert a record into a single table but only if the item doesn't already exist. The KEY in this case is an NVARCHAR(400) field. For this example, lets pretend it's the name of a <em>word</em> in the Oxford English Dictionary / insert your fav dictionary here. Also, i'm guessing i will need to make the Word field a primary key. (the table will also have a unique identifier PK also).</p> <p>So .. i might get these words that i need to add to the table...</p> <p>eg.</p> <ul> <li>Cat </li> <li>Dog </li> <li>Foo</li> <li>Bar</li> <li>PewPew </li> <li>etc...</li> </ul> <p>So traditionally, i would try the following (pseudo code)</p> <pre><code>SELECT WordID FROM Words WHERE Word = @Word IF WordID IS NULL OR WordID &lt;= 0 INSERT INTO Words VALUES (@Word) </code></pre> <p>ie. <em>If the word doesn't exist, then insert it.</em></p> <p>Now .. the problem i'm worried about is that we're getting LOTS of hits .. so is it possible that the word could be inserted from another process in between the SELECT and the INSERT .. which would then throw a constraint error? (ie. a <a href="http://en.wikipedia.org/wiki/Race_condition" rel="noreferrer" title="Race Condition">Race Condition</a>).</p> <p>I then thought that i might be able to do the following ...</p> <pre><code>INSERT INTO Words (Word) SELECT @Word WHERE NOT EXISTS (SELECT WordID FROM Words WHERE Word = @Word) </code></pre> <p>basically, <em>insert a word when it doesn't exist.</em></p> <p>Bad syntax aside, i'm not sure if this is bad or good because of how it locks down the table (if it does) and is not that performant on a table that it getting massive reads and plenty of writes.</p> <p>So - what do you Sql gurus think / do?</p> <p>I was hoping to have a simple insert and 'catch' that for any errors thrown.</p>
<p>Your solution:</p> <pre><code>INSERT INTO Words (Word) SELECT @Word WHERE NOT EXISTS (SELECT WordID FROM Words WHERE Word = @Word) </code></pre> <p>...is about as good as it gets. You could simplify it to this:</p> <pre><code>INSERT INTO Words (Word) SELECT @Word WHERE NOT EXISTS (SELECT * FROM Words WHERE Word = @Word) </code></pre> <p>...because EXISTS doesn't actually need to return any records, so the query optimiser won't bother looking at which fields you asked for.</p> <p>As you mention, however, this isn't particularly performant, because it'll lock the whole table during the INSERT. Except that, if you add a unique index (it doesn't need to be the primary key) to Word, then it'll only need to lock the relevant pages.</p> <p>Your best option is to simulate the expected load and look at the performance with SQL Server Profiler. As with any other field, premature optimisation is a bad thing. Define acceptable performance metrics, and then measure before doing anything else.</p> <p>If that's still not giving you adequate performance, then there's a bunch of techniques from the data warehousing field that could help.</p>
<pre><code>declare @Error int begin transaction INSERT INTO Words (Word) values(@word) set @Error = @@ERROR if @Error &lt;&gt; 0 --if error is raised begin goto LogError end commit transaction goto ProcEnd LogError: rollback transaction </code></pre>
33,592
<p>This may not be strictly programming related but more OS-structure related.</p> <p>Running Vista 32 bit on a brand new laptop with 3GB of memory, Running idle the system consumes about 40% of its memory. Other then the fact that this is outrageous on its own right, the OS <strong>should be able to fit all of the processes nicely into memory</strong> and not need to swap to disk EVER.<br> Yet looking at the task manager I see processes having page faults all the time. Not many but still. for instance explorer.exe has one every second approximately.</p> <p>Why is that? Why does the OS feel the need to swap out pages although it has plenty of physical memory?</p>
<p>A page fault doesn't necessarily mean that something was paged to disk. A modern OS has many levels of state that a page might be in, for example Windows will probably distinguish between a page of memory that is being actively used, and a page of memory that hasn't been touched in a while and could be paged to disk if needed. (This makes the pager's job easier, because it only has to look at the second kind of page to find out which ones it can page.) Now, how does a page get from the second state back to the first one? The kernel sets a bit on that page indicating that if anything accesses it, then the page will be marked as "active" and moved back to the first state. This results in a page fault.</p> <p>Other things that might cause a page fault are things like memory mapped files. An application requests that a file be mapped to memory, that is it just <em>appears</em> in memory whenever the app wants to read from it. Obviously it would be tremendously expensive to load the whole file into memory all at once, so the kernel just marks the memory space with the "please page fault if this is ever accessed" bit, and reads from the disk if the app ever touches that page.</p> <p>The real situation is a lot more complex than the above, but that should give you a general idea of what might be going on.</p>
<p>Of course Vista uses the memory your computer has to boot and run faster. It will release/swap the memory when some other program needs it.</p> <p>Why not use the ressource if it is there and available and can be released later on without problems?</p> <p>About the page faults, see this explanation, the task manager creates those: <a href="http://blogs.msdn.com/oldnewthing/archive/2008/08/21/8880075.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/oldnewthing/archive/2008/08/21/8880075.aspx</a> </p> <p>(short abstract, there is one page fault every time the task manager updates the system tray icon. Set the task managers update speed to high, you'll get even more page faults. No memory is swapped on these page faults)</p>
23,100
<p>If you try to launch a .NET 3.5 application on a Windows computer which does not have this version of the .NET framework installed, you get a <code>FileNotFoundException</code> for some system assemblies (for example System.Core 3.5.0.0).</p> <p>Is it possible to catch this exception and tell the user to upgrade their .NET framework or is it thrown too early to handle it?</p>
<p>How are you currently deploying the app? ClickOnce can do assembly (GAC) checks before launch, and with msi you should have a whole range of pre-check options available... although not always feasible, you might consider one of these deployment options?</p> <p>Re catching the exception - just be sure to split the Main up so that it does <em>nothing</em> except catch the exception - otherwise JIT can stop your Main from loading:</p> <pre><code>// [STAThread] here if winform [MethodImpl(MethodImplOptions.NoInlining)] static void Main() { try { MainCore(); } catch (SomeException ex) { // TODO something simple but fun } } static void MainCore() { ... } // your app here... </code></pre> <p>If you put too much in the outer Main, it can barf before running <em>any</em> of it, since JIT might need the types.</p>
<p>The simplest thing would just be to try it. (I don't have any non-3.5 machines to test it on, but I assume you do.)</p> <p>Make your entry point a very simple one which just tries to load <code>System.Core.dll</code> and handles the exception appropriately. If it passes, move on to another class which can then use it. If it fails, give the appropriate error message and exit.</p> <p>I <em>suspect</em> you don't need to have quite this level of isolation - so long as you don't have any fields which are of unavailable types, I wouldn't expect the assembly to be resolved until you first call a method which needs it. I'd have to consult CLR via C# to check. However, keeping it quite isolated would probably be safer - it avoids you accidentally introducing dependencies later. Heck, you could even have your "boot and check" type in a separate assembly which did nothing but launch another one if everything's okay.</p>
37,708
<p>I am trying to rename all the files present in a Windows directory using <strong>FOR</strong> command as follows at the command prompt:</p> <pre><code>for %1 in (*.*) do ren %1 test%1 </code></pre> <p>E.g. This renames a file <strong>enc1.ctl</strong> to <strong>testenc1.ctl</strong> <strong>enc2.ctl</strong> to <strong>testenc2.ctl</strong> </p> <p>Thats not what i want. What i want is <strong>enc1.ctl</strong> renamed to <strong>test1.ctl</strong> <strong>enc2.ctl</strong> renamed to <strong>test2.ctl</strong> </p> <p>How do i do that?</p> <hr> <p>@Akelunuk: Thanks, that w kind of works but i have files names as </p> <p><strong>h263_enc_random_pixels_1.ctl , h263_enc_random_pixels_2.ctl</strong> which i want to rename to</p> <p><strong>test1.ctl and test2.ctl</strong> respectively </p> <p>Then how?</p>
<p>If you know the number of files, (say 10), you can use</p> <pre><code>for /L %1 in (1,1,10) do ren enc%1.ctl test%1.ctl </code></pre>
<p>This renames all files in directory for filter file types with PREFIX and today's date and time</p> <pre><code>@echo ON cls for %%a in (*.pdf) do (set myfiledate=%%~ta echo !myfiledate!) echo Date format = %myfiledate% echo dd = %myfiledate:~0,2% echo mm = %myfiledate:~3,2% echo yyyy = %myfiledate:~6,4% echo. echo Time format = %myfiledate% echo hh = %myfiledate:~11,2% echo mm = %myfiledate:~14,2% echo AM = %myfiledate:~17,2% echo. echo Timestamp = %myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2% ECHO "TEST..." &gt; "test-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%.txt" PAUSE </code></pre> <p>This echos successfuly the date modified and time as a postfix but doesnt parse the info into the rename. I cant figure out why, but it is very close. Maybe someone cant tweak to suit your purpose.</p> <pre><code>@echo ON setlocal cls for %%a in (*.pdf) do (set myfiledate=%%~ta echo !myfiledate!) :DATETIME echo Date format = %myfiledate% echo dd = %myfiledate:~0,2% echo mm = %myfiledate:~3,2% echo yyyy = %myfiledate:~6,4% echo Time format = %myfiledate% echo hh = %myfiledate:~11,2% echo mm = %myfiledate:~14,2% echo AM = %myfiledate:~17,2% = %myfiledate:~17,2% echo. echo Timestamp = %myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2% ECHO "TEST..." &gt; "test-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%.txt" for /f "delims=" %%a in ('dir *.pdf /t:a /a:-d /b /s') do call :RENAME "%%a" :RENAME REM for /f "tokens=1-6 delims=/ " %%a in ('dir %%a /t:w^|find "/"') do ( ren %%a "3DC-test-OFF-ELE-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%~x1") PAUSE GOTO :EOF </code></pre>
23,235
<p>So, I have 2 database instances, one is for development in general, another was copied from development for unit tests.</p> <p>Something changed in the development database that I can't figure out, and I don't know how to see what is different.</p> <p>When I try to delete from a particular table, with for example:</p> <pre><code>delete from myschema.mytable where id = 555 </code></pre> <p>I get the following normal response from the unit test DB indicating no row was deleted:</p> <blockquote> <p>SQL0100W No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table. SQLSTATE=02000</p> </blockquote> <p>However, the development database fails to delete at all with the following error:</p> <blockquote> <p>DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0440N No authorized routine named "=" of type "FUNCTION" having compatible arguments was found. SQLSTATE=42884</p> </blockquote> <p>My best guess is there is some trigger or view that was added or changed that is causing the problem, but I have no idea how to go about finding the problem... has anyone had this problem or know how to figure out what the root of the problem is?</p> <p>(note that this is a DB2 database)</p>
<p>Hmm, applying the great oracle to this question, I came up with:</p> <p><a href="http://bytes.com/forum/thread830774.html" rel="nofollow noreferrer">http://bytes.com/forum/thread830774.html</a></p> <p>It seems to suggest that another table has a foreign key pointing at the problematic one, when that FK on the other table is dropped, the delete should work again. (Presumably you can re-create the foreign key as well)</p> <p>Does that help any?</p>
<p>You might have an open transaction on the dev db...that gets me sometimes on SQL Server</p>
7,634
<p>Does anyone have some sample code showing how to POST to a URL using wxWidgets? The documentation and discussion forums imply that it's possible but the methods in wxHTTP are very low-level compared to what you find in .NET and scripting languages like Perl and Ruby. Do I actually have to create the HTTP request myself and send it to the server via the SocketOutputStream? Am I missing something?</p>
<p>I came across a similar problem initially and ended up using Curl instead as it's also cross platform and is very easy to use.</p> <p>Tim</p>
<p>Atually, same here. Tried using wxHTTP and ended up using Curl. And Curl is a charm to work with...</p> <p>J-O</p>
36,928
<p>I'm new to ASP.NET MVC so this may be a stupid question.</p> <p>I have an account object that has many parameters. I've figured out a strategy to break this down into a "wizard"-like interface that will walk a user through collecting the required fields to create the initial business objects. It will then step through pages to collect other, optional, parameters. This way the user isn't faced with a single page on which they have to enter 30 things (I'm probably exaggerating the number, but you get the idea).</p> <p>Still, the first page is going to have 10-12 items that the user needs to fill out before I can fill in all the required fields on the 2-3 business objects that accompany a successful registration. Basically, a new user needs to both get an account AND register for an event at the same time, thus the number of items.</p> <p>In ASP.NET MVC it appears that all of my form parameters map onto method parameters in the controller method. Knowing that methods with lots of parameters are considered a <em>code smell</em> that ought to be refactored out, I'm wondering if there is a different way to accomplish this or if I'm stuck with a controller method that has a one-to-one mapping between form parameters and method parameters.</p> <p>Is there a good known pattern that I've missed in my Google searches to solve this problem?</p>
<p>Have a look at Scott Gu's post on <a href="http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx" rel="nofollow noreferrer">form posting scenarios</a>. In particular you want to look at model binders.</p>
<p>There is always the old...</p> <pre><code>Request.Form("key"); </code></pre>
31,299
<p>I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method)</p> <p>I am currently doing this by exposing the following JavaScript method:</p> <pre><code>function doScript(js){ eval(js);} </code></pre> <p>I can then do something like this in Flex (note: I am doing something more substantial then an alert box in the real Flex app):</p> <pre><code>ExternalInterface.call("doScript","alert('foo')); </code></pre> <p>My question is does this impose any security risk, I am assuming it's not since the Flex and JasvaScript all run client side...</p> <p>Is there a better way to do this?</p>
<p>There's no need for the JavaScript function, the first argument to <code>ExternalInterface</code> can be any JavaScript code, it doesn't have to be a function name (the documentation says so, but it is wrong).</p> <p>Try this:</p> <pre><code>ExternalInterface.call("alert('hello')"); </code></pre>
<pre><code>ExternalInterface.call("eval", "alert('hello');"); </code></pre>
4,086
<p>I have searched the forum, and google for this topic. Most of the articles are talking about using JSON to call the controller/action on the server and do ajax effect on the result.</p> <p>I am trying to use some very basic JQuery features, like the JQuery UI/Tabs, and JQuery UI/Block for a dialog window. I cannot get these simple samples to work in my MVC project. Any ideas how I should modify these samples? I only need these basic feature now and I can go from here.</p> <p>Thanks!</p>
<p>Actually I just got it working. The problem is that I need to modify the path to an absolute path to the view page because the relative path doesn't work with the MVC routes {controller}/{action}/{id}.</p> <p>Thanks!</p>
<p>I just implemented the jquery autocomplete textbox in one of my asp.net project. I only had to import the js file and drop some code into my aspx page. Could you be more detailled about what sample you are trying to run?</p>
12,043
<p>I would like to migrate from Oracle to MySQL, and one of the important steps is to replace the actual job built on an Oracle environment.</p> <p>Basically, every day I receive some 'oracle' dump files from another Oracle environment (mainly CTL or Oracle table exports). Today my Oracle jobs loaded the received data (CTL...) in my Oracle tables. Now I would like to replace my Oracle tables in MySQL tables, continuing to receive the file coming from the Oracle environment.</p> <p>So. Do you have same tools or artifacts to read the Oracle CTL files (or Oracle tables dump) from an MySQL environment? I already used the mysqlimport GUI, but it does not meet my needs. I need the script/command to do these.</p>
<p>I think it's because the matching starts at the first character and moves on from there... </p> <p>For your first regular expression:</p> <pre><code>Does "AMEVDIEERPK + 7 Oxidation (M)" match "\s*(\d*).*?Oxidation\s+(M)"? Yes.. stop matching. </code></pre> <p>For your second regular expression:</p> <pre><code>Does "AMEVDIEERPK + 7 Oxidation (M)" match "\s*(\d*)\s*Oxidation\s+(M)"? No... Does "MEVDIEERPK + 7 Oxidation (M)" match "\s*(\d*)\s*Oxidation\s+(M)"? No... Does "EVDIEERPK + 7 Oxidation (M)" match "\s*(\d*)\s*Oxidation\s+(M)"? No... ... Does " 7 Oxidation (M)" match "\s*(\d*)\s*Oxidation\s+(M)"? Yes </code></pre> <p>If for the first regular expression you'd used <code>\d+</code> instead of <code>\d*</code> you'd have got a better result.</p> <p>This is not <em>exactly</em> how regular expressions work, but you get the idea.</p>
<p>". * ?" in this example will always match zero characters, since "* ?" does shortest possible match. As a result, since the thing right before the 'O' is a space, "\ d *" can match 0 digits.</p> <p>(Sorry about the spaces in the quotes; the auto-formatter was eating my syntax.)</p> <p>Reference: <em><a href="http://msdn.microsoft.com/en-us/library/3206d374.aspx" rel="nofollow noreferrer">Quantifiers in Regular Expressions</a></em> (MSDN)</p>
43,233
<p>I need to implement the classic Factory Method pattern in ASP.NET to create server controls dynamically.</p> <p>The only way I've found to create .ascx controls is to use the LoadControl method of the Page/UserControl classes. I find it messy however to link my factory with a page or to pass a page parameter to the factory.</p> <p>Does anybody know of another method to create such controls (such as a static method somewhere i'd have overlooked) ?</p> <p>Thanks.</p>
<p>In the end, I decided to pass the page as a parameter to the factory. To make calls to the factory method easier, I changed the factory class from a singleton to a common class, and I passed the page to the constructor:</p> <pre><code>public ControlsFactory { private Page _containingPage; public ControlsFactory(Page containingPage) { _containingPage = containingPage; } public CustomControlClass GetControl(string type) { ... snip ... CustomControlClass result = (CustomControlClass)_containingPage.LoadControl(controlLocation); return result; } } </code></pre> <p>Since I have to instantiate many controls on each page with the factory, this is probably the most concise and usable way to implement the pattern.</p>
<p>Well after opening up reflector, the LoadControl function that is being used in Page is available in any TemplateControl.</p> <p>Inside the actual LoadControl uses internal methods in BuildManager, so I don't think there's a way to use static methods without using reflection.</p> <p>Well at least you don't need to pass a page around. Subclassing TemplateControl would work.</p>
35,181
<p>Is there a tool which tells you (or gives you a hint) why a particular select statement dose not return any rows given the current data in your database. </p> <p>eg if you had the following 4 table join</p> <pre><code>select * from a, b, c, d where a.b_id = b.id and b.c_id = c.id and c.d_id = d.id </code></pre> <p>If there were rows which satisfied the conditions a.b_id = b.id also rows which satisfied b.c_id = c.id but no rows which satisfied the condition c.d_id = d.id it would highlight c.d_id = d.id as the problem.</p> <p>Ie it would brake up the where clause and find out which of the sub conditions returned true and highlight those which do not return true.</p> <p>It would not work well for complex querys but many select statements are simple joins over lots of tables.</p> <p>This would be useful when creating test data to exercise a peace of application code or debugging a problem with a live system.</p> <p>Graphical explain tools (that show the plan of the actual exiection path) come close but they show too much info and do not highlight the missing link in the select stament.</p> <p>I am using postgres, sqllight and mysql but would be interested in how tools for other databases/platforms work. </p> <p>Im also interested in any manula techniques.</p> <p>Does anybody else have this problem?</p> <p>Would anybody be interested if I wrote such a tool?</p>
<p>I never have this problem, but I also use explicit joins so it's usually as simple as running parts of the query until I find out which one is restricting my results incorrectly.</p> <p>In your case</p> <pre><code>SELECT * FROM a -- First run just to here, are there records? INNER JOIN b ON a.b_id = b.id -- Then run just to here, is it OK? INNER JOIN c ON b.c_id = c.id -- Then run just to here, is it OK? INNER JOIN d ON c.d_id = d.id -- Then run just to here, is it OK? </code></pre>
<p>You should be able to study the execution plan (if you are using SQL Server, otherwise a similar feature in your database) to see where the joins produce an empty set. </p>
38,029
<p>Since C# is strongly typed, do we really need to prefix variables anymore?</p> <p>e.g.</p> <pre><code>iUserAge iCounter strUsername </code></pre> <p>I used to prefix in the past, but <b>going forward I don't see any benefit</b>.</p>
<blockquote> <p>Are variable prefixes ( Hungarian ) really necessary anymore?</p> </blockquote> <h1>NO!</h1> <p>In fact, Microsoft's own <a href="http://msdn.microsoft.com/en-us/library/ms229042.aspx" rel="noreferrer">style guidelines</a> (where the practice originated) now recommend against it. In particular, see the section on <a href="http://msdn.microsoft.com/en-us/library/ms229045.aspx" rel="noreferrer">General Naming Conventions</a>, which includes the following text (in bold type, no less):</p> <blockquote> <p><strong>Do not use Hungarian notation.</strong></p> </blockquote> <p>Of course, these guidelines are not binding or mandatory outside of Microsoft. However, this is the published recommendation of the platform vendor, and it goes beyond merely removing the positive recommendation from any prior guide, to instead a strongly-worded and emphasized negative recommendation today.</p> <p>In other words, don't use them anymore.</p>
<p>No, if your methods are so long that you cant read the definition at the same time as the use, or the name doesnt imply the type then you have more serious design issues than just naming.</p> <p>However, i INSIST that you do prefix controls with their type, such as txtName.</p>
39,840
<p>What is meant by "Constant Amortized Time" when talking about time complexity of an algorithm?</p>
<p>Amortised time explained in simple terms:</p> <p>If you do an operation say a million times, you don't really care about the worst-case or the best-case of that operation - what you care about is how much time is taken in total when you repeat the operation a million times.</p> <p>So it doesn't matter if the operation is very slow once in a while, as long as "once in a while" is rare enough for the slowness to be diluted away. Essentially amortised time means "average time taken per operation, if you do many operations". Amortised time doesn't have to be constant; you can have linear and logarithmic amortised time or whatever else.</p> <p>Let's take mats' example of a dynamic array, to which you repeatedly add new items. Normally adding an item takes constant time (that is, <code>O(1)</code>). But each time the array is full, you allocate twice as much space, copy your data into the new region, and free the old space. Assuming allocates and frees run in constant time, this enlargement process takes <code>O(n)</code> time where n is the current size of the array.</p> <p>So each time you enlarge, you take about twice as much time as the last enlarge. But you've also waited twice as long before doing it! The cost of each enlargement can thus be "spread out" among the insertions. This means that in the long term, the total time taken for adding <em>m</em> items to the array is <code>O(m)</code>, and so the amortised time (i.e. time per insertion) is <code>O(1)</code>.</p>
<p>Amortized Running Time: This refers to the calculation of the algorithmic complexity in terms of time or memory used <strong>per operation</strong>. It's used when mostly the operation is fast but on some occasions the operation of the algorithm is slow. Thus sequence of operations is studied to learn more about the amortized time.</p>
24,441
<p>I cant' figure out how to reference the current instance object defined by the XAML file in the XAML file.</p> <p>I have a converter that I want to send in the current instance as the parameter object.</p> <pre><code>{Binding Path=&lt;bindingObject&gt;, Converter={x:Static namespace:Converter.Instance}, ConverterParameter=this} </code></pre> <p>In this code this is converted to a string instead of a reference to the current instance object.</p> <p>Thanks</p> <p>John</p>
<p>According to the <a href="http://msdn.microsoft.com/en-us/library/ms752347.aspx#current_record_pointers" rel="nofollow noreferrer">Data Binding Overview</a>, you can use the "/" to indicate the current item. You can then navigate up and down the tree as needs be using the following type syntaxes:</p> <pre><code>&lt;Button Content="{Binding }" /&gt; &lt;Button Content="{Binding Path=/}" /&gt; &lt;Button Content="{Binding Path=/Description}" /&gt; </code></pre>
<p>Have you tried using the <a href="http://msdn.microsoft.com/en-us/library/ms743599.aspx" rel="nofollow noreferrer"><code>RelativeSource</code> markup extension</a>? You can use <code>Self</code> there.</p>
28,633
<p>Given a path such as <code>&quot;mydir/myfile.txt&quot;</code>, how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:</p> <pre><code>&quot;C:/example/cwd/mydir/myfile.txt&quot; </code></pre>
<pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.abspath("mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt' </code></pre> <p>Also works if it is already an absolute path:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.abspath("C:/example/cwd/mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt' </code></pre>
<p>In case someone is using python and linux and looking for full path to file:</p> <pre><code>&gt;&gt;&gt; path=os.popen("readlink -f file").read() &gt;&gt;&gt; print path abs/path/to/file </code></pre>
7,460
<p>I'd like to use regular expressions in selecting elements using the match function. I'd prefer not to use an external library (such as saxon) to do this. </p>
<p>There are some things in XSLT 2.0 that aren't supported in the built in libraries (there was discussion on the mono mailing list about this but I can't find the information anymore). But most people never run into the corner cases that aren't supported.</p> <p>Another option is to check out the open source <a href="http://saxon.sourceforge.net/" rel="nofollow noreferrer">http://saxon.sourceforge.net/</a> which has great support for 2.0.</p> <p><strong><em>EDIT (AB): the above accepted answer may be confusing. There's no support at all and there are <a href="https://stackoverflow.com/questions/1525299/xpath-and-xslt-2-0-for-net">no plans in that direction</a> for any of the XPath 2.0 or XSLT 2.0 functions in .NET.</em></strong></p>
<p>Yes, 3.5 XPathNavigator supports XSLT 2.0.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx</a></p> <p>"The XPathNavigator class in the System.Xml.XPath namespace is an abstract class which defines a cursor model for navigating and editing XML information items as instances of the XQuery 1.0 and XPath 2.0 Data Model."</p>
11,968
<p>If I were looking to create my own language are there any tools that would help me along? I have heard of yacc but I'm wondering how I would implement features that I want in the language.</p>
<p>The first tool I would recommend is the Dragon Book. That is the reference for building compilers. Designing a language is no easy task, implementing it is even more difficult. The dragon book helps there. The book even reference to the standard unix tools lex and yacc. The gnu equivalent tools are called flex and bison. They both generate lexer and parser. There exist also more modern tools for generating lexer and parser, e.g. for java there are ANTLR (I also remember javacc and CUP, but I used myself only ANTLR). The fact that ANTLR combines parser and lexer and that eclipse plugin is availabe make it very comfortable to use. But to compare them, the type of parser you need, and know for what you need them, you should read the Dragon book. There are also other things you have to consider, like runtime environment, programming paradigm, ....</p> <p>If you have already certain design ideas and need help for a certain step or detail the anwsers could be more helpful.</p>
<p>I never finished the complete language, I had used rply and llvmlite implements a simple foxbase language, in <a href="https://github.com/acekingke/foxbase_compiler" rel="nofollow noreferrer">https://github.com/acekingke/foxbase_compiler</a></p> <p>so if you want use python, <code>rply</code> or <code>llvmlite</code> is helpful. if you want use golang, <code>goyacc</code> maybe useful. But you should write a lexical analyzer by hard coding by hand. Or you can use <a href="https://github.com/acekingke/lexergo" rel="nofollow noreferrer">https://github.com/acekingke/lexergo</a> to simplify it.</p>
47,731
<p>Can someone show me a regex to select <strong>#OnlinePopup_AFE53E2CACBF4D8196E6360D4DDB6B70</strong> its okay to assume <code>#OnlinePopup</code></p> <pre><code>~DCTM~dctm://aicpcudev/37004e1f8000219e?DMS_OBJECT_SPEC=RELATION_ID#OnlinePopup_AFE53E2CACBF4D8196E6360D4DDB6B70_11472026_1214836152225_6455280574472127786 </code></pre>
<p>NB: The following is .NET Regex syntax, modify for your flavour.</p> <p>The following:</p> <pre><code>#[^_]+_[^_]+ </code></pre> <p>will match:</p> <ul> <li>Hash</li> <li>One or more characters until an underscore</li> <li>Underscore</li> <li>One or more characters until an underscore</li> </ul> <p>If the first bit is constant, and you want to be more specific you could use:</p> <pre><code>#OnlinePopup_[A-F0-9]+ </code></pre> <p>This will match</p> <ul> <li><h1>OnlinePopup_ (exactly)</h1> </li> <li>One or more hex characters until a non Hex character</li> </ul>
<p>Simply matching anything between the first '#' and the first or last '_' will not work for your example since the string that you want returned has an underscore in it. If all the text that you want to match has only <strong>one</strong> underscore in it, you could use this regex:</p> <pre><code>/(#[^_]+_[^_]+)/ </code></pre> <p>This matches an octothorpe (#), followed by two strings that do not contain an underscore, seperated by a single underscore.</p>
38,052
<p>In standard php or source code based projects we easily keep all of the code in SVN and each developer can checkout their own copy and collaborate on the same code. </p> <p>When developing a Drupal site however, much of the work is in "setup". Besides the theme and modules you don't really have any "source code". How do you run multiple instances of the same site so developers can all work at the same time yet share their work?</p> <p>Example Scenario:</p> <p>We launch an initial version of a Drupal site with content type "X" created. We also initially launch a view on the site that lists all the nodes of type "X" in chronological order. The client starts using the site, add content, menu items etc.</p> <p>The next release is planned to add user search ability to that view. The setup for that is contained in the database though. We can copy down the production database to our development version to get the latest data while we work on changing the view. During that time however the client can still be updating the site, making our dev database out of sync. When we are ready to push the new view to production, is there an easier way to do it other than manually repeat the steps to set it up on the production install?</p>
<p>I think a good strategy here is to use the install profile API. With install profile API you can do most things that using the Drupal admin tools do. Most core forms simply set variables in the variables table. To be able to sensibly version your non content database contents i.e. configuration it is wise to use update functions.</p> <p>On my site we have on module "ec" that does very little apart from have it's ec.install file contain update functions e.g. ec_update_6001()</p> <p>Your main install function can take care of actually running the updates on any new installs you make to bring your modules up to date.</p> <pre><code>function ec_install() { $ret = array(); $num = 0; while (1) { $version = 6000 + $num; $funcname = 'ec_update_' . $version; if (function_exists($funcname)) { $ret[] = $funcname(); $num++; } else { break; } } return $ret; } </code></pre> <p>A sample update function or two from our actual file now follow</p> <pre><code>// Create editor role and set permissions for comment module function ec_update_6000() { install_include(array('user')); $editor_rid = install_add_role('editor'); install_add_permissions(DRUPAL_ANONYMOUS_RID, array('access comments')); install_add_permissions(DRUPAL_AUTHENTICATED_RID, array('access comments', 'post comments', 'post comments without approval')); install_add_permissions($editor_rid, array('administer comments', 'administer nodes')); return array(); } // Enable the pirc theme. function ec_update_6001() { install_include(array('system')); // TODO: line below is not working due to a bug in Install Profile API. See http://drupal.org/node/316789. install_enable_theme('pirc'); return array(); } // Add the content types for article and mtblog function ec_update_6002() { install_include(array('node')); $props = array( 'description' =&gt; 'Historical Movable Type blog entries', ); install_create_content_type('mtblog', 'MT Blog entry', $props); $props = array( 'description' =&gt; 'Article', ); install_create_content_type('article', 'Article', $props); return array(); } </code></pre> <p>Effectively this mostly solves the versioning problem with databases and Drupal code. We use it extensively. It allows us to promote new code which changes database configuration without having to reimport the database or make live changes. This also means we can properly test releases without fear of hidden database changes.</p> <p>Finally cck and views support this approach. See this code snippet</p> <pre><code>// Enable CCK modules, add CCK types for Articles in prep for first stage of migration, // enable body for article, enable migration modules. function ec_update_6023() { $ret = array(); drupal_install_modules(array('content', 'content_copy', 'text', 'number', 'optionwidgets')); install_include(array('content', 'content_copy')); install_content_copy_import_from_file(drupal_get_path('module', 'ec') . '/' . 'article.type', 'article'); $sql = "UPDATE {node_type} SET body_label='Body', has_body=1 WHERE type = 'article'"; $ret[] = update_sql($sql); return $ret; } </code></pre>
<p>Drupal has now support for <em>exportables configuration</em> that allow you to move most of a site configuration to code. Exportables are supported for configuration variables, views, content type, fields, input formats, etc. with the help of the <a href="http://drupal.org/project/features" rel="nofollow">features</a> module.</p> <p>You can also manage initial, non exportable configuration and changes of configuration throuh a central <em>controller</em> profile, or module. Use it to enable module, create user, etc.</p> <p>See <a href="http://developmentseed.org/blog/2009/jul/09/development-staging-production-workflow-problem-drupal" rel="nofollow">The Development -> Staging -> Production Workflow Problem in Drupal</a> and the <a href="http://www.archive.org/details/CodeDrivenDevelopmentUsingFeaturesEffectivelyInDrupal6And7" rel="nofollow">Code driven development: using Features effectively in Drupal 6 and 7</a> presentation.</p>
35,834
<p>Can we access div tags of user control in Master page? I am trying to change the background color for each one of the div tags on some event.</p>
<p>Something like this should work (in C#):</p> <pre><code>Control myControl = this.Page.Master.FindControl("[Your name here]"); </code></pre> <p>Then you can do whatever you would like to the control. If it's a Panel control (for the div) you can cast it that way, or if you are using an HTML server side control, you can cast it that way.</p>
<p>The best way is to make a public property in the user control that you can then set directly from the masterpage.</p>
44,884
<p>I’ve got a problem with Visual Basic (6) in combination with LDAP. When I try to connect to an LDAP store, I always get errors like ‘Bad Pathname’ or ‘Table does not exist’ (depending on what the code looks like).</p> <p>This is the part of the code I wrote to connect:</p> <pre><code>path = "LDAP://xx.xxx.xxx.xxx:xxx/" Logging.WriteToLogFile "Test1", logINFO Set conn = CreateObject("ADODB.Connection") conn.Provider = "ADsDSOObject" conn.Properties("User ID") = "USER_ID" conn.Properties("Password") = "PASSWORD" conn.Properties("Encrypt Password") = True conn.Properties("ADSI Flag") = 34 Logging.WriteToLogFile "Test2", logINFO conn.Open "Active Directory Provider" Logging.WriteToLogFile "Test3", logINFO Set rs = conn.Execute("&lt;" &amp; path &amp; "ou=Some,ou=Kindof,o=Searchbase&gt;;(objectclass=*);name;subtree") Logging.WriteToLogFile "Test4", logINFO </code></pre> <p>The logfile shows “Test1” , “Test2”, “Test3” and then “Table does not exist”, so it’s the line “Set rs = conn.Execute(…)” where things go wrong (pretty obvious…).</p> <p>In my code, I try to connect in a secure way. I found out it has nothing to do with SSL/certificates though, because it’s also not possible to establish an anonymous unsecured connection. Funny thing is: I wrote a small test app in .NET in five minutes. With that app I was able to connect (anonymously) and read results from the LDAP store, no problems at all.</p> <p>Does anyone have any experience with the combination LDAP and VB6 and maybe know what could be the problem? I googled and saw some example code snippets, but unfortunately none of them worked (same error messages as result). Thanks in advance!</p>
<p>I'm not sure how much help this will be, but I use this code to access Active Directory objects.</p> <pre><code> Set oinfo = New ADSystemInfo sDomain = Split(oinfo.DomainDNSName, ".") '-- Get Datasets from the Active Directory '-- Connect to Active Directory in logged in domain con.Open "Provider=ADsDSOObject;Encrypt Password=False;Integrated Security=SSPI;Data Source=ADSDSOObject;Mode=Read;Bind Flags=0;ADSI Flag=-2147483648" '-- Query all serviceConnectionPoints in the Active Directory '-- that contain the keyword "urn://tavis.net/TM/Database" '-- and return the full path to the object Set rst = con.Execute("&lt;LDAP://DC=" &amp; sDomain(0) &amp; ",DC=" &amp; sDomain(1) &amp; "&gt;;(&amp;(objectCategory=serviceConnectionPoint)(keywords=urn://tavis.net/TM/Database));Name, AdsPath;subTree") </code></pre>
<p>2 things: </p> <ul> <li>The <code>Open()</code> method call takes additional parameters, server/username/password</li> <li><p>The LDAP query you passed to <code>Execute()</code> should be: </p> <pre><code>"&lt;" &amp; path &amp; "ou=Some/ou=Kindof/o=Searchbase&gt;;(objectclass=*);name;subtree" </code></pre></li> </ul>
14,001
<p>given the following code: </p> <pre><code>import ctypes ip="192.168.1.1" thisdll = ctypes.cdll['aDLL'] thisdll.functionThatExpectsAnIP(ip) </code></pre> <p>how can I correctly pack this for a DLL that expects it as a c_ulong datatype?</p> <p>I've tried using: </p> <pre><code>ip_netFrmt = socket.inet_aton(ip) ip_netFrmt_c = ctypes.c_ulong(ip_netFrmt) </code></pre> <p>however, the <code>c_ulong()</code> method returns an error because it needs an integer. </p> <p>is there a way to use <code>struct.pack</code> to accomplish this? </p>
<p>The inet_aton returns a string of bytes. This used to be the <em>lingua franca</em> for C-language interfaces.</p> <p>Here's how to unpack those bytes into a more useful value.</p> <pre><code>&gt;&gt;&gt; import socket &gt;&gt;&gt; packed_n= socket.inet_aton("128.0.0.1") &gt;&gt;&gt; import struct &gt;&gt;&gt; struct.unpack( "!L", packed_n ) (2147483649L,) &gt;&gt;&gt; hex(_[0]) '0x80000001L' </code></pre> <p>This unpacked value can be used with ctypes. The hex thing is just to show you that the unpacked value looks a lot like an IP address.</p>
<p>First a disclaimer: This is just an educated guess.</p> <p>an ip-address is traditionally represented as four bytes - i.e. xxx.xxx.xxx.xxx, but is really a unsigned long. So you should convert the representation 192.168.1.1 to an unsiged int. you could convert it like this.</p> <pre><code>ip="192.168.1.1" ip_long = reduce(lambda x,y:x*256+int(y), ip.split('.'), 0) </code></pre>
41,014
<p>Is there a fixed point in the MD5 transformation, i.e. does there exist x such that <code>md5(x) == x</code>?</p>
<p>Since an MD5 sum is 128 bits long, any fixed point would necessarily also have to be 128 bits long. Assuming that the MD5 sum of any string is uniformly distributed over all possible sums, then the probability that any given 128-bit string is a fixed point is <sup>1</sup><em>/</em><sub>2<sup>128</sup></sub>.</p> <p>Thus, the probability that no 128-bit string is a fixed point is (1 − <sup>1</sup><em>/</em><sub>2<sup>128</sup></sub>)<sup>2<sup>128</sup></sup>, so the probability that there is a fixed point is 1 − (1 − <sup>1</sup><em>/</em><sub>2<sup>128</sup></sub>)<sup>2<sup>128</sup></sup>.</p> <p>Since the limit as n goes to infinity of (1 − <sup>1</sup><em>/</em><sub>n</sub>)<sup>n</sup> is <sup>1</sup><em>/</em><sub><em>e</em></sub>, and 2<sup>128</sup> is most certainly a very large number, this probability is almost exactly 1 − <sup>1</sup><em>/</em><sub><em>e</em></sub> ≈ 63.21%.</p> <p>Of course, there is no randomness actually involved &ndash; either there is a fixed point or there isn't. But, we can be 63.21% confident that there is a fixed point. (Also, notice that this number does not depend on the size of the keyspace &ndash; if MD5 sums were 32 bits or 1024 bits, the answer would be the same, so long as it's larger than about 4 or 5 bits).</p>
<p>Probably, but finding it would take longer than we have or would involve compromising MD5.</p>
29,182
<p>I'm using JScrollPane to allow scrolling in a JFrame that has a text component that's serving as a text editor. What I want to do, after setting the text in this editor, is have it scroll back up to the top, so you can see what's at the beginning of the file.</p> <p>Does anyone know how to do this?</p>
<p>Calling <a href="http://java.sun.com/javase/6/docs/api/javax/swing/text/JTextComponent.html#setCaretPosition(int)" rel="noreferrer">setCaretPosition(0)</a> on your text component will cause it to scroll to the top.</p>
<p>Here's how:</p> <pre><code>textArea.setSelectionStart(0); textArea.setSelectionEnd(0); </code></pre>
37,125
<p>I have two tables in my database, called <em>ratings</em> and <em>movies</em>.</p> <p><strong>Ratings:</strong></p> <blockquote> <p><code>| id | movie_id | rating |</code></p> </blockquote> <p><strong>Movies:</strong></p> <blockquote> <p><code>| id | title |</code></p> </blockquote> <p>A typical movie record might be like this:</p> <blockquote> <p><code>| 4 | Cloverfield (2008) |</code></p> </blockquote> <p>and there may be several rating records for Cloverfield, like this:</p> <blockquote> <p><code>| 21 | 4 | 3 |</code> (rating number 21, on movie number 4, giving it a rating of 3)</p> <p><code>| 22 | 4 | 2 |</code> (rating number 22, on movie number 4, giving it a rating of 2)</p> <p><code>| 23 | 4 | 5 |</code> (rating number 23k on movie number 4, giving it a rating of 5)</p> </blockquote> <p><strong>The question:</strong></p> <p>How do I create a JOIN query for only selecting the rows in the movie table that have more than <code>x</code> number of ratings in the ratings table? For example, in the above example if Cloverfield only had one rating in the ratings table and <code>x</code> was 2, it would not be selected.</p> <p>Thanks for any help or advice!</p>
<p>Use the HAVING clause. Something along these lines:</p> <pre><code>SELECT movies.id, movies.title, COUNT(ratings.id) AS num_ratings FROM movies LEFT JOIN ratings ON ratings.movie_id=movies.id GROUP BY movies.id HAVING num_ratings &gt; 5; </code></pre>
<p>The above solutions are okay for the scenario you mentioned. My suggestion may be overkill for what you have in mind, but may be handy for other situations:</p> <ol> <li><p>Subquery only those from the ratings table having more than the number you need (again using tha group by having clause):</p> <p>select movie_id from ratings group by movie_id having count (*) > x</p></li> <li><p>Join that subquery with the movies table</p> <p>select movies.id from movies join as MoviesWRatings on movies.id = MoviesWRatings.movie_id</p></li> </ol> <p>When you're doing more stuff to the subquery, this might be helpful. (Not sure if the syntax is right for MySQL, please fix if necessary.)</p>
21,174
<p>I'm testing how the classes FileStream and StreamReader work togheter. Via a Console application. I'm trying to go in a file and read the lines and print them on the console.</p> <p>I've been able to do it with a while-loop, but I want to try it with a foreach loop.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace testing { public class Program { public static void Main(string[] args) { string file = @"C:\Temp\New Folder\New Text Document.txt"; using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { using(StreamReader sr = new StreamReader(fs)) { foreach(string line in file) { Console.WriteLine(line); } } } } } } </code></pre> <p>The error I keep getting for this is: Cannot convert type 'char' to 'string'</p> <p>The while loop, which does work, looks like this:</p> <pre><code>while((line = sr.ReadLine()) != null) { Console.WriteLine(line); } </code></pre> <p>I'm probably overlooking something really basic, but I can't see it.</p>
<p>To read all lines in New Text Document.txt:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace testing { public class Program { public static void Main(string[] args) { string file = @"C:\Temp\New Folder\New Text Document.txt"; using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { using(StreamReader sr = new StreamReader(fs)) { while(!sr.EndOfStream) { Console.WriteLine(sr.ReadLine()); } } } } } } </code></pre>
<p>You are enumerating a string, and when you do that, you take one char at the time.</p> <p>Are you sure this is what you want?</p> <pre><code>foreach(string line in file) </code></pre>
36,413
<p>What is the easiest way to create and verify PGP/GPG signatures from within a Python application? </p> <p>I can call pgp or gpg using subprocess and parse the output, but I was looking for a way that didn't require an external program to be installed (my application is cross-platform mac/windows/unix).</p>
<p>I think <a href="http://www.gnupg.org/related_software/gpgme/" rel="nofollow noreferrer">GPGME</a> and the <a href="http://pyme.sourceforge.net/" rel="nofollow noreferrer">PyMe Python wrapper</a> should do what you need.</p>
<p>In addition to PyMe, consider <a href="http://code.google.com/p/python-gnupg/" rel="nofollow">python-gnupg</a> and the <a href="http://py-gnupg.sourceforge.net/" rel="nofollow">gnupginterface</a>.</p>
6,113
<p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p> <pre><code>def _dir_list(self, dir_name, whitelist): outputList = [] for root, dirs, files in os.walk(dir_name): for f in files: if os.path.splitext(f)[1] in whitelist: outputList.append(os.path.join(root, f)) else: self._email_to_("ignore") return outputList </code></pre>
<p>Don't use os.walk.</p> <p>Example:</p> <pre><code>import os root = "C:\\" for item in os.listdir(root): if os.path.isfile(os.path.join(root, item)): print item </code></pre>
<p>This is how I solved it</p> <pre><code>if recursive: items = os.walk(target_directory) else: items = [next(os.walk(target_directory))] ... </code></pre>
28,369
<p>Is there a way with WPF to get an array of elements under the mouse on a MouseMove event?</p>
<p>You can also try using the Mouse.DirectlyOver property to get the top-most element that is under the mouse.</p>
<p>Can you use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.visualtreehelper.hittest.aspx" rel="nofollow noreferrer">VisualTreeHelper.HitTest</a> ?</p> <p><a href="http://lukieb.blogspot.com/2008/07/visualtreehelperhittest.html" rel="nofollow noreferrer">http://lukieb.blogspot.com/2008/07/visualtreehelperhittest.html</a></p>
6,782
<p>I have a Visual Studio 2008 solution with several projects in it - some of which are web applications / sites. </p> <p>Whenever I go "Debug > Start new instance" for a specific web application and VS launches the ASP.net Development Server (WebDev.WebServer.EXE) for that application, VS also launches 3 additional such processes - one for each of 3 other web applications I have in the solution.</p> <p>How can I tell Visual Studio to only launch WebDev for the one project I'm debugging? I've looked both in the project configurations and in the solution configuration and could not find the relevant setting... </p>
<p>I think it runs one for each Port -- you can try turning setting them to have the same port - click on the project and look at the properties pane (you have to turn off the the automatic port generation and then set the port#)</p>
<p>Suggestion - don't use the internal WebDev, use IIS instead. Also reduces the clutter in the systray. ;)</p>
42,605
<p>I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?</p>
<p><strong>Here is a small trick that I use in JAVA to replicate C++ friend mechanism.</strong></p> <p>Lets say I have a class <code>Romeo</code> and another class <code>Juliet</code>. They are in different packages (family) for hatred reasons.</p> <p><code>Romeo</code> wants to <code>cuddle</code> <code>Juliet</code> and <code>Juliet</code> wants to only let <code>Romeo</code> <code>cuddle</code> her.</p> <p>In C++, <code>Juliet</code> would declare <code>Romeo</code> as a (lover) <code>friend</code> but there are no such things in java.</p> <p>Here are the classes and the trick :</p> <p>Ladies first :</p> <pre class="lang-java prettyprint-override"><code>package capulet; import montague.Romeo; public class Juliet { public static void cuddle(Romeo.Love love) { Objects.requireNonNull(love); System.out.println("O Romeo, Romeo, wherefore art thou Romeo?"); } } </code></pre> <p>So the method <code>Juliet.cuddle</code> is <code>public</code> but you need a <code>Romeo.Love</code> to call it. It uses this <code>Romeo.Love</code> as a "signature security" to ensure that only <code>Romeo</code> can call this method and checks that the love is real so that the runtime will throw a <code>NullPointerException</code> if it is <code>null</code>.</p> <p>Now boys :</p> <pre class="lang-java prettyprint-override"><code>package montague; import capulet.Juliet; public class Romeo { public static final class Love { private Love() {} } private static final Love love = new Love(); public static void cuddleJuliet() { Juliet.cuddle(love); } } </code></pre> <p>The class <code>Romeo.Love</code> is public, but its constructor is <code>private</code>. Therefore anyone can see it, but only <code>Romeo</code> can construct it. I use a static reference so the <code>Romeo.Love</code> that is never used is only constructed once and does not impact optimization.</p> <p>Therefore, <code>Romeo</code> can <code>cuddle</code> <code>Juliet</code> and only he can because only he can construct and access a <code>Romeo.Love</code> instance, which is required by <code>Juliet</code> to <code>cuddle</code> her (or else she'll slap you with a <code>NullPointerException</code>).</p>
<p>I once saw a reflection based solution that did "friend checking" at runtime using reflection and checking the call stack to see if the class calling the method was permitted to do so. Being a runtime check, it has the obvious drawback.</p>
22,027
<p>I'm using a build script that calls Wise to create some install files. The problem is that the Wise license only allows it to be run under one particular user account, which is not the same account that my build script will run under. I know Windows has the <strong>runas</strong> command but this won't work for an automated script as there is no way to enter the password via the command line.</p>
<p>This might help: <a href="http://blogs.msdn.com/oldnewthing/archive/2004/11/29/271551.aspx" rel="nofollow noreferrer">Why doesn't the RunAs program accept a password on the command line?</a></p>
<p>This might help, it's a class I've used in another project to let people make their own accounts; everyone had to have access to the program, but the same account couldn't be allowed to have access to the LDAP stuff, so the program uses this class to run it as a different user.</p> <p><a href="http://www.codeproject.com/KB/dotnet/UserImpersonationInNET.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/dotnet/UserImpersonationInNET.aspx</a></p>
12,363
<p>Everytime I upload a file to my ASP.NET site, all users are logged out (aka, I guess their session become invalidated). </p> <p>Is there any way to "hotswap" the code in ASP.NET so that this doesn't happen? Compile before deploying etc. </p> <p>My deployment method is pretty simple through a SVN update. </p> <p>Thanks! /Niels</p>
<p>You could store your session in a <a href="http://msdn.microsoft.com/en-us/library/ms229862(VS.80).aspx" rel="nofollow noreferrer">SQL database</a>, thus the application restart would not lose your sessions.</p> <p>Having precompiled non updatable code to deploy would make your xcopy faster alright but app pool would still be restarted.</p> <p>UPDATE: @configurator, making your comment visible to any casual observers <a href="http://support.microsoft.com/kb/317604" rel="nofollow noreferrer">http://support.microsoft.com/kb/317604</a> </p> <p>(there is plenty of coverage of the different options and how-tos out there, e.g. more than one session db, different frameworks dbs in same db, etc)</p>
<p>If you're deploying files to the bin folder or the web.config, this will automatically reset the site for very good reasons.</p>
41,910
<p>I'd like to call svn up from an asp.net page so people can hit the page to update a repository. (BTW: I'm using Beanstalk.com svn hosting which doesn't allow post-commit hooks, which is why I am doing it this way). </p> <p>See what I've got below. The process starts (it shows up in Processes in Task Manager) and exits after several seconds with no output message (at least none is outputted to the page). The repository does not get updated. But it does do something with the repository because the next time I try to manually update it from the command line it says the repo is locked. I have to run svn cleanup to get it to update. </p> <p>Ideas?</p> <pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) startInfo = New System.Diagnostics.ProcessStartInfo("svn") startInfo.RedirectStandardOutput = True startInfo.UseShellExecute = False startInfo.Arguments = "up " &amp; Request.QueryString("path") pStart.StartInfo = startInfo pStart.Start() pStart.WaitForExit() Response.Write(pStart.StandardOutput.ReadToEnd()) End Sub </code></pre>
<p>You can also use the Subversion library that comes with Ankh SVN. I used it in a project to manage files in a Subversion repository and it worked well.</p> <p>If you insist on using the command line client make sure you check the StandardError output for any error messages. Also make sure the user you run the process as has the appropriate rights.</p>
<p>Using <a href="http://sharpsvn.net/" rel="nofollow noreferrer">SharpSvn</a>:</p> <pre><code>using(SvnClient client = new SvnClient()) { client.Update(Request["path"]); } </code></pre> <p>But I would recommend not to use a user passed variable directly for security reasons.</p>
36,269
<p>What's the best .NET communication component or protocol for very low bandwidth and intermittently connected communication (i.e.: &lt; 10 kilobits/sec)?</p>
<p>Probably <code>System.Net.Sockets.</code><strong><code>Socket</code></strong>. There is also a <code>TcpClient</code> and <code>UdpClient</code> in that namespace.</p>
<p>yeap!, sockets is what you're looking for</p>
20,487
<p>Let's say I wanted to have an application that could easily switch the DB at the back-end.<br> I'm mostly thinking of SQL Server as the primary back-end, but with the flexibility to go another DB engine. Firebird and PostGreSQL seem to have (from my brief wikipedia excursion) the most in common w/ SQL Server (plus they are free).</p> <p>How similar would the DB setup, access, queries, etc.. be for Firebird, PostGreSQL and MS SQL Server?</p>
<p>I worked on one project where it was an absolute requirement to support many databases, including at least Access, SQL Server and Oracle.</p> <p>So I know that it can be done. Mostly DML (SELECT,UPDATE,INSERT...) is the same and certainly we didn't have huge problems making it work across all of the databases - just occasional annoyances. MySQL was the exception at that time as it simply wasn't capable enough.</p> <p>We found most differences in the DDL, but with the right architecture (which we had), it wasn't difficult to fix this.</p> <p>The only thing that caused us a problem was generating unique id's - autoincrement is non-standard. Fortuantely in a database of around 40 tables there were only a few places where unique ID's were need (good DB design). In the end we generate the unique ID in code, and handle any clashes (everything in transactions).</p> <p>It did make things easier because we had avoided using autoincrement for ID fields, it's harder to think of unique keys - but better in the long run.</p>
<p>Well, CRUD stuff should be the same everywhere, but if you build anything complex, you'll probably want to use triggers and stored procedures and that's where compatibility becomes low. Writing a DBMS-agnostic application usually means moving most of the business logic outside of database, so having a 3-tier application is, IMHO, a must in such case. </p> <p>Alternatively, you could use some wrapper library that works like abstraction layer, but I'm yet to see one that is able to do the job correctly over a range of DBMS-es. Of course, that is also dependent on the programming language you use.</p>
24,389
<p>I'm developing non-interactive cpu-bound application which does only computations, almost no IO. Currently it works too long and while I'm working on improving the algorithm, I also think if it can give any benefit to change language or platform. Currently it is C++ (no OOP so it is almost C) on windows compiled with Intel C++ compiler. Can switching to ASM help and how much? Can switching to Linux and GCC help?</p>
<p>Just to be thorough: the first thing to do is to gather profile data and the second thing to do is consider your algorithms. I'm sure you know that, but they've got to be #included into any performance-programming discussion.</p> <p>To be direct about your question "Can switching to ASM help?" the answer is "If you don't know the answer to that, then probably not." Unless you're very familiar with the CPU architecture and its ins and outs, it's unlikely that you'll do a significantly better job than a good optimizing C/C++ compiler on your code. </p> <p>The next point to make is that significant speed-ups in your code (aside from algorithmic improvements) will almost certainly come from parallelism, not linear increases. Desktop machines can now throw 4 or 8 cores at a task, which has much more performance potential than a slightly better code generator. Since you're comfortable with C/C++, OpenMP is pretty much a no-brainer; it's very easy to use to parallelize your loops (obviously, you have to watch loop-carried dependencies, but it's definitely "the simplest parallelism that could possibly work"). </p> <p>Having said all that, code generation quality does vary between C/C++ compilers. The Intel C++ compiler is well-regarded for its optimization quality and has full support not just for OpenMP but for other technologies such as the Threading Building Blocks. </p> <p>Moving into the question of what programming languages might be even better than C++, the answer would be "programming languages that actively promote / facilitate concepts of parallelism and concurrent programming." Erlang is the belle of the ball in that regard, and is a "hot" language right now and most people interested in performance programming are paying at least some attention to it, so if you want to improve your skills in that area, you might want to check it out.</p>
<p>It is hard to produce ASM code that is faster than naive C or C++ code. In most cases if you do this job really well, you probably gain not much than few percents and getting like 10% speedup is considered great success but in most cases it is just impossible. </p> <p>Compilers are capable of understanding how to compile efficiently. You should profile in order to figure out where to optimize.</p>
23,659
<p>I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with <code>e.preventDefault()</code> and runs an AJAX command. This works fine when the submit button is clicked but when a link with <code>onclick='document.formName.submit();'</code> is clicked, the event is not caught by the AJAX form submit event handler. Any ideas why not or how to get this working without binding to all the a elements?</p>
<p>A couple of suggestions:</p> <ul> <li>Overwrite the submit function to do your evil bidding</li> </ul> <pre><code> var oldSubmit = form.submit; form.submit = function() { $(form).trigger("submit"); oldSubmit.call(form, arguments); } </code></pre> <ul> <li>Why not bind to all the &lt;a&gt; tags? Then you don't have to do any monkey patching, and it could be as simple as (assuming all the links are inside the form tag):</li> </ul> <pre><code> $("form a").click(function() { $(this).parents().filter("form").trigger("submit"); }); </code></pre>
<p>Thanks Eran</p> <p>I am using this event binding code</p> <pre><code>this._form.bind('submit', Delegate.create(this, function(e) { e.preventDefault(); this._searchFadeOut(); this.__onFormSubmit.invoke(this, new ZD.Core.GenericEventArgs(this._dateField.attr('value'))); }); </code></pre> <p>but there is legacy <code>onclick</code> code on the HTML and I would prefer not to change it as there are just so many links.</p>
17,166
<p>I've got a bunch of stateless ejb 3.0 beans calling each other in chain. Consider, BeanA.do(message) -> BeanB.do() -> BeanC.do() -> BeanD.do(). Now i'd like to access message data from BeanD.do(). Obvious solution is to pass message as a parameter to all that do() calls (actually that's how it works now), but i want some nicer solution.</p> <p>Is there some kind of call context? And can i associate arbitrary data with it?</p> <p>What i'd like to do, is simply put message in BeanA.do(message) to some local storage associated with bean function call and retrieve it in BeanD.do().</p> <p>Any ideas?</p>
<p>i don't believe there is anything in the EJB spec that provides that functionality. If you are on a specific app server, you may be able to use app server specific stuff (i think JBoss allows you to add stuff to a call context). you also may be able to fake something up using JNDI.</p> <p>personally, this seems (to me) like a poor design. i could see doing this if you had some code in the middle you could not control, but why do it otherwise? you are making your code logic very hard to follow because you have a bunch of "magic" data which just appears in your function.</p>
<p>You could have a class with static get/set methods that access a static ThreadLocal field. However I would take james' advice and consider very carefully if you want to couple your EJBs to that other class. Definitely double-check your app server docs as I'm not sure if using ThreadLocals in an EJB environment is supported.</p>
48,086
<p>I have a cron "time definition"</p> <pre><code>1 * * * * (every hour at xx:01) 2 5 * * * (every day at 05:02) 0 4 3 * * (every third day of the month at 04:00) * 2 * * 5 (every minute between 02:00 and 02:59 on fridays) </code></pre> <p>And I have an unix timestamp.</p> <p>Is there an obvious way to find (calculate) the next time (after that given timestamp) the job is due to be executed?</p> <p>I'm using PHP, but the problem should be fairly language-agnostic.</p> <p>[Update]</p> <p>The class "<a href="http://www.phpclasses.org/browse/package/2568.html" rel="noreferrer">PHP Cron Parser</a>" (suggested by Ray) calculates the LAST time the CRON job was supposed to be executed, not the next time.</p> <p>To make it easier: In my case the cron time parameters are only absolute, single numbers or "*". There are no time-ranges and no "*/5" intervals.</p>
<p>This is basically doing the reverse of checking if the current time fits the conditions. so something like:</p> <pre><code>//Totaly made up language next = getTimeNow(); next.addMinutes(1) //so that next is never now done = false; while (!done) { if (cron.minute != '*' &amp;&amp; next.minute != cron.minute) { if (next.minute &gt; cron.minute) { next.addHours(1); } next.minute = cron.minute; } if (cron.hour != '*' &amp;&amp; next.hour != cron.hour) { if (next.hour &gt; cron.hour) { next.hour = cron.hour; next.addDays(1); next.minute = 0; continue; } next.hour = cron.hour; next.minute = 0; continue; } if (cron.weekday != '*' &amp;&amp; next.weekday != cron.weekday) { deltaDays = cron.weekday - next.weekday //assume weekday is 0=sun, 1 ... 6=sat if (deltaDays &lt; 0) { deltaDays+=7; } next.addDays(deltaDays); next.hour = 0; next.minute = 0; continue; } if (cron.day != '*' &amp;&amp; next.day != cron.day) { if (next.day &gt; cron.day || !next.month.hasDay(cron.day)) { next.addMonths(1); next.day = 1; //assume days 1..31 next.hour = 0; next.minute = 0; continue; } next.day = cron.day next.hour = 0; next.minute = 0; continue; } if (cron.month != '*' &amp;&amp; next.month != cron.month) { if (next.month &gt; cron.month) { next.addMonths(12-next.month+cron.month) next.day = 1; //assume days 1..31 next.hour = 0; next.minute = 0; continue; } next.month = cron.month; next.day = 1; next.hour = 0; next.minute = 0; continue; } done = true; } </code></pre> <p>I might have written that a bit backwards. Also it can be a lot shorter if in every main if instead of doing the greater than check you merely increment the current time grade by one and set the lesser time grades to 0 then continue; however then you'll be looping a lot more. Like so:</p> <pre><code>//Shorter more loopy version next = getTimeNow().addMinutes(1); while (true) { if (cron.month != '*' &amp;&amp; next.month != cron.month) { next.addMonths(1); next.day = 1; next.hour = 0; next.minute = 0; continue; } if (cron.day != '*' &amp;&amp; next.day != cron.day) { next.addDays(1); next.hour = 0; next.minute = 0; continue; } if (cron.weekday != '*' &amp;&amp; next.weekday != cron.weekday) { next.addDays(1); next.hour = 0; next.minute = 0; continue; } if (cron.hour != '*' &amp;&amp; next.hour != cron.hour) { next.addHours(1); next.minute = 0; continue; } if (cron.minute != '*' &amp;&amp; next.minute != cron.minute) { next.addMinutes(1); continue; } break; } </code></pre>
<p>Check <a href="http://www.phpclasses.org/browse/package/2568.html" rel="noreferrer">this out</a>:</p> <blockquote>It can calculate the next time a scheduled job is supposed to be run based on the given cron definitions.</blockquote>
41,615
<p>If my domain objects implement IDataErrorInfo, and I am using M-V-VM, how do I propagate errors through the ViewModel into the View? If i was binding directly to the model, I would set the "ValidateOnExceptons" and "ValidateOnErrors" properties to true on my binding. But my ViewModel doesn't implement IDataErrorInfo. Only my model. What do I do?</p> <p><strong>Clarification</strong> I am dealing with an existing codebase that implements IDataErrorInfo in the domain objects. I can't just implement IDataErrorInfo in the my view model.</p>
<p>You can implement IDataErrorInfo additionally in your VM and route the calls to the VM to your corresponding domain objects. I think this is the only way without exposing domain objects directly to the view.</p>
<p>The <strong>BookLibrary</strong> sample application of the <strong><a href="http://waf.codeplex.com" rel="nofollow noreferrer">WPF Application Framework (WAF)</a></strong> might be interesting for you. It implements the IDataErrorInfo interface as well on the domain objects and it uses the M-V-VM pattern.</p>
44,425
<p>Given the following XML:</p> <pre><code>&lt;current&gt; &lt;login_name&gt;jd&lt;/login_name&gt; &lt;/current&gt; &lt;people&gt; &lt;person&gt; &lt;first&gt;John&lt;/first&gt; &lt;last&gt;Doe&lt;/last&gt; &lt;login_name&gt;jd&lt;/login_name&gt; &lt;/preson&gt; &lt;person&gt; &lt;first&gt;Pierre&lt;/first&gt; &lt;last&gt;Spring&lt;/last&gt; &lt;login_name&gt;ps&lt;/login_name&gt; &lt;/preson&gt; &lt;/people&gt; </code></pre> <p>How can I get "John Doe" from within the current/login matcher?</p> <p>I tried the following:</p> <pre><code>&lt;xsl:template match="current/login_name"&gt; &lt;xsl:value-of select="../people/first[login_name = .]"/&gt; &lt;xsl:text&gt; &lt;/xsl:text&gt; &lt;xsl:value-of select="../people/last[login_name = .]"/&gt; &lt;/xsl:template&gt; </code></pre>
<p>I'd define a key to index the people:</p> <pre><code>&lt;xsl:key name="people" match="person" use="login_name" /&gt; </code></pre> <p>Using a key here simply keeps the code clean, but you might also find it helpful for efficiency if you're often having to retrieve the <code>&lt;person&gt;</code> elements based on their <code>&lt;login_name&gt;</code> child.</p> <p>I'd have a template that returned the formatted name of a given <code>&lt;person&gt;</code>:</p> <pre><code>&lt;xsl:template match="person" mode="name"&gt; &lt;xsl:value-of select="concat(first, ' ', last)" /&gt; &lt;/xsl:template&gt; </code></pre> <p>And then I'd do:</p> <pre><code>&lt;xsl:template match="current/login_name"&gt; &lt;xsl:apply-templates select="key('people', .)" mode="name" /&gt; &lt;/xsl:template&gt; </code></pre>
<p>I think what he actually wanted was the replacement in the match for the "current" node, not a match in the person node:</p> <pre><code>&lt;xsl:variable name="login" select="//current/login_name/text()"/&gt; &lt;xsl:template match="current/login_name"&gt; &lt;xsl:value-of select='concat(../../people/person[login_name=$login]/first," ", ../../people/person[login_name=$login]/last)'/&gt; &lt;/xsl:template&gt; </code></pre>
8,733
<p>How do I cause the page to make the user jump to a new web page after X seconds. If possible I'd like to use HTML but a niggly feeling tells me it'll have to be Javascript.</p> <p>So far I have the following but it has no time delay</p> <pre><code>&lt;body onload="document.location='newPage.html'"&gt; </code></pre>
<p>A meta refresh is ugly but will work. The following will go to the new url after 5 seconds: </p> <pre><code>&lt;meta http-equiv="refresh" content="5;url=http://example.com/"/&gt; </code></pre> <p><a href="http://en.wikipedia.org/wiki/Meta_refresh" rel="noreferrer">http://en.wikipedia.org/wiki/Meta_refresh</a></p>
<p>The JavaScript method, without invoking <code>eval</code> in the the <code>setTimeout</code>:</p> <pre><code>&lt;body onload="setTimeout(function(){window.location.href='newpage.html'}, 5000)"&gt; </code></pre>
16,888
<p>In my JSP I need to test two objects using the <code>equals()</code> method. Is there a way to do this using EL, JSTL, or another tag library? I am not allowed to use scriptlets due to team rules.</p> <p>I tried to use the JSTL <code>&lt;c:if&gt;</code> tag, but it only seems to use the <code>==</code> operator.</p>
<p>The JSP Expression Language operator <code>==</code> (or its alias, <code>eq</code>) performs comparison with the <code>equals</code> method, although some coercions are performed if one of the objects is a special type (BigDecimal, BigInteger, Double, Float, Long, Integer, Short, Byte, Character, Boolean, or String). You shouldn't need a tag for this, just <code>${a == b}</code>. If that doesn't fit in your context, could you please post more information?</p>
<p>The <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html" rel="nofollow noreferrer">J2EE 1.4 guide</a> has an example of just that. You'll have to setup your once function lib, but it doesn't look hard.</p>
43,944
<p>Currently, we are using WebSphere Portal v5.1, and the URLs are about a un-friendly as a URL could get. For example: </p> <p><a href="http://www.foo.com/wsps/portal/!ml/QjzQ0IhyR0UAkc39Aw!!/delta/base64xml/L3dJ82XzBfQ1A" rel="nofollow noreferrer">http://www.foo.com/wsps/portal/!ml/QjzQ0IhyR0UAkc39Aw!!/delta/base64xml/L3dJ82XzBfQ1A</a>! </p> <p>I have removed a bunch of the characters, but you get the idea. One of our frustrations is that the URLs often end with punctuation. The users of the portal try to cut/paste from the address bar into emails or word docs, and the trailing exclamation mark does not become part of the generated hyperlink (a feature of Microsoft products, this happens with Outlook, Word, Powerpoint, etc).</p> <p>As for solutions, we've been advised that the URL mapping feature of WPS does not scale well, and I don't believe that has changed much with the more recent releases.</p> <p>So, back to the question. Are there other portal products that manage URLs better? or is this simply the nature of the portal beast?</p>
<p>WebSphere Portal is holding the navigational state in its URLs. Cutting this urls will destroy that information. Since Portal 6.1 there is a way to define a "friendly name"=url for pages which allows to send them around without the risk to get them destroyed by copy&amp;paste actions. WebSphere portal is of course supporting JSR286 portlets since version 6.0 I believe. Unfortunately I have no experience with other portal implementations. </p>
<p>What are your portal requirements?</p> <p>I'm guessing it needs to be Java orientated and I'm guessing when you say portal you mean JSR-168? Or JSR-286? (WPS 5.1 is 168 + IBM mess, 286 is newer, I think Java5+).</p> <p>It's also worth mentioning that if you've built an entire set of portlets in WAS 5.1 you may need to check with your developers to make sure you're not using IBM-specific extensions. If you are then you'll need to refactor those out, otherwise you cannot drop them into another Portal implementation.</p>
43,447
<p>I have a pretty unusual problem (for me). I am writing an application that will allow a user to change their system time forward or back either by explicit date (change my date to 6/3/1955) or by increment using buttons (go forward 1 month).</p> <p>I'm writing this to help some of my users test some software that requires jumps like this in order to simulate real world usage of a billing system.</p> <p>Changing the time in Delphi is of course very easy:</p> <pre><code>SetDateTime(2008,05,21,16,07,21,00); </code></pre> <p>But I'm not sure if Delphi (2006) has any built in helpers for date math, which is one of my least favorite things :)</p> <p>Any suggestions for the best way to handle this? I'd prefer to stay native as the winapi datetime calls suck.</p> <p>Thanks!</p>
<p>As mentioned by gabr and mliesen, have a look at the <a href="http://docwiki.embarcadero.com/VCL/en/DateUtils" rel="noreferrer">DateUtils</a> and <a href="http://docwiki.embarcadero.com/VCL/en/SysUtils" rel="noreferrer">SysUtils</a> units, useful functions include.</p> <ul> <li><a href="http://docwiki.embarcadero.com/VCL/en/DateUtils.IncDay" rel="noreferrer">IncDay</a> - Add a or subtract a number of days.</li> <li><a href="http://docwiki.embarcadero.com/VCL/en/SysUtils.IncMonth" rel="noreferrer">IncMonth</a> - Add a or subtract a number of months.</li> <li><a href="http://docwiki.embarcadero.com/VCL/en/DateUtils.IncWeek" rel="noreferrer">IncWeek</a> - Add a or subtract a number of weeks.</li> <li><a href="http://docwiki.embarcadero.com/VCL/en/DateUtils.IncYear" rel="noreferrer">IncYear</a> - Add a or subtract a number of years.</li> <li><a href="http://docwiki.embarcadero.com/VCL/en/SysUtils.EncodeDate" rel="noreferrer">EncodeDate</a> - Returns a TDateTime value from the Year, Month, and Day params.</li> </ul>
<p>There is plenty of helpers in the SysUtils unit (and as gabr pointed out, also in DateUtils).</p>
20,303
<p>Large datasets, millions of records, need special programming to maintain speed in DBGrids. </p> <p>I want to know if there are any ready-made components for Delphi (DBGrids) that do this automatically?</p> <p>EDIT For Example: Some databases have features such as fetch 1st X records (eg 100 records). When I reach the bottom with scrolling, I want to auto fetch the next 100. Conversely when I reach the beginning, I want to fetch the previous 100. I know I can program this, but it sure is possible to propagate that feature to a DBGrid control where the DBGrid does the buffering. It will save quite a bit of programming - you simply have to set the "buffer size" so to speak.</p>
<p>I would have a look at <a href="http://www.devexpress.com/Products/VCL/ExQuantumGrid/key_datacontroller.xml" rel="nofollow noreferrer">Developer Express QuantumGrid Suite</a>. (@birger: you just were a tick faster ;-) ) So I'm not just duplicating the answer, some elaboration:</p> <p>The DevExpress Grid uses a data controller that has several modes to controll the data bound to the grid. One of these is exactly what you are looking for:</p> <blockquote> <p><strong>Grid Mode</strong></p> <p>When using Grid Mode, only a fixed number of dataset records is loaded into memory. Because only a limited set of records are retrieved from the dataset, automatic sorting, filtering and summary calculations are disabled in Grid Mode (must be controlled manually instead). By default, this mode is disabled and the ExpressDataController loads all records in a dataset.</p> </blockquote> <p>It does have some drawbacks, which seem pretty obvious: you cannot make a summary, sort, or filter if you do not have all records at hand.</p>
<p>sorry, I just saw your comment to Neftalí</p> <p>if you would to bring 100 record per time, and then fetch the next 100, this work related to database access components, look at <strong>devart</strong> components, they are offer direct access components to most used database, and they have the feature you are asking about and more:</p> <p><a href="http://www.devart.com/products-vcl.html" rel="nofollow noreferrer">http://www.devart.com/products-vcl.html</a></p>
24,506
<p>I have a subclass "s" of UIView. I want to put some buttons and labels on s. How do I associate my UIView subclass with a nib file?</p>
<ol> <li>In Interface Builder, create a new xib with the View template. <ul> <li>Click on the view in the list of objects in the xib (you should also see "File's Owner and "First Responder").</li> <li>Push Cmd-4 to open the Identity pane of the inspector.</li> <li>Type your class's name into the "Class Name" field and push return.</li> </ul></li> </ol> <p>You should be able the drag buttons in. To get at the nib from code, use <code>-[NSBundle loadNibNamed:owner:options:]</code>. Your view should be the first object in the returned array.</p>
<p>In my case, I didn't want my view controller to have any knowledge of the IBOutlets from my view's .xib. I wanted my view subclass to own the IBOutlets. Unfortunately UIView doesn't have an <code>initWithNibName:</code> method, so I just created my own category.</p> <p>Here's what I did:</p> <ul> <li>In IB, click on your main UIView, and in the Identity Inspector, set the class to your subclass</li> <li>In IB, click on File's Owner, and in the Identity Inspector, set the class to your subclass</li> <li>Use your new category method <code>initWithNibName:</code> to instantiate your view.</li> </ul> <p>And here's the category I created:</p> <pre><code>- (instancetype)initWithNibName:(NSString *)nibName { NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil]; if (arrayOfViews.count &lt; 1) { return nil; } self = arrayOfViews[0]; return self; } </code></pre> <p>Inspired by <a href="http://answers.oreilly.com/topic/2578-loading-a-nib-file-programmatically-objective-c/" rel="nofollow">this post</a>.</p> <p>Note though, that so far the frame will adjust automatically, so unlike the code in the post, I haven't yet had to explicitly set the frame. Also, unlike the post's code, I needed to set <code>owner:self</code> so the IBOutlets would be wired up correctly.</p>
29,514
<p>Over the years I've worked on a number of microcontroller-based projects; mostly with Microchip's PICs. I've used various microcontroller simulators, and while they can be very helpful at times, I often find myself frustrated. In real life microcontrollers never exist alone and the firmware's behavior is dependent on the environment. However, none of the sims I've used provide decent support for anything outside the microcontroller.</p> <p>My first thought was to model the entire board in Verilog. But, I'd rather not create an entire CPU model, and I haven't had much luck finding existing models for the chips I use. Regardless, I really don't need, or want, to simulate the proc at that level of detail, and I'd like to retain the debugging facilities provided by a regular processor sim.</p> <p>It seems to me that the ideal solution would be a hybrid simulator that interfaces a traditional processor simulator with a Verilog model.</p> <p>Does such a thing exist?</p>
<p>For the "simulate the whole board" approach, The Free Model Foundry has a large number of models, some in VHDL others in Verilog, that are available now.. but you'll need to pay to have new models created. These are very helpful in being sure the board is built correctly. </p> <p>But I think the more common approach when debugging your PIC is to just build a board, then work on the firmware. In the chip world, (where the firmware is running on a microprocessor in a chip that hasn't gone to fab yet) people often resort to very expensive systems (or renting time on them) that allow compiling part of the design into an emulator while the rest of the design runs in the normal simulator environment. Without the barrier of an expensive mask set for the chip, the cost is just not justifiable for a Circuit board. Although I've heard of some creative applications of Simulink (Mathworks) with FPGA's, but my recollection is that one either ran the system on the computer, or programmed the device and ran the same thing in realtime. </p> <p>I believe both Cadence (ask about Palladium) and Mentor Graphics have that integrated solution if you have the money to spend on it. </p>
<p>My workmates from the hardware department use FPGA simulation software quite often to find timing-bugs and trace down strange behaviours.</p> <p>Simulating one or two milliseconds can take several hours, so using the simulator for anything but very small things is not feasable.</p> <p>You may want to have a look at SystemC though. <a href="http://en.wikipedia.org/wiki/SystemC" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/SystemC</a></p>
49,171
<p>My application is generating different floating point values when I compile it in release mode and in debug mode. The only reason that I found out is I save a binary trace log and the one from the release build is ever so slightly off from the debug build, it looks like the bottom two bits of the 32 bit float values are different about 1/2 of the cases.</p> <p>Would you consider this "difference" to be a bug or would this type of difference be expected. Would this be a compiler bug or an internal library bug.</p> <p>For example:</p> <pre><code>LEFTPOS and SPACING are defined floating point values. float def_x; int xpos; def_x = LEFTPOS + (xpos * (SPACING / 2)); </code></pre> <p>The issue is in regards to the X360 compiler.</p>
<p>Release mode may have a different FP strategy set. There are different floating point arithmetic modes depending on the level of optimization you'd like. MSVC, for example, has strict, fast, and precise modes.</p>
<p>This discrepancy may very well be caused by the compiler optimization, which is typically done in the release mode, but not in debug mode. For example, the compiler may reorder some of the operations to speed up execution, which can conceivably cause a slight difference in the floating point result.</p> <p>So, I would say most likely it is not a bug. If you are really worried about this, try turning on optimization in the Debug mode.</p>
17,134
<p>Hey everyone, I am trying to run the following program, but am getting a NullPointerException. I am new to the Java swing library so I could be doing something very dumb. Either way here are my two classes I am just playing around for now and all i want to do is draw a damn circle (ill want to draw a gallow, with a hangman on it in the end).</p> <pre><code>package hangman2; import java.awt.*; import javax.swing.*; public class Hangman2 extends JFrame{ private GridLayout alphabetLayout = new GridLayout(2,2,5,5); private Gallow gallow = new Gallow(); public Hangman2() { setLayout(alphabetLayout); setSize(1000,500); setVisible( true ); } public static void main( String args[] ) { Hangman2 application = new Hangman2(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } package hangman2; import java.awt.*; import javax.swing.*; public class Gallow extends JPanel { private Graphics g; public Gallow(){ g.fillOval(10, 20, 40, 25); } } </code></pre> <p>The NullPointerException comes in at the g.fillOval line.</p> <p>Thanks in advance,</p> <p>Tomek</p>
<p>You're getting NPE because <code>g</code> is not set, therefore, it's <code>null</code>. Furthermore, you shouldn't be doing the drawing in the constructor. Overload <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JComponent.html#paintComponent(java.awt.Graphics)" rel="nofollow noreferrer"><code>paintComponent(Graphics g)</code></a> instead.</p> <pre><code>public class Gallow extends JPanel { public paintComponent(Graphics g){ g.fillOval(10, 20, 40, 25); } } </code></pre> <p>I'd also look into <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/image/BufferedImage.html" rel="nofollow noreferrer">BufferedImage</a>.</p>
<p>A couple of things: Don't forget to add the panel to the <code>JFrame</code>. And override the <code>paint()</code> method of <code>JPanel</code> for your custom painting. You do not need to declare a Graphics object since the <code>JPanel</code>'s paint method will have a reference to one in any case.</p> <pre><code>package hangman2; import java.awt.*; import javax.swing.*; public class Hangman2 extends JFrame{ private GridLayout alphabetLayout = new GridLayout(2,2,5,5); private Gallow gallow = new Gallow(); public Hangman2() { setLayout(alphabetLayout); add(gallow, BorderLayout.CENTER);//here setSize(1000,500); setVisible( true ); } public static void main( String args[] ) { Hangman2 application = new Hangman2(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } package hangman2; import java.awt.*; import javax.swing.*; public class Gallow extends JPanel { public Gallow(){ super(); } public void paint(Graphics g){ g.fillOval(10, 20, 40, 25); } } </code></pre>
35,368
<p>Can it be assumed a evaluation order of the function parameters when calling it in C ? According to the following program, it seems that there is not a particular order when I executed it. </p> <pre><code>#include &lt;stdio.h&gt; int main() { int a[] = {1, 2, 3}; int * pa; pa = &amp;a[0]; printf("a[0] = %d\ta[1] = %d\ta[2] = %d\n",*(pa), *(pa++),*(++pa)); /* Result: a[0] = 3 a[1] = 2 a[2] = 2 */ pa = &amp;a[0]; printf("a[0] = %d\ta[1] = %d\ta[2] = %d\n",*(pa++),*(pa),*(++pa)); /* Result: a[0] = 2 a[1] = 2 a[2] = 2 */ pa = &amp;a[0]; printf("a[0] = %d\ta[1] = %d\ta[2] = %d\n",*(pa++),*(++pa), *(pa)); /* a[0] = 2 a[1] = 2 a[2] = 1 */ } </code></pre>
<p>No, function parameters are not evaluated in a defined order in C.</p> <p>See Martin York's answers to <a href="https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-c-programmer-should-know-about">What are all the common undefined behaviour that c++ programmer should know about?</a>.</p>
<p>Grant's answer is correct, it's undefined.</p> <p>BUT,,,</p> <p>By your example, your compiler seems to be evaluating in right-to-left order (unsurprisingly, the order that arguments are pushed onto the stack). If you can do other tests to show that the order is maintained consistently even with optimizations enabled, and if you're only going to stick with that one version of the compiler, you can safely assume right-to-left ordering.</p> <p>It's totally non-portable and a horrible, horrible thing to do, though.</p>
49,254
<p>I want to develop a website in ASP classic that uses HTTP Authentication against a database or password list that is under the control of the script. Ideally, the solution should involve no components or IIS settings as the script should be runnable in a hosted environment.</p> <p>Any clues/code deeply appreciated.</p>
<p>It is possible to do HTTP Basic Authentication in pure classic ASP VBScript. </p> <p>You will need something to decode base 64. <a href="http://www.motobit.com/tips/detpg_base64/" rel="noreferrer">Here is a pure VBScript implementation</a>. You will also need to make sure that in your IIS config you turn off "Basic authentication" and "Integrated Windows authentication" as these will interfere with what you get back in the HTTP_AUTHORIZATION header. </p> <p>Here is a sample implementation that just echoes back the user name and password.</p> <pre><code>&lt;%@LANGUAGE="VBSCRIPT"%&gt; &lt;!--#include file="decbase64.asp" --&gt; &lt;% Sub Unauth() Call Response.AddHeader("WWW-Authenticate", "Basic realm=""SomethingGoesHere""") Response.Status = "401 Unauthorized" Call Response.End() End Sub Dim strAuth strAuth = Request.ServerVariables("HTTP_AUTHORIZATION") If IsNull(strAuth) Or IsEmpty(strAuth) Or strAuth = "" Then Call Unauth Else %&gt; &lt;html&gt; &lt;body&gt; &lt;% Dim aParts, aCredentials, strType, strBase64, strPlain, strUser, strPassword aParts = Split(strAuth, " ") If aParts(0) &lt;&gt; "Basic" Then Call Unauth End If strPlain = Base64Decode(aParts(1)) aCredentials = Split(strPlain, ":") %&gt; &lt;%= Server.HTMLEncode(aCredentials(0) &amp; " - " &amp; aCredentials(1)) %&gt; &lt;/body&gt; &lt;/html&gt; &lt;% End If %&gt; </code></pre> <p>Hooking the user name and password up to something meaningful is left as an exercise for the reader.</p>
<p>Hi are you trying to get a list of users from a database or use network based permissions on the HTTP server?</p> <p>If you are using a database use ODBC and DSN</p> <pre><code>Dim DatabaseObject1 Set DatabaseObject1 = Server.CreateObject("ADODB.Connection") DatabaseObject1.Open("DSN=DSNname;") </code></pre> <p>If you are wanting a password dialogue box (from the server), you will need to alter IIS settings for a good guide to this..</p> <p><a href="http://www.authenticationtutorial.com/tutorial/" rel="nofollow noreferrer">http://www.authenticationtutorial.com/tutorial/</a></p>
25,518
<p>What is the behind-the-scenes difference between 'int?' and 'int'? Is 'int?' a somehow a reference type?</p>
<p>? wraps the value type (T) in a Nullable&lt;T&gt; struct:</p> <p><a href="http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx</a></p>
<p>I learned that you must explicitly cast a nullable value type to a none-nullable value type, as the following example shows:</p> <pre><code>int? n = null; //int m1 = n; // Doesn't compile int n2 = (int)n; // Compiles, but throws an exception if n is null </code></pre> <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types" rel="nofollow noreferrer">MS Document</a></p>
13,543
<p>I'm trying to import an XML file via a web page in a Ruby on Rails application, the code ruby view code is as follows (I've removed HTML layout tags to make reading the code easier)</p> <pre><code>&lt;% form_for( :fmfile, :url =&gt; '/fmfiles', :html =&gt; { :method =&gt; :post, :name =&gt; 'Form_Import_DDR', :enctype =&gt; 'multipart/form-data' } ) do |f| %&gt; &lt;%= f.file_field :document, :accept =&gt; 'text/xml', :name =&gt; 'fmfile_document' %&gt; &lt;%= submit_tag 'Import DDR' %&gt; &lt;% end %&gt; </code></pre> <p>Results in the following HTML form</p> <pre><code>&lt;form action="/fmfiles" enctype="multipart/form-data" method="post" name="Form_Import_DDR"&gt;&lt;div style="margin:0;padding:0"&gt;&lt;input name="authenticity_token" type="hidden" value="3da97372885564a4587774e7e31aaf77119aec62" /&gt; &lt;input accept="text/xml" id="fmfile_document" name="fmfile_document" size="30" type="file" /&gt; &lt;input name="commit" type="submit" value="Import DDR" /&gt; &lt;/form&gt; </code></pre> <p>The Form_Import_DDR method in the 'fmfiles_controller' is the code that does the hard work of reading the XML document in using REXML. The code is as follows</p> <pre><code>@fmfile = Fmfile.new @fmfile.user_id = current_user.id @fmfile.file_group_id = 1 @fmfile.name = params[:fmfile_document].original_filename respond_to do |format| if @fmfile.save require 'rexml/document' doc = REXML::Document.new(params[:fmfile_document].read) doc.root.elements['File'].elements['BaseTableCatalog'].each_element('BaseTable') do |n| @base_table = BaseTable.new @base_table.base_table_create(@fmfile.user_id, @fmfile.id, n) end </code></pre> <p>And it carries on reading all the different XML elements in.</p> <p>I'm using Rails 2.1.0 and Mongrel 1.1.5 in Development environment on Mac OS X 10.5.4, site DB and browser on same machine.</p> <p>My question is this. This whole process works fine when reading an XML document with character encoding UTF-8 but fails when the XML file is UTF-16, does anyone know why this is happening and how it can be stopped?</p> <p>I have included the error output from the debugger console below, it takes about 5 minutes to get this output and the browser times out before the following output with the 'Failed to open page'</p> <pre><code>Processing FmfilesController#create (for 127.0.0.1 at 2008-09-15 16:50:56) [POST] Session ID: BAh7CDoMdXNlcl9pZGkGOgxjc3JmX2lkIiVmM2I3YWU2YWI4ODU2NjI0NDM2 NTFmMDE1OGY1OWQxNSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxh c2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--dd9f588a68ed628ab398dd1a967eedcd09e505e0 Parameters: {"commit"=&gt;"Import DDR", "authenticity_token"=&gt;"3da97372885564a4587774e7e31aaf77119aec62", "action"=&gt;"create", "fmfile_document"=&gt;#&lt;File:/var/folders/LU/LU50A0vNHA07S4rxDAOk4E+++TI/-Tmp-/CGI.3001.1&gt;, "controller"=&gt;"fmfiles"} [4;36;1mUser Load (0.000350)[0m [0;1mSELECT * FROM "users" WHERE (id = 1) LIMIT 1[0m [4;35;1mFmfile Create (0.000483)[0m [0mINSERT INTO "fmfiles" ("name", "file_group_id", "updated_at", "report_created_at", "report_link", "report_version", "option_on_open_account_name", "user_id", "option_default_custom_menu_set", "option_on_close_script", "path", "report_type", "option_on_open_layout", "option_on_open_script", "created_at") VALUES('TheTest_fp7 2.xml', 1, '2008-09-15 15:50:56', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, '2008-09-15 15:50:56')[0m REXML::ParseException (#&lt;Iconv::InvalidCharacter: "਼䙍偒数 (followed by a few thousand similar looking chinese characters) 䙍偒数潲琾", ["\n"]&gt; /Library/Ruby/Site/1.8/rexml/encodings/ICONV.rb:7:in `conv' /Library/Ruby/Site/1.8/rexml/encodings/ICONV.rb:7:in `decode' /Library/Ruby/Site/1.8/rexml/source.rb:50:in `encoding=' /Library/Ruby/Site/1.8/rexml/parsers/baseparser.rb:210:in `pull' /Library/Ruby/Site/1.8/rexml/parsers/treeparser.rb:21:in `parse' /Library/Ruby/Site/1.8/rexml/document.rb:190:in `build' /Library/Ruby/Site/1.8/rexml/document.rb:45:in `initialize' </code></pre>
<p>Rather than a rails/mongrel problem, it sounds more likely that there's an issue either with your XML file or with the way REXML handles it. You can check this by writing a short script to read your XML file directly (rather than within a request) and seeing if it still fails.</p> <p>Assuming it does, there are a couple of things I'd look at. First, I'd check you are running the latest version of REXML. A couple of years ago there was a bug (<a href="http://www.germane-software.com/projects/rexml/ticket/63" rel="nofollow noreferrer">http://www.germane-software.com/projects/rexml/ticket/63</a>) in its UTF-16 handling. </p> <p>The second thing I'd check is if you're issue is similar to this: <a href="http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/ba7b0585c7a6330d" rel="nofollow noreferrer">http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/ba7b0585c7a6330d</a>. If so you can try the workaround in that thread.</p> <p>If none of the above helps, then please reply with more information, such as the exception you are getting when you try and read the file.</p>
<p>Since getting this to work requires me to only change the encoding attribute of the first XML element to have the value UTF-8 instead of UTF-16, the XML file is actually UTF-8 and labelled wrongly by the application that generates it.</p> <p>The XML file is a FileMaker DDR export produced by FileMaker Pro Advanced 8.5 on OS X 10.5.4</p>
8,904
<p>This is the page that I'm having. But the resize part in the section does not seem to be working. I copied most of the code from the <a href="http://www.asp.net/ajax/ajaxcontroltoolkit/samples/UpdatePanelAnimation/UpdatePanelAnimation.aspx" rel="nofollow noreferrer">Ajax site</a>. I placed a alert() in the tag (line 108) to find the value of 'b._originalHeight' and it shows up as '44'. I have also tried the code in the above-said tutorial (line 132) and that did not work either. (I'm not sure where it is getting this value from. But I need it to show all the controls on the form.</p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddEditContest.ascx.cs" Inherits="TMPInternational.Spawn2DotComAdmin.Contest.UserControls.AddEditContest" %&gt; &lt;%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="uc" %&gt; &lt;%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %&gt; &lt;%@ Register TagPrefix="ew" Assembly="eWorld.UI, Version=1.9.0.0, Culture=neutral, PublicKeyToken=24d65337282035f2" Namespace="eWorld.UI" %&gt; &lt;h1 style="margin-left:8px"&gt;Add/Edit Contest&lt;/h1&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" /&gt; &lt;div style="text-align:left;width:500px; margin-left:8px"&gt; &lt;div id="PanelContainer"&gt; &lt;asp:UpdatePanel ID="AddEditContestUpdatePanel" runat="server" UpdateMode="Always"&gt; &lt;ContentTemplate&gt; &lt;div id="background" style="text-align:left; height: 44px;"&gt; &lt;asp:Panel ID="ContestList" runat="server"&gt; &lt;asp:datagrid AllowSorting="false" id="ContestGrid" GridLines="None" CellPadding="5" Width="100%" AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#cccccc" HeaderStyle-Font-Size="15px" HeaderStyle-Font-Bold="true" HeaderStyle-BackColor="#888f9b" Runat="server" AllowPaging="True" PageSize="10" PagerStyle-NextPageText="Next &gt;&gt;" PagerStyle-PrevPageText="&lt;&lt; Back" &gt; &lt;Columns&gt; &lt;asp:HyperLinkColumn DataNavigateUrlField="ContestID" DataNavigateUrlFormatString="../?Load=AddEditContest&amp;Type=Edit&amp;ContestID={0}" DataTextField="Title" ItemStyle-width="30%" headertext="Contest Title" /&gt; &lt;asp:BoundColumn DataField="StartDate" ItemStyle-Width="35%" HeaderText="Start Date" /&gt; &lt;asp:BoundColumn DataField="EndDate" ItemStyle-Width="35%" HeaderText="End Date" /&gt; &lt;/Columns&gt; &lt;/asp:datagrid&gt; &lt;div style="text-align:right;"&gt; &lt;asp:ImageButton ID="AddContest" runat="server" ImageUrl="~/Contest/Images/Add.png" AlternateText="Add Contest" onclick="AddContest_Click" /&gt; &lt;/div&gt; &lt;/asp:Panel&gt; &lt;asp:Panel ID="FieldsPanel" runat="server"&gt; &lt;p /&gt;&lt;b&gt;Title&lt;/b&gt; &lt;br /&gt; &lt;asp:TextBox Runat="server" id="TitleText" /&gt; &lt;asp:RequiredFieldValidator id="TitleValidator" runat="server" ForeColor="Red" ErrorMessage="Please add a title" ControlToValidate="TitleText"&gt;*&lt;/asp:RequiredFieldValidator&gt; &lt;p /&gt;&lt;b&gt;Contest Description&lt;/b&gt; &lt;br /&gt; Use HTML tags to format this area. Start paragraphs with &amp;lt;p /&amp;gt; tag, bold items with &amp;lt;b&amp;gt;&amp;lt;/b&amp;gt; tags. Create a line-break between lines with one &amp;lt;br /&amp;gt; tag.&lt;br /&gt; &lt;asp:TextBox Runat="server" ID="DescriptionText" TextMode="MultiLine" Width="400" Height="200" /&gt; &lt;asp:RequiredFieldValidator id="DescriptionValidator" runat="server" ErrorMessage="Please add a description" ControlToValidate="DescriptionText" ForeColor="Red"&gt;*&lt;/asp:RequiredFieldValidator&gt; &lt;p /&gt; &lt;b&gt;Contest Start Date&lt;/b&gt; &lt;br /&gt; &lt;ew:CalendarPopup id="StartDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif" CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select" CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False"&gt; &lt;WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" /&gt; &lt;MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" /&gt; &lt;OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" /&gt; &lt;GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/&gt; &lt;TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" /&gt; &lt;DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" /&gt; &lt;WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" /&gt; &lt;SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/&gt; &lt;HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" /&gt; &lt;/ew:CalendarPopup&gt; &amp;nbsp; &lt;ew:TimePicker id="StartTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time" ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px"&gt; &lt;TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" /&gt; &lt;SelectedTimeStyle ForeColor="Blue" BackColor="Gray" /&gt; &lt;/ew:TimePicker&gt; &lt;p/&gt;&lt;b&gt;Contest End Date&lt;/b&gt; &lt;br /&gt; &lt;ew:CalendarPopup id="EndDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif" CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select" CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False"&gt; &lt;WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" /&gt; &lt;MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" /&gt; &lt;OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" /&gt; &lt;GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/&gt; &lt;TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" /&gt; &lt;DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" /&gt; &lt;WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" /&gt; &lt;SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/&gt; &lt;HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" /&gt; &lt;/ew:CalendarPopup&gt; &amp;nbsp; &lt;ew:TimePicker id="EndTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time" ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px"&gt; &lt;TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" /&gt; &lt;SelectedTimeStyle ForeColor="Blue" BackColor="Gray" /&gt; &lt;/ew:TimePicker&gt; &lt;p /&gt; &lt;asp:ImageButton ID="SaveContestButton" runat="server" AlternateText="Confirm" ImageUrl="~/Contest/Images/Confirm.png" onclick="SaveContestButton_Click" /&gt; &lt;/asp:Panel&gt; &lt;br /&gt; &lt;asp:Label ID="MessageLabel" runat="server" /&gt; &lt;/div&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="SaveContestButton" EventName="Click" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; &lt;/div&gt; &lt;uc:UpdatePanelAnimationExtender ID="upae" BehaviorID="animation" runat="server" TargetControlID="AddEditContestUpdatePanel"&gt; &lt;Animations&gt; &lt;OnUpdating&gt; &lt;Sequence&gt; &lt;%-- Store the original height of the panel --%&gt; &lt;ScriptAction Script="var b = $find('animation'); b._originalHeight = b._element.offsetHeight;" /&gt; &lt;%-- Disable all the controls --%&gt; &lt;Parallel duration="0"&gt; &lt;EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="false" /&gt; &lt;/Parallel&gt; &lt;StyleAction Attribute="overflow" Value="hidden" /&gt; &lt;%-- Do each of the selected effects --%&gt; &lt;Parallel duration=".25" Fps="30"&gt; &lt;FadeOut AnimationTarget="PanelContainer" minimumOpacity=".2" /&gt; &lt;Resize Height="0px" /&gt; &lt;/Parallel&gt; &lt;/Sequence&gt; &lt;/OnUpdating&gt; &lt;OnUpdated&gt; &lt;Sequence&gt; &lt;%-- Do each of the selected effects --%&gt; &lt;Parallel duration=".25" Fps="30"&gt; &lt;FadeIn AnimationTarget="PanelContainer" minimumOpacity=".2" /&gt; &lt;Length duration="2" fps="40" Property="style" PropertyKey="height" StartValue="10" EndValueScript="$get('animation').offsetHeight" AnimationTarget="animation" /&gt; &lt;%--Also tried the below &lt;Resize HeightScript="$find('animation')._originalHeight" /&gt; --%&gt; &lt;/Parallel&gt; &lt;%-- Enable all the controls --%&gt; &lt;Parallel duration="0"&gt; &lt;EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="true" /&gt; &lt;/Parallel&gt; &lt;/Sequence&gt; &lt;/OnUpdated&gt; &lt;/Animations&gt; &lt;/uc:UpdatePanelAnimationExtender&gt; &lt;/div&gt; </code></pre>
<p>Use the following function:</p> <pre><code>DATEADD(type, value, date) </code></pre> <ul> <li><p><strong>date</strong> is the date you want to manipulate</p> </li> <li><p><strong>value</strong> is the integere value you want to add (or subtract if you provide a negative number)</p> </li> <li><p><strong>type</strong> is one of:</p> </li> <li><p>yy, yyyy: year</p> </li> <li><p>qq, q: quarter</p> </li> <li><p>mm, m: month</p> </li> <li><p>dy, y: day of year</p> </li> <li><p>dd, d: day</p> </li> <li><p>wk, ww: week</p> </li> <li><p>dw, w: weekday</p> </li> <li><p>hh: hour</p> </li> <li><p>mi, n: minute</p> </li> <li><p>ss or s: second</p> </li> <li><p>ms: millisecond</p> </li> <li><p>mcs: microsecond</p> </li> <li><p>ns: nanosecond</p> </li> </ul> <pre><code>SELECT DATEADD(dd, 1, GETDATE()) -- will return a current date + 1 day </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms186819.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms186819.aspx</a></p>
<pre><code>DECLARE @date DateTime SET @date = GetDate() SET @date = DateAdd(day, 1, @date) SELECT @date </code></pre>
20,231
<p>Can anyone point to some code that deals with the security of files access via a path specified (in part) by an environment variable, specifically for Unix and its variants, but Windows solutions are also of interest?</p> <p><em>This is a big long question - I'm not sure how well it fits the SO paradigm.</em></p> <p>Consider this scenario:</p> <p><strong>Background:</strong></p> <ul> <li>Software package PQR can be installed in a location chosen by users.</li> <li>The environment variable $PQRHOME is used to identify the install directory.</li> <li>By default, all programs and files under $PQRHOME belong to a special group, pqrgrp.</li> <li>Similarly, all programs and files under $PQRHOME either belong to a special user, pqrusr, or to user root (and those are SUID root programs).</li> <li>A few programs are SUID pqrusr; a few more programs are SGID pqrgrp.</li> <li>Most directories are owned by pqrusr and belong to pqrgrp; some can belong to other groups, and the members of those groups acquire extra privileges with the software.</li> <li>Many of the privileged executables must be run by people who are not members of pqrgrp; the programs have to validate that the user is permitted to run it by arcane rules that do not directly concern this question.</li> <li>After startup, some of the privileged programs have to retain their elevated privileges because they are long-running daemons that may act on behalf of many users over their lifetime.</li> <li>The programs are not authorized to change directory to $PQRHOME for a variety of arcane reasons.</li> </ul> <p><strong>Current checking:</strong></p> <ul> <li>The programs currently check that $PQRHOME and key directories under it are 'safe' (owned by pqrusr, belong to pqrgrp, do not have public write access).</li> <li>Thereafter, programs access files under $PQRHOME via the full value of environment variable.</li> <li>In particular, the G11N and L10N is achieved by accessing files in 'safe' directories, and reading format strings for printf() etc out of the files in those directories, using the full pathname derived from $PQRHOME plus a known sub-structure (for example, $PQRHOME/g11n/en_us/messages.l10n).</li> </ul> <p>Assume that the 'as installed' value of $PQRHOME is /opt/pqr.</p> <p><strong>Known attack:</strong></p> <ul> <li>Attacker sets PQRHOME=/home/attacker/pqr.</li> <li>This is actually a symlink to /opt/pqr, so when one of the PQR programs, call it pqr-victim, checks the directory, it has correct permissions.</li> <li>Immediately after the security checking is completed successfully, the attacker changes the symlink so that it points to /home/attacker/bogus-pqr, which is clearly under the attacker's control.</li> <li>Dire things happen when the pqr-victim now accesses a file under the supposedly safe directory.</li> </ul> <p><strong>Given that PQR currently behaves as described, and is a large package (multiple millions of lines of code, developed over more than a decade to a variety of coding standards, which were frequently ignored, anyway), what techniques would you use to remediate the problem?</strong></p> <p><em>Known options include:</em></p> <ol> <li>Change all formatting calls to use function that checks actual arguments against the format strings, with an extra argument indicating the actual types passed to the function. (This is tricky, and potentially error prone because of the sheer number of format operations to be changed - but if the checking function is itself sound, works well.)</li> <li>Establish the direct path to PQRHOME and validate it for security (details below), refusing to start if it is not secure, and thereafter using the direct path and not the value of $PQRHOME (when they differ). (This requires all file operations that use $PQRHOME to use not the value from getenv() but the mapped path. For example, this would require the software to establish that /home/attacker/pqr is a symlink to /opt/pqr, that the path to /opt/pqr is secure, and thereafter, whenever a file is referenced as $PQRHOME/some/thing, the name used would be /opt/pqr/some/thing and not /home/attacker/pqr/some/thing. This is a large code base - not trivial to fix.)</li> <li>Ensure that all directories on $PQRHOME, even tracking through symlinks, are secure (details below, again), and the software refuses to start if anything is insecure.</li> <li>Hard-code the path to the software install location. (This won't work PQR; it makes testing hell, if nothing else. For users, it means they can have but one version installed, and upgrades etc require parallel running. This does not work for PQR.)</li> </ol> <p><em>Proposed criteria for secure paths:</em></p> <ul> <li>For each directory, the owner must be trusted. (<em>Rationale: the owner can change permissions at any time, so the owner must be trusted not to make changes at random that break the security of the software.</em>)</li> <li>For each directory, the group must either not have write privileges (so members of the group cannot modify the directory contents) or the group must be trusted. (<em>Rationale: if the group members can modify the directory, then they can break the security of the software, so either they must be unable to change it, or they must be trusted not to changed it.</em>)</li> <li>For each directory, 'others' must have no write privilege on the directory.</li> <li>By default, the users root, bin, sys, and pqrusr can be trusted (where bin and sys exist).</li> <li>By default, the group with GID=0 (variously known as root, wheel or system), bin, sys, and pqrgrp can be trusted. Additionally, the group that owns the root directory (which is called admin on MacOS X) can be trusted.</li> </ul> <p>The POSIX function <code>realpath()</code> provides a mapping service that will map /home/attacker/pqr to /opt/pqr; it does not do the security checking, but that need only be done on the resolved path.</p> <p><strong>So, with all that as background, is there any known software which goes through vaguely related gyrations to ensure its security? Is this being overly paranoid? (If so, why - and are you really sure?)</strong></p> <p><em>Edited:</em></p> <p>Thanks for the various comments.</p> <p>@S.Lott: The attack (outlined in the question) means that at least one setuid root program can be made to use a format string of the (unprivileged) user's choosing, and can at least crash the program and therefore most probably can acquire a root shell. It requires local shell access, fortunately; it is not a remote attack. It requires a non-negligible amount of knowledge to get there, but I consider it unwise to assume that the expertise is not 'out there'.</p> <p>So, what I'm describing is a 'format string vulnerability' and the known attack path involves faking the program out so that although it thinks it is accessing secure message files, it actually goes and uses the message files (which contain format strings) that are under the control of the user, not under the control of the software.</p>
<p>Option 2 works, if you write a new value for <code>$PQRHOME</code> after resolving its real path and check its security. That way very little of your code needs changing thereafter.</p> <p>As far as keeping the setuid privileges, it would help if you can do some sort of privilege separation, so that any operations involving input from the real user runs under the real uid. The privileged process and the real-uid process then talk using a <code>socketpair</code> or something like it.</p>
<p>Well, it <strong>sounds</strong> paranoid, but if it is or not depends on which system(s) your application is running on and which damage can an attacker do.</p> <p>So, if your userbase is possibly hostile and if the damage is possibly very high, I'd go for the option 4, but modified as follows to remove its drawbacks.</p> <p>Let me quote two relevant things:</p> <p>1)</p> <blockquote> <p>The programs currently check that $PQRHOME and key directories under it are 'safe' (owned by pqrusr, belong to pqrgrp, do not have public write access).</p> </blockquote> <p>2)</p> <blockquote> <p>Thereafter, programs access files under $PQRHOME via the full value of environment variable.</p> </blockquote> <p>You don't need to actually hard-code the full path, you can hard-code just the relative path from the "program" you mentioned in 1) to the path mentioned in 2) where the files are. </p> <p>Issue to control:</p> <p>a) you must be sure that there isn't anything "attacker-accessible" (e.g. in term of symlinks) in between the executable's path and the files' path</p> <p>b) you must be sure that the executable check its own path in a reliable way, but this should not be a problem in all the Unix'es I know (but I don't know all 'em and I don't know windows at all).</p> <hr> <p>EDITED after the 3rd comment:</p> <p>If your OS support /proc, the syslink /proc/${pid}/exe is the best way to solve b)</p> <hr> <p>EDITED after sleeping on it:</p> <p>Is the installation a "safe" process? If so, you might create (at installation time) a wrapper script. This script should be executable but not writable (and possibly neither readable). It would set the $PQRHOME env var to the "safe" value and then call your actual program (it might eventually do other useful things too). Since in UNIX the env vars of a running process <strong>cannot</strong> be changed by anything else but the running process, you are safe (of course the env vars <em>can</em> be changed by the parent <strong>before</strong> the process starts). I do not know if this approach works in Windows, though.</p>
23,845
<p>On a Windows 2003 server I have a pure .NET 3.5 <code>C#</code> app (no unmanaged code). It connects to various other remote systems via sockets and acts like a data hub. It runs for 10-15 hours fine with no problem but from time to time it just disappears. If I watch the app using task manager the memory usage remains constant.</p> <p>In the <code>Main()</code> function I wrap the invocation of the rest of the app in a <code>try .. catch</code> block which it just blows completely past - the catch block which logs the exception to a file is ignored. If I manually raise an exception for testing, the catch block is invoked.</p> <p>Prior to entering the <code>try .. catch</code> I do :</p> <pre><code>Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); </code></pre> <p>The system has Dr. Watson on it, but nothing gets written in the directory <code>DRWTSN32.EXE</code> is pointing to.</p> <p>How can I catch whatever exception is causing this?</p>
<p>Try using the debugging tools from microsoft. You can download them from <a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx" rel="noreferrer">here</a>.</p> <p>Use adplus to capture the crash and then windbg to analyze it.</p> <p>adplus -crash -pn your.exe -quiet</p> <p>Lots of great info about debugging on windows on this <a href="http://blogs.msdn.com/tess/" rel="noreferrer">blog</a>.</p>
<p>If it's a Windows Forms application, you could try <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx" rel="nofollow noreferrer"><code>Application.ThreadException</code></a>.</p>
33,701
<p>Rehsarper 4.0 - Renaming a class does not rename the file…<br> I probably set something on accident in the options, but I can't find it. Any ideas?</p>
<p>When I do a rename in Resharper there's a checkbox below the textbox where you type the new name that says "Synchronise file name with class name". Check that and the file is renamed too.</p> <p>Be sure you're using Resharper's rename (right-click/Refactor/Rename) rather than Visual Studio's (right-click/Rename), as the latter definitely doesn't rename the file.</p>
<ol> <li>Go to the class name and click Ctrl+R+R</li> <li>Set the new name</li> <li>select the check box &quot;Also rename files to reflect this change.&quot;</li> </ol>
7,873
<p>I am trying out the debugger built into <code>Zend studio</code>. It seems great! One thing though, when I start a page using the debugger does anyone know how I can set a request get argument within the page?</p> <p>For example, I don't want to debug runtests.php</p> <p>I want to debug <code>runtests.php?test=10</code></p> <p>I assume its a simple configuration and I just can't find it.</p>
<p>Just start the debugger on another page, and then change the browser url to what you wanted. It's not ideal but it should work.</p> <p>I have high hopes for their next release.</p>
<p>I recommend getting the <a href="http://www.zend.com/en/products/studio/downloads" rel="nofollow noreferrer">Zend Studio Toolbar</a>. The extension allows you to control which pages are debugged from within the browser instead of from Zend Studio. The options for debugging let you debug the next page, the next form post or all pages. When you debug like this it runs the PHP just like it will from your server instead of from within Zend Studio. It's an essential tool when using Zend Studio. </p>
9,473
<p>Problem: I have an address field from an Access database which has been converted to SQL Server 2005. This field has everything all in one field. I need to parse out the address's individual sections into their appropriate fields in a normalized table. I need to do this for approximately 4,000 records, and it needs to be repeatable.</p> <p>Assumptions:</p> <ol> <li><p>Assume an address in the US (for now)</p> </li> <li><p>assume that the input string will sometimes contain an addressee (the person being addressed) and/or a second street address (i.e. Suite B)</p> </li> <li><p>states may be abbreviated</p> </li> <li><p>zip code could be standard 5 digits or zip+4</p> </li> <li><p>there are typos in some instances</p> </li> </ol> <p>UPDATE: In response to the questions posed, standards were not universally followed; I need need to store the individual values, not just geocode and errors means typo (corrected above)</p> <p>Sample Data:</p> <ul> <li><p>A. P. Croll &amp; Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947</p> </li> <li><p>11522 Shawnee Road, Greenwood DE 19950</p> </li> <li><p>144 Kings Highway, S.W. Dover, DE 19901</p> </li> <li><p>Intergrated Const. Services 2 Penns Way Suite 405 New Castle, DE 19720</p> </li> <li><p>Humes Realty 33 Bridle Ridge Court, Lewes, DE 19958</p> </li> <li><p>Nichols Excavation 2742 Pulaski Hwy Newark, DE 19711</p> </li> <li><p>2284 Bryn Zion Road, Smyrna, DE 19904</p> </li> <li><p>VEI Dover Crossroads, LLC 1500 Serpentine Road, Suite 100 Baltimore MD 21</p> </li> <li><p>580 North Dupont Highway Dover, DE 19901</p> </li> <li><p>P.O. Box 778 Dover, DE 19903</p> </li> </ul>
<p>I've done a lot of work on this kind of parsing. Because there are errors you won't get 100% accuracy, but there are a few things you can do to get most of the way there, and then do a visual BS test. Here's the general way to go about it. It's not code, because it's pretty academic to write it, there's no weirdness, just lots of string handling.</p> <p>(Now that you've posted some sample data, I've made some minor changes)</p> <ol> <li>Work backward. Start from the zip code, which will be near the end, and in one of two known formats: XXXXX or XXXXX-XXXX. If this doesn't appear, you can assume you're in the city, state portion, below.</li> <li>The next thing, before the zip, is going to be the state, and it'll be either in a two-letter format, or as words. You know what these will be, too -- there's only 50 of them. Also, you could soundex the words to help compensate for spelling errors.</li> <li>before that is the city, and it's <em>probably</em> on the same line as the state. You could use a <a href="http://zipinfo.com" rel="noreferrer">zip-code database</a> to check the city and state based on the zip, or at least use it as a BS detector.</li> <li>The street address will generally be one or two lines. The second line will generally be the suite number if there is one, but it could also be a PO box.</li> <li>It's going to be near-impossible to detect a name on the first or second line, though if it's not prefixed with a number (or if it's prefixed with an "attn:" or "attention to:" it could give you a hint as to whether it's a name or an address line.</li> </ol> <p>I hope this helps somewhat.</p>
<p>There are data services that given a zip code will give you list of street names in that zip code.</p> <p>Use a regex to extract Zip or City State - find the correct one or if a error get both. pull the list of streets from a <a href="http://www.melissadata.com/lookups/zipstreet.asp" rel="nofollow noreferrer">data source</a> Correct the city and state, and then street address. Once you get a valid Address line 1, city, state, and zip you can then make assumptions on address line 2..3</p>
3,712
<p>I need to create a news ticker that is updated via an RSS feed. Any ideas on how to implement this?</p> <p>I would prefer Javascript but any language is acceptable.</p>
<p>There are are several good examples of this on <a href="http://www.dynamicdrive.com/dynamicindex17/rsstickerajax/index.htm" rel="nofollow noreferrer">this DynamicDrive page</a>, although one of the requirements is that you can run PHP on your site. PHP here is used to fetch the actual feeds and allow your ticker to access them locally via an AJAX call.</p> <p>There are several other projects out there built on JQuery, and the basic approach taken by each is:</p> <ul> <li><p>use a PHP (or ASP.net) script to fetch the feed to your server. </p></li> <li><p>access this local file via repeated AJAX calls, making use of <a href="http://www.w3schools.com/js/js_timing.asp" rel="nofollow noreferrer">setTimeout</a></p></li> <li><p>update the display (ticker) with latest data fetched</p></li> </ul> <p>The file is fetched to your local server for the AJAX calls due to the <a href="http://en.wikipedia.org/wiki/Same_origin_policy" rel="nofollow noreferrer">Same Origin Policy</a>:</p> <blockquote> <p>It prevents a document or script loaded from one "origin" from getting or setting properties of a document from a different "origin".</p> </blockquote> <p><hr> Further examples include:</p> <ul> <li><p><a href="http://www.jasons-toolbox.com/JTicker/" rel="nofollow noreferrer">JTicker from Jason's Toolbox</a></p></li> <li><p><a href="http://blogs.atalayasec.org/dev/2008/02/jquery-rss-feed-reader-plugin/" rel="nofollow noreferrer">JQuery feed plugin</a> - need to read the comments on this one, as code originally posted doesn't seem to work out of the box</p></li> </ul>
<p>If you really have a nice niche market where your news ticker could be very popular, you might want to 'be on their desktop' and develop a widget with <a href="http://www.adobe.com/products/air/" rel="nofollow noreferrer">Adobe Air</a>.</p> <p>You can create a nice scrolling ticker then with any javascript you like (or flash/flex, that's supported too)</p>
20,804
<p>What is the proper way to give printer settings to CuraEngine? Is it possible to put all these settings into a file (like Json formatted)?</p> <pre><code>CuraEngine.exe -v -o "c:\3d\test.gcode" "c:\3d\test.stl" </code></pre>
<p>I'm not sure if it's possible, but on github is code for setting CuraEngine up. Maybe you'll find this link, <a href="https://github.com/Ultimaker/CuraEngine/blob/master/src/settings/settings.cpp" rel="nofollow noreferrer"> CuraEngine/src/settings/settings.cpp</a> helpful. </p> <p>The latest release has more speed customization. You can change first layer speed, outer shell speed, inner shell speed, infill speed, and top and bottom speed.</p> <p>You can cut objects, its just a little wonky. In the advanced tab there is a "cut off object at Z height" that you can use to cut objects in half.</p> <p>Theoretically, you can put all settings into a JSON formatted file. </p>
<p>I'm not sure if it's possible, but on github is code for setting CuraEngine up. Maybe you'll find this link, <a href="https://github.com/Ultimaker/CuraEngine/blob/master/src/settings/settings.cpp" rel="nofollow noreferrer"> CuraEngine/src/settings/settings.cpp</a> helpful. </p> <p>The latest release has more speed customization. You can change first layer speed, outer shell speed, inner shell speed, infill speed, and top and bottom speed.</p> <p>You can cut objects, its just a little wonky. In the advanced tab there is a "cut off object at Z height" that you can use to cut objects in half.</p> <p>Theoretically, you can put all settings into a JSON formatted file. </p>
213
<p>I’m attempting to check the rights on a particular file for a specific trustee and am using the win32 API GetEffectiveRightsFromAcl(). When the file is accessible by a domain group, the function returns 5 (Access Denied) when a local account (admin or other) is used to execute the function.</p> <p>These three statements summarize the behavior I am seeing with GetEffectiveRightsFromAcl():</p> <ul> <li>When domain group has rights to the file and the program runs under a local account: Access Denied.</li> <li>When domain group has rights to the file and the program runs under a domain account or Local System: Success</li> <li>When domain group doesn't have rights to the file and the program runs under any account: Success</li> </ul> <p>Does anyone know the reason behind this? It looks to me like this is related to Active Directory security. What settings could affect this and what would be a good way to debug this? </p> <p>Also, I've heard that GetEffectiveRightsFromAcl() may be generally problematic and to use AccessCheck() instead. However I need to be able to take an arbitrary SID and check it's access against a file and since AccessCheck() requires an impersonation token I don't know how I could greate a token out of an arbitrary SID... Any ideas? Thanks</p> <p>Bob</p>
<ul> <li>if domain group have right to the file, this function has to access the active directory to enumerate the group membership of the trustee ( at least if it is a domain user ). If your program is running under local account, then this account don't have right to access the active directory, hence the error return code.</li> <li>domain account and Local System have access to the active directory. Local system is the computer account in the active directory( computers are like users in AD).</li> <li>If no domain group has access to the file, the function don't have to check with the active directory. So local users succeed too.</li> </ul>
<ul> <li>if domain group have right to the file, this function has to access the active directory to enumerate the group membership of the trustee ( at least if it is a domain user ). If your program is running under local account, then this account don't have right to access the active directory, hence the error return code.</li> <li>domain account and Local System have access to the active directory. Local system is the computer account in the active directory( computers are like users in AD).</li> <li>If no domain group has access to the file, the function don't have to check with the active directory. So local users succeed too.</li> </ul>
47,532
<p>When i compile the application in my laptop it runs fine but when i run the same application in the server something is wrong with the date format. But when i checked the system date time format wit my laptop and server it the same format. Can anyone tell me what is wrong.</p>
<p>You also have to check the default culture set in the laptop and the server. Are they running in the same culture? Different culture settings will have different default time formats.</p>
<p>Is the system clock running UTC, and the OS changing it to local time on the server. This is a pretty common configuration, but will break programs that bypass the OS's functions to retrieve the date/time.</p>
12,413
<p>Is that possible to switch an Open Source Project license from <a href="http://opensource.org/licenses/gpl-2.0.php" rel="nofollow noreferrer">GPL</a> to <a href="http://opensource.org/licenses/lgpl-3.0.html" rel="nofollow noreferrer">LGPL v3</a> ?</p> <p>I am the project originator and the only contributor.</p>
<p>yes, of course. You can change the licence to whatever you want.</p> <p>Go to your admin page, then edit registration from the menu, view Public Info, then edit the Trove categorisation. You need to remove then add a new category. Easy (if a little link-happy).</p> <p>This applies if you're an admin of the project, no matter how many of you there are or who has contributed.</p>
<p>AFAIK, you can do that if you're the only contributor to the source code, irrespective of whether you're the original author or lead developer.</p> <p>If you can get approval from all the contributors, then you can change the license.</p> <p>Warning: IANAL.</p>
11,821
<p>I'm looking at the output from spring being loaded up by tomcat and there's something very strange...Everything is duplicated. What would cause this? Whatever it is, it's causing my application to run in odd ways.</p> <p><strong>Additional Info:</strong></p> <p>The application is a web app. All the spring information is loaded using the context loader(?) defined in the web.xml file. My configuration files are split amoung 6 (or so) files.</p> <p>Example debug output:</p> <blockquote> <p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [REQUIRES_SECURE_CHANNEL]</p> <p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [REQUIRES_SECURE_CHANNEL]</p> <p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [ROLE_READ, ROLE_UPDATE]</p> <p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [ROLE_READ, ROLE_UPDATE]</p> <p>[DEBUG,AbstractFallbackMethodDefinitionSource,main] Adding security method [CacheKey[com.service.impl.FooServiceImpl; public abstract java.lang.Boolean com.service.IFooService.saveOrUpdateFoo(com.model.Foo2,java.lang.String) throws org.springframework.dao.DataAccessException]] with attribute [[ROLE_UPDATE]]</p> <p>[DEBUG,AbstractFallbackMethodDefinitionSource,main] Adding security method [CacheKey[com.service.impl.FooServiceImpl; public abstract java.lang.Boolean com.service.IFooService.saveOrUpdateFoo(com.model.Foo2,java.lang.String) throws org.springframework.dao.DataAccessException]] with attribute [[ROLE_UPDATE]]</p> <p>[INFO,AbstractSecurityInterceptor,main] Validated configuration attributes</p> <p>[INFO,AbstractSecurityInterceptor,main] Validated configuration attributes</p> </blockquote>
<p>Are you sure that something in the logging configuration isn't adding each category/logger to the appender more than once?</p> <p>That's something that's possible with log4j, not sure about JCL or whatever the latest version of Tomcat uses under the cover.</p>
<p>In Tomcat, if your application is configured to be the default application it must be deployed under the /root directory. If not, then Tomcat will launch 2 copies of your application, one where you put it, and one where it expects the default to be. </p> <p>That could explain what is happening here, assuming that I recall all of that correctly.</p>
30,334
<p>I have a JSP page that will display the exact content of another web page on a different server. My understanding was that c:import from the JSTL should be able to include content from files that are not part of the current web application.</p> <p>I added c:import url="page on my server in a different application" and it works fine, but when I try to include a page from another server it fails.</p> <p>Any suggestions as to what might be wrong?</p> <p><strong>EDIT:</strong> The exact error is: "The server encountered an internal error () that prevented it from fulfilling this request.". However, requesting a page from the same server, different app works...I get the content of the page.</p>
<p>I had a similar error once. It turned out to be that the machine that I was running the app on had some problems connecting to the internet through the firewall. Once I deployed the app to a machine that was always connected it worked fine.</p>
<p>If it works from the same server, different app, makes it possible that there's a variable that's not being initialized somewhere, or some state which makes it throw an exception. Check the error logs for any stack traces that could point to the specific line of code that's causing the problem.</p>
28,215
<p>I have been sold on the fun of using linq in areas other than pure database interaction. (See <a href="https://stackoverflow.com/questions/365352/calling-fellow-code-nerds-alternatives-to-nested-loops">Calling fellow code nerds - Alternatives to Nested Loops?</a>).</p> <p>We are stuck on 2.0. I have told the powers that be about the ease of updating to 3.5 (we have already migrated to VS2008) but they are wanting a list of "benefits" for upgrading.</p> <p>Can those that have experience in 3.5 help provide some talking points for the benefits of updating an existing app to 3.5?</p> <p>UPDATE: Found an additional reason: Microsoft's inclusion of Charting tools for Asp.Net as a patch on top of 3.5! They get their business value, I get the fun...</p>
<p>Can YOU make a case for it? Sounds like you want it because LINQ is fun. Other people are mentioning features that are <em>fun</em>. I've always had a problem selling <em>fun</em> features to management because they aren't very compelling reasons to potentially disrupt an environment.</p> <p>Honestly, it really depends on what you are using C# for. Are you a web developer, system admin, something else? Taking a general approach, I would use the following selling points (you will need to do some work to prove these things):</p> <ol> <li><strong>Zero-disruption for end-users when upgrading.</strong> Upgrading to the new version will be seamless and we will have a thoroughly reviewed test plan for updating all clients to this version. All of our old applications that require .NET 1.x or .NET 2.0 will still work perfectly.</li> <li><strong>Programmer Efficiency</strong>. You could mention how more of the Windows API is wrapped by .NET classes, thus making programmer more efficient because they don't have to P/Invoke as much. LINQ makes your more productive because of x, y, and z. Lambda expressions make you more productive because of x, y, and z.</li> <li><strong>Ease pains of future OS migration</strong>. Moving to WPF now will prepare us for Vista/Windows 7. We won't have to migrate applications using the now deprecated "Windows Forms" to WPF, because we will already be using it.</li> <li><strong>More applications purchased from 3rd parties will require it</strong>, so we will have to upgrade sooner or later.</li> </ol> <p>In the end, you need to prove that at the very least, this move will not cost you money in terms of increased support or testing costs. If you can show it will make you be more productive and it will be a rather painless switch, then you will get your wish.</p>
<p>In my experience, the addition of LINQ and Extension methods alone have made many previously arduous and/or time consuming tasks much easier and faster. The increased developer productivity from that alone is worth the upgrade effort IMHO.</p>
48,196
<p>My background is primarily as a Java Developer, but lately I have been doing some work in .NET. So I have been trying to do some simple projects at home to get better at working with .NET. I have been able to transfer much of my Java experience into working with .NET (specifically C#), but the only thing that has really perplexed me is namespaces.</p> <p>I know namespaces are similar to Java packages, but as from what I can tell the main difference is that with Java packages they use actual file folders to show the seperation, while in .NET it does not and all the files reside in a single folder and the namespace is simply declared in each class.</p> <p>I find this odd, because I always saw packages as a way to organize and group related code, making it easier to navigate and comprehend. Since in .NET it does not work this work this way, overtime, the project appears more overcrowded and not as easy to navigate.</p> <p>Am I missing something here? I have to be. Should I be breaking things into separate projects within the solution? Or is there a better way to keep the classes and files organized within a project?</p> <p>Edit: As Blair pointed out this is pretty much the same question asked <a href="https://stackoverflow.com/questions/4664/should-the-folders-in-a-solution-match-the-namespace">here</a>.</p>
<p>I can't claim that it's a best practice, but I often see files organized in a directory hierarchy that mirrors the namespace. If it fits your mental model of the code better, then do so - I can't think of any harm. Just because the .NET model doesn't enforce relationships between namespaces, projects, and directory structure doesn't mean you can't have such relationships if you want to.</p> <p>I'd be a little leery of breaking up the code into more projects than you need, as this can slow compilation and add a little bit of overhead when you have to manage multiple assemblies.</p> <p>EDIT: Note that this question is nearly a duplicate of <a href="https://stackoverflow.com/questions/4664/should-the-folders-in-a-solution-match-the-namespace">should the folders in a solution match the namespace?</a></p>
<p>I've always considered source file organization and assigning identifiers to classes and objects to be two separate problems. I tend to keep related classes in groups, but not every group should be a namespace. Namespaces exist (more or less) to solve the problem of name conflicts—in flat-namespace languages like C, you can't walk two feet without tripping over identifiers like <code>mycompany_getcurrentdate</code> or <code>MYCGetCurrentDate</code>, because the risk of a conflict with another function in a third-party (or system) library is that much smaller. If you created a package or namespace for every logical separation, you would get (Java example) class names like <code>java.lang.primitivewrapper.numeric.Integer</code>, which is pretty much overkill.</p>
7,950
<p>I have a textbox with the <strong>Text</strong> property bound to a dataset column with the DataType set to System.DateTime.<br> The FormatString on the Binding is set to <strong>dd-MM-yyyy</strong>.</p> <p>When the user enters a date it attempts to convert it to a date but can come up with some strange values for a seemingly invalid date.</p> <p>For example:</p> <pre><code>textBox1.Text = "01-02-200"; </code></pre> <p>Should be an invalid date but it formats it as <strong>01-02-0200</strong>.</p> <p>Is there an easy way to catch these out-of-bounds values either through setting a valid range or overriding an event on the binding/textbox?</p>
<p>A .NET DateTime is in the range 01/01/0001 to 31/12/9999 23:59:59.9999999, so 01/01/200 is considered to be valid.</p> <p>You can validate the input and restrict the range: the Validating event would be the place to do your validation. You'll need to parse the string into a DateTime and validate its range.</p> <p>The allowed range will be application dependent. For example, the following code will restrict the datetime to values that can be stored in a SQL Server 2005 DATETIME column (01-01-1753 to 31-12-999):</p> <pre><code>private void textBox1_Validating(object sender, CancelEventArgs e) { DateTime date; if (!DateTime.TryParseExact(textBox1.Text, "dd-MM-yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out date)) { MessageBox.Show(textBox1.Text + " is not a valid date"); textBox1.Focus(); e.Cancel = true; return; } if ((date &lt; (DateTime) System.Data.SqlTypes.SqlDateTime.MinValue) || (date &gt; (DateTime) System.Data.SqlTypes.SqlDateTime.MaxValue)) { MessageBox.Show(textBox1.Text + " is out of range"); textBox1.Focus(); e.Cancel = true; return; } } </code></pre>
<p>Any reason not to use a date picker control instead of a textbox? Would solve validation problem and probably make it a better experience for the user.</p>
31,012
<p>What is the difference between <strong><code>const</code></strong> and <strong><code>readonly</code></strong> in C#? </p> <p>When would you use one over the other?</p>
<p>Apart from the apparent difference of</p> <ul> <li>having to declare the value at the time of a definition for a <code>const</code> VS <code>readonly</code> values can be computed dynamically but need to be assigned before the constructor exits. After that it is frozen.</li> <li><code>const</code>'s are implicitly <code>static</code>. You use a <code>ClassName.ConstantName</code> notation to access them.</li> </ul> <p>There is a subtle difference. Consider a class defined in <code>AssemblyA</code>.</p> <pre><code>public class Const_V_Readonly { public const int I_CONST_VALUE = 2; public readonly int I_RO_VALUE; public Const_V_Readonly() { I_RO_VALUE = 3; } } </code></pre> <p><code>AssemblyB</code> references <code>AssemblyA</code> and uses these values in code. When this is compiled:</p> <ul> <li>in the case of the <code>const</code> value, it is like a find-replace. The value 2 is 'baked into' the <code>AssemblyB</code>'s IL. This means that if tomorrow I update <code>I_CONST_VALUE</code> to 20, <em><code>AssemblyB</code> would still have 2 till I recompile it</em>.</li> <li>in the case of the <code>readonly</code> value, it is like a <code>ref</code> to a memory location. The value is not baked into <code>AssemblyB</code>'s IL. This means that if the memory location is updated, <code>AssemblyB</code> gets the new value without recompilation. So if <code>I_RO_VALUE</code> is updated to 30, you only need to build <code>AssemblyA</code> and all clients do not need to be recompiled.</li> </ul> <p>So if you are confident that the value of the constant won't change, use a <code>const</code>.</p> <pre><code>public const int CM_IN_A_METER = 100; </code></pre> <p>But if you have a constant that may change (e.g. w.r.t. precision) or when in doubt, use a <code>readonly</code>.</p> <pre><code>public readonly float PI = 3.14; </code></pre> <p><em>Update: Aku needs to get a mention because he pointed this out first. Also I need to plug where I learned this: <a href="https://rads.stackoverflow.com/amzn/click/com/0321245660" rel="nofollow noreferrer" rel="nofollow noreferrer">Effective C# - Bill Wagner</a></em></p>
<p>One thing to add to what people have said above. If you have an assembly containing a readonly value (e.g. readonly MaxFooCount = 4; ), you can change the value that calling assemblies see by shipping a new version of that assembly with a different value (e.g. readonly MaxFooCount = 5;)</p> <p>But with a const, it would be folded into the caller's code when the caller was compiled.</p> <p>If you've reached this level of C# proficiency, you are ready for Bill Wagner's book, Effective C#: 50 Specific Ways to Improve Your C# Which answers this question in detail, (and 49 other things).</p>
7,986
<p>Our team is migrating from VSS 6.0 to TFS 2008 to be used for source control purposes. I am wondering if anyone has any experience with this migration. In particular, we are interested in preserving the history of files in source control, as well as any other potential gotchas.</p>
<p>This is fairly easy once setup. You will first need to create a usermap.xml. This will map your VSS users to your TFS2008 users. Then you create a project configuration file. I would post examples of mine but I can't get the XML to post.</p> <p>The project configuration file will point to the usermap XML file. Then all you have to do is type the command "VSSConverter migrate settings.xml" to migrate or "VSSConverter analyze settings.xml" to analyze the project. I suggest you to analze before migrating the project.</p> <p>Here is a link for more information. <a href="http://msdn.microsoft.com/en-us/library/ms253090(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms253090(VS.80).aspx</a></p>
<p>Unfortunately, when I tried this...</p> <p>TF60032: The VSS Converter requires Visual SourceSafe 2005 or later to run. Please install Visual SourceSafe 2005 or later and try again.</p>
45,959
<p>I've run into strange problem in my Flex/Flashcom application. If client application unexpectedly disconnects from server latter does not call application.onDisconnect handler function. In witch direction should I look? Thank you.</p> <p><strong>Update</strong> I'm not using server components, but I do host this thing on Linux.</p>
<p>If so, it's documented and <a href="https://www.adobe.com/cfusion/webforums/forum/messageview.cfm?forumid=15&amp;catid=578&amp;threadid=1401786&amp;enterthread=y" rel="noreferrer">here</a> an interesting forum to follow..basically on Linux it may work a bit crazy like :)</p>
<p>It's possible that a client is disconnected before the (Flash Media-) server 'knows' about this. So no 'onDisconnect' function gets invoked (it <em>never</em> gets called by the client) until very, very late.</p> <p>If you want to detect (and act upon) "lingering" disconnects early, use the client.getStats() method.</p> <p>I have this server-side actionscript example:</p> <pre><code>// add method to standard class Client.prototype.isAlive = function() { var stats = this.getStats(); var timeout_value = 3 * 1000; // in ms. //trace('Measured timeout: ' + stats['ping_rtt']); if (stats) return (stats['ping_rtt'] &lt; timeout_value); } // use this in an interval which traverses the application.clients list if (! client.isAlive()) application.disconnect(client); </code></pre> <p>You can trigger and test this 'missing onDisconnect' behavior by removing the network cable from the connected Flash client.</p>
46,928
<p>I am running into a very strange issue with PHP 5.2.6 w/ IIS on Windows XP (have tried both CGI and ISAPI). I am running a fresh installation with the default php.ini settings. </p> <p>First, assume the following (ugly, but effective) HTML code:</p> <pre><code>&lt;form action="&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;" method="post"&gt; &lt;input type="hidden" name="test1" value="foo" /&gt; &lt;input type="hidden" name="test2" value="bar" /&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;br /&gt;&lt;br /&gt; &lt;pre&gt; &lt;?php print_r($_POST); ?&gt; &lt;/pre&gt; </code></pre> <p>When the form is submitted, I expect it to bring out an array containing the two hidden variables. Instead all I see is an empty array. If I change the form method to "get" and change print_r($_POST) to print_r($_GET), I see the array items with no problem.</p> <p>I have tried variations such as <code>&lt;?php print file_get_contents('php://input'); ?&gt;</code> and <code>&lt;?php echo print_r($HTTP_POST_VARS); ?&gt;</code> to no avail. Any ideas where the problem might lie?</p>
<p>Well, if it's any consolation your code works as intended in PHP5 with Apache.</p> <p>A quick Google revealed a couple other people with the same problem but no definitive solution - closest thing was <a href="http://bytes.com/archives/php/389664-_post-problem-php5-iis" rel="nofollow noreferrer">this</a>...</p> <blockquote> <p>Check your IIS configuration and see what verbs are permitted for PHP. My guess is that POST isn't included. You should have GET and POST enabled at a minimum, or just make your life easy and allow all verbs.</p> </blockquote> <p>Make sure you update your question if you find a solution; I'm sure other people will benefit.</p>
<p>Well, I just had the same issue. </p> <p>The PHP.ini file is picky...make sure you don't have "GB" where it should be "G". I had my "post_max_size" at 1GB instead of 1G, PHP ran fine, except for POST requests.</p>
40,375
<p>I tried to package a Twisted program with py2exe, but once I run the exe file I built, I got a "No module named resource" error. </p> <p>And I found the py2exe said:</p> <blockquote> <p>The following modules appear to be missing ['FCNTL', 'OpenSSL', 'email.Generator', 'email.Iterators', 'email.Utils', 'pkg_resources', 'pywintypes', 'resource', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security']</p> </blockquote> <p>So how do I solve this problem?</p> <p>Thanks.</p>
<p>I've seen this before... py2exe, for some reason, is not detecting that these modules are needed inside the ZIP archive and is leaving them out.</p> <p>You can explicitly specify modules to include on the py2exe command line:</p> <pre><code>python setup.py py2exe -p win32com -i twisted.web.resource </code></pre> <p>Something like that. Read up on the options and experiment.</p>
<p>Had same issue with email module. I got it working by explicitly including modules in setup.py:</p> <p>OLD setup.py:</p> <pre><code>setup(console = ['main.py']) </code></pre> <p>New setup.py:</p> <pre><code>setup(console = ['main.py'], options={"py2exe":{"includes":["email.mime.multipart","email.mime.text"]}}) </code></pre>
20,505
<p>I'm trying to write a html helper extension that outputs an image tag. I need to access (within C# code) something like Razor's @Url.Content() helper to get the proper URL for the current context. How does one do this?</p>
<p>Use the following to mimic Url.Content in code.</p> <pre><code>VirtualPathUtility.ToAbsolute("~/url/"); </code></pre>
<p>You can get to the Request object and thus the URL like this:</p> <pre><code>string fullUrl = HttpContext.Current.Request.Url.AbsoluteUri; </code></pre>
45,828
<p>I am seeking insight on how to have each row in a Gridview expand to show a DIV or PANEL that has a form of elements, i.e. a simple form of textboxes, etc. I don't need a nested Gridview showing results or using DynamicPopulate.</p> <p>I have tried some techniques from a DataGrid Expandable Row, but ran into some problems trying to access variables that just aren't a part of the Gridview. I could essentially do this using the Editable Templates in the Gridview, but I need a much cleaner solution.</p>
<p>I was able to do this successfully by injecting a div within a div underneath each gridview row created. Once there, I was able to give them unique ids based on the data I was using, call an expand function in javascript, and expand/collapse the divs as I wished.</p> <p>This is fairly doable with a gridview, but a repeater would also work as well as a simple AJAX implementation returning a table structure.</p> <p>Here is a very similar example to what I did:</p> <p><a href="http://www.codeproject.com/KB/ajax/ExpandPanelGridView.aspx?display=Print" rel="nofollow">http://www.codeproject.com/KB/ajax/ExpandPanelGridView.aspx?display=Print</a></p>
<p>If you can afford it, there are many gridview controls that are ajaxified and have the ability to expand each row as needed. I use one set of controls from a company who shall remain nameless (for now) and have been extremely happy with them.</p> <p>Do a google search on gridview controls.</p>
38,780
<p>Within my Subversion project I have a few directories that contain other open source projects that my code needs. For example ffmpeg, freetype, matrixssl and a few others. </p> <p>What is the best way to update SVN to hold the the latest version of one of these projects?</p> <p>Essentially I will be doing the following (using ffmpeg as an example):</p> <pre><code>1) Rename current ffmpeg folder to ffmpeg.old 2) Download new version of ffmpeg from net 3) Make sure it and my code compile and work fine together 4) Update subversion to now hold the "new" version of ffmpeg 5) Delete ffmpeg.old directory tree </code></pre>
<p>You can take a look to svnbook talking about <a href="http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.advanced.vendorbr" rel="noreferrer">vendor branches</a>. This is exactly what you try to accomplish</p> <p>You can use <strong>svn_load_dirs.pl</strong> to replace your manual steps 1-5. svn_load_dirs.pl will also keep track of new, moved or deleted files.</p>
<p>I think you've got two options.</p> <p><strong>A)</strong></p> <ol> <li>SVN Delete all the files.</li> <li>Get current &amp; make it work.</li> <li>SVN Add all the files.</li> </ol> <p>Pro: Will make sure no extra files are kept if they are not present in the latest version.</p> <p>Con: May be time consuming.</p> <p><strong>B)</strong></p> <ol> <li>Download and install the new version over the old one.</li> <li>Make it work.</li> <li>SVN add any new files.</li> </ol> <p>Pro: You can see what has changed in the files of the tool.</p> <p>Con: May end up with clutter. Depending upon the tool overwriting may cause bugs.</p>
23,443
<p>How can I measure runtime memory requirements of an application on windows platform?</p>
<p>Perfmon.exe will monitor the usage of a process.</p> <p>Run perfmon.exe, right-click Add counters, pick Process for the Performance Object, then choose things like Virtual Bytes, Working Set, and Page File.</p>
<p>"Memory requirements" are not very well defined, in the first place. WHen you start, your executabel will be linked to many DLLs. Together with the first stack, this forms your initial process. Then, your proces might start extra threads, allocate more memory, and/or memory map some files. </p> <p>Now Wwindows won't give you real RAM for all these needs. Many DLLs are already loaded for other reasons, so you'll share that RAM. Extra RAM for stacks is allocated when you get soft stackoverflows. Memory mapped files get RAM allocated when those pages fault.</p> <p>So, one of the important questions is what you really want. You have to answer that first.</p>
47,629
<p>How to unit test WCF services? Any 3rd Party tools available?</p>
<p>As aku says, if you're testing service methods (ie code behaviour) then you can unit test that directly and bypass the WCF infrastructure. Of course, if your code depends on WCF context classes (like OperationContext) then I suggest introducing wrappers much like ASP.NET MVC does for HttpContext.</p> <p>For testing connectivity, it will depend on the type of endpoints you have configured. In some cases you can just self-host your WCF service inside the unit test (like you would with a WCF Windows Service) and test that. </p> <p>However, you may need to spin up the ASP.NET Development Web Server or even IIS if you want to test WCF behaviour specific to those hosting environments (ie SSL, authentication methods). This gets tricky and can start making demands on the configuration of everyone's development machine and the build servers but is doable.</p>
<p>I have seen <a href="http://www.parasoft.com/jsp/solutions/soa_solution.jsp?itemId=319" rel="nofollow noreferrer">SOA Test</a> used to evaluate performance and scalability tests on WCF services, if this is what you seek. I have no information on cost or liscencing.</p> <p>In our case, we captured the messages from our UI in order to perform automated testing.</p>
18,381
<p>I have the following problem. If I query values with a keyfigure which is a function I can't specify multiple values of the same dimension restriction, but if it is not a function it works.</p> <p>So this works:</p> <pre><code>SELECT {[Measures].[Netto]} on columns FROM TDC where ({NonEmpty([Time].[Month].[Month].&amp;[2008-03-01T00:00:00]), NonEmpty([Time].[Month].[Month].&amp;[2008-04-01T00:00:00])}) </code></pre> <p>But this doesn't:</p> <pre><code>SELECT {[Measures].[CalculatedFunction]} on columns FROM TDC where ({NonEmpty([Time].[Month].[Month].&amp;[2008-03-01T00:00:00]), NonEmpty([Time].[Month].[Month].&amp;[2008-04-01T00:00:00])}) </code></pre> <p>And this also works:</p> <pre><code>SELECT {[Measures].[CalculatedFunction]} on columns FROM TDC where ({NonEmpty([Time].[Month].[Month].&amp;[2008-03-01T00:00:00])}) </code></pre> <p>I guess the solution is something like adding the where clause to the header but I really like this solution because it's so simple.</p> <p>The Calucated function is:</p> <pre><code>CREATE MEMBER CURRENTCUBE.[MEASURES].Ultimo AS (iif ((not [Time].[Year - Month - Date].currentmember is [Time].[Year - Month - Date].defaultmember), IIF(NOT ([Measures].[LagerStk] = 0), Sum([Time].[Year - Month - Date].[Date].members(0): ClosingPeriod([Time].[Year - Month - Date].[Date]), [Measures].[LagerStk]), NULL) , IIF(NOT ([Measures].[LagerStk] = 0), Sum([Time].[Year - Week - Date].[Date].members(0): ClosingPeriod([Time].[Year - Week - Date].[Date]), [Measures].[LagerStk]), NULL))), VISIBLE = 1; </code></pre> <p>The code is inspired from this and modified for two hierarchies in the time dimension: <a href="http://www.sqlserveranalysisservices.com/OLAPPapers/InventoryManagement%20in%20AS2005v2.htm" rel="nofollow noreferrer">http://www.sqlserveranalysisservices.com/OLAPPapers/InventoryManagement%20in%20AS2005v2.htm</a></p> <p>This is on SQL server 2005 Enterprise edition.</p>
<p>Ok, this works:</p> <pre><code>WITH MEMBER [Time].[Month].a AGGREGATE ({[Time].[Month].[Month].&amp;[2008-03-01T00:00:00], [Time].[Month].[Month].&amp;[2008-04-01T00:00:00]}) SELECT {[Measures].[CalculatedFunction]} on columns FROM TDC where a </code></pre>
<p>The problem is in your calculated measure. You are using .CurrentMember and ClosingPeriod without a specific member reference which implies a call to .CurrentMember. When you have set in the WHERE clause there is no "Current" member - there are multiple current members. Re-writting your MDX to something like the following should allow it to work with multiple members in the WHERE clause.</p> <pre><code>CREATE MEMBER CURRENTCUBE.[MEASURES].Ultimo AS NULL; SCOPE ([MEASURES].Ultimo); SCOPE ([Time].[Year - Month - Date].[All]); this = IIF ( (NOT [Measures].[LagerStk] = 0) ,Sum ( NULL:Tail(Existing [Time].[Year - Week - Date].[Date],1).item(0).item(0) ,[Measures].[LagerStk] ) ,NULL ); END SCOPE; SCOPE ([Time].[Year - Week - Date].[All]); this = IIF ( (NOT [Measures].[LagerStk] = 0) ,Sum ( NULL:Tail(Existing [Time].[Year - Month - Date].[Date],1).Item(0).Item(0) ,[Measures].[LagerStk] ) ,NULL ) ); END SCOPE; END SCOPE; </code></pre> <p>I am using SCOPE on the All members of the two dimensions, this should be fast that the out IIF and will also avoid one reference to .CurrentMember. I then replaced the <strong>ClosingPeriod()</strong> call with <strong>Tail(Existing [Time].[Year - Week - Date].[Date],1).item(0).item(0)</strong> what this does is to get the set of date members that exist in the current context, the Tail() call then gets the last on of these as a single member set and the .Item(0).Item(0) calls get the first member from the first tuple of that set.</p> <p>Obviously, not having access to your cube, I can't test any of this. The issue you reported in your comment could relate to either an incorrect reference to the All members (I may have a different naming format to the one in your cube) or it may be related to the IIF() statement. I'm not sure that the check for 0 is being evaluated in the correct context</p> <p>You could try testing without the IIF()</p> <p>CREATE MEMBER CURRENTCUBE.[MEASURES].Ultimo AS NULL;</p> <p>SCOPE ([MEASURES].Ultimo); SCOPE ([Time].[Year - Month - Date].[All]); this = Sum ( NULL:Tail(Existing [Time].[Year - Week - Date].[Date],1).item(0).item(0) ,[Measures].[LagerStk] ); END SCOPE;</p> <pre><code> SCOPE ([Time].[Year - Week - Date].[All]); this = Sum ( NULL:Tail(Existing [Time].[Year - Month - Date].[Date],1).Item(0).Item(0) ,[Measures].[LagerStk] ); END SCOPE; </code></pre> <p>END SCOPE;</p>
48,216
<p>I have a clock feature in a VB.NET program that displays the time including the seconds. I currently have a timer constantly polling using NOW. I have to poll the system clock quite often because I need to have the second update in sync with the system clock.</p> <p>Is there a more direct to access the time only when the seconds change?</p> <p>Is there a more efficient way to write this code?</p> <p>If you need more info let me know.</p>
<p>Why not use the timer component? This assumes that you are using a GUI and not building a service.</p> <p>You could call a synchronization routine that performed the polling to get the timer very close to the seconds changing, then delegate to the timer. You could call the sync routine once a minute or so to make sure that you aren't getting any OS drift.</p> <p>That being said, I'm sure there is a way to detect the seconds changing event, I just don't know how to do it.</p> <p>Update:</p> <p><a href="http://en.csharp-online.net/Delegates_and_Events%E2%80%94Events_and_Delegates" rel="noreferrer">This link</a> has an implementation similar to what I was envisioning. Just modify it so that you are not permanently stuck in a loop and voila! You have your sync routine.</p> <p>Update 2:</p> <p>Based on feedback from Shog9, I think this might be a better approach than polling:</p> <pre><code>Public Class Form1 Private WithEvents clockTimer As New Timer Private currentTime As DateTime = DateTime.MinValue Private Sub ClockTick(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles clockTimer.Tick UpdateTimer() DisplayTimer() End Sub Private Sub UpdateTimer() currentTime = DateTime.Now clockTimer.Stop() clockTimer.Interval = 1000 - currentTime.Millisecond clockTimer.Start() End Sub Private Sub DisplayTimer() lblTime.Text = currentTime.ToString("T") End Sub Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load UpdateTimer() DisplayTimer() End Sub End Class </code></pre> <p>Now, based on my preliminary tests, there is some sort of drift with each Tick event. On my machine, it varied between 12 and 20 milliseconds. If anyone has an idea on how to reliably correct the drift, I would be interested in learning.</p>
<p>Use a Timer object, set it's "interval" to 0, set it's "enabled" to true. That will fire roughly every 15 milliseconds (based on your hardware configuration). In that method, set MyLabel.Text = DateTime.Now.ToString() (or whatever you're doing).</p> <p>That is perfectly performant.</p>
33,884
<p>Im using APACHE as my web server and using port 8080. Ive create a site called (e.g. <a href="http://test.domain.com:8080" rel="nofollow noreferrer">http://test.domain.com:8080</a>). I have a Firewall (ISA Server 2006).</p> <p>How am I suppose to establish "<a href="http://test.domain.com:8080" rel="nofollow noreferrer">http://test.domain.com:8080</a>"in ISA Server? Will I just add "<a href="http://test.domain.com" rel="nofollow noreferrer">http://test.domain.com</a>" as its public name or with this "<a href="http://test.domain.com:8080" rel="nofollow noreferrer">http://test.domain.com:8080</a>"?</p> <p>any suggestion will be appreciated. Thanks. :D</p>
<p>Create a rule and related listner rule to listen on port 80 for the domain test.domain.com Then on the bridging tab of the rule, redirect to port 8080.<br> (That's if you want users to use port 80 rather then 8080).</p> <p>It's public name would be test.domain.com </p>
<p>Thanks a lot Bravax!</p> <p>Here's the step Ive done so far... first Ive created a web publishing rule, its public name was (e.g. test.domain.com) then after establishing new web rule I went to its properties and go to the bridging tab... I change the "Redirect request to http port" from 80 to 8080.</p> <p>Then I created an "Access Rule", opening the "Http8080" protocol.</p> <p>Did I made the correct setuo? </p>
20,911
<p>I am trying to access a Windows Media Player library from ASP.NET.</p> <p>The following code:</p> <p>WMPLib.WindowsMediaPlayer mplayer = new WMPLib.WindowsMediaPlayer();</p> <p>WMPLib.IWMPStringCollection list = mplayer.mediaCollection.getAttributeStringCollection("artist", "audio");</p> <p>Returns an non-empty list when run using the VS2005 development web server but an empty list when using IIS.</p> <p>Setting impersonation with:</p> <p>System.Security.Principal.WindowsImpersonationContext impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();</p> <p>Doesn't help. It seems that WMPLib still doesn't thinks its running as a user who has a library. </p> <p>Is there a way to get around this?</p>
<p>Have you tried configuration via web.config in ASP.NET? When you're running in the VS2005 debugger, you're (probably) running code as yourself, but when under IIS you'll be running it as IUSR_<em>machinename</em> or another low-permission system account.</p> <p>Try adding something like this to your web.config file:</p> <pre><code>&lt;system.web&gt; &lt;identity impersonate="true" userName="MYDOMAIN\myuser" password="p@ssw0rd" /&gt; &lt;/system.web&gt; </code></pre> <p>No idea whether this works with Media Player specifically, but it works for other identity/security related problems like this. </p>
<p>I've run into a similar problem: the code works fine on my local machine, but once deployed on my home server, it can not pull anything out of the media library (I can open media player to verify there are songs in the library)</p> <p>At first I thought it was a process issue as well, so I tried both setting the application pool to run under my own account, and to set it via the identity impersonate tags; neither resolved the issue.</p> <p>I'm not sure of what other differences would cause the issue</p>
16,731
<p>I'm coding the shutdown of a multithreaded server.If everything goes as it should all the threads exit by their own, but there's a small chance that a thread gets stuck.In this case it would be convenient to have a non-blocking join so I could do.</p> <p><strong>Is there a way of doing a non-blocking pthread_join? Some sort of timed join would be good too.</strong></p> <p>something like this:</p> <pre> foreach thread do nb_pthread_join(); if still running pthread_cancel(); </pre> <p>I can think more cases where a a non-bloking join would be useful.</p> <p>As it seems there is no such a function so I have already coded a workaround, but it's not as simple as I would like.</p>
<p>If you are running your application on Linux, you may be interested to know that:</p> <pre><code>int pthread_tryjoin_np(pthread_t thread, void **retval); int pthread_timedjoin_np(pthread_t thread, void **retval, const struct timespec *abstime); </code></pre> <p>Be careful, as the suffix suggests it, "np" means "non-portable". They are not POSIX standard, gnu extensions, useful though.</p> <p><a href="http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_tryjoin_np.3.html" rel="noreferrer">link to man page</a></p>
<p>You could push a byte into a pipe opened as non-blocking to signal to the other thread when its done, then use a non-blocking read to check the status of the pipe.</p>
9,912