instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>We have a java program that requires a large amount of heap space - we start it with (among other command line arguments) the argument -Xmx1500m, which specifies a maximum heap space of 1500 MB. When starting this program on a Windows XP box that has been freshly rebooted, it will start and run without issues. But if the program has run several times, the computer has been up for a while, etc., when it tries to start I get this error:</p> <pre> Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine. </pre> <p>I suspect that Windows itself is suffering from memory fragmentation, but I don't know how to confirm this suspicion. At the time that this happens, Task manager and sysinternals procexp report 2000MB free memory. I have looked at <a href="https://stackoverflow.com/questions/60871/how-to-solve-memory-fragmentation">this question related to internal fragmentation</a></p> <p>So the first question is, How do I confirm my suspicion? The second question is, if my suspicions are correct, does anyone know of any tools to solve this problem? I've looked around quite a bit, but I haven't found anything that helps, other than periodic reboots of the machine. </p> <p>ps - changing operating systems is also not currently a viable option. </p>
<p>Agree with Torlack, a lot of this is because other DLLs are getting loaded and go into certain spots, breaking up the amount of memory you can get for the VM in one big chunk.</p> <p>You can do some work on WinXP if you have more than 3G of memory to get some of the windows stuff moved around, look up PAE here: <a href="http://www.microsoft.com/whdc/system/platform/server/PAE/PAEdrv.mspx" rel="nofollow noreferrer">http://www.microsoft.com/whdc/system/platform/server/PAE/PAEdrv.mspx</a></p> <p>Your best bet, if you really need more than 1.2G of memory for your java app, is to look at 64 bit windows or linux or OSX. If you're using any kind of native libraries with your app you'll have to recompile them for 64 bit, but its going to be a lot easier than trying to rebase dlls and stuff to maximize the memory you can get on 32 bit windows.</p> <p>Another option would be to split your program up into multiple VMs and have them communicate with eachother via RMI or messaging or something. That way each VM can have some subset of the memory you need. Without knowing what your app does, i'm not sure that this will help in any way, though...</p>
<p>Using Minimem (<a href="http://minimem.kerkia.net/" rel="nofollow noreferrer">http://minimem.kerkia.net/</a>) for that application might fix your problem. However, I'm not sure this is the answer you are looking for. I hope it helps.</p>
12,928
<p>I need some resources that talk about how to design your software to be extensible, i.e. so that other people can write add-ons/plug-ins that adds functionality to it.</p> <p>What do you recommend? Any books out there that discuss the subject?<br> I would prefer something that's short and to the point; a bit of theory and a bunch of concrete examples.</p> <p>I'm not targeting a specific language, I want to be able to understand the core idea so that I can implement it in any language. </p> <p>And for the same reason, I prefer not to do it using a framework that someone else built (unless the framework is not very high-level, i.e. doesn't hide <em>too</em> much), at the moment I only want to educate myself on the subject and experiment with various ways to implement it. Plus, a framework usually assumes user's knowledge about the subject.</p> <p><strong>UPDATE</strong></p> <p>I'm not asking about OOP or allowing my classes to be inherited. I'm talking about designing an application that will be deployed on a system, such that it can be extended by third-party add-ons AFTER its been deployed.</p> <p>For example, Notepad++ has a plug-in architecture where you can place a .dll file in the plugins folder, and it adds functionality to the application that wasn't there, such as color-picking, or snippet insertion, or many other things (a wide range of functionality).</p>
<p>IF we're talking .NET, try <a href="http://www.codeproject.com/KB/system/mScriptable.aspx" rel="noreferrer">Scripting .NET applications with VBScript</a> over on CodeProject. Lots of concrete examples there.</p> <p>Below are sites implementing various application extension techniques</p> <ul> <li><a href="http://clearscript.codeplex.com" rel="noreferrer">ClearScript - Makes V8, VBScript and JScript available to .NET apps</a></li> <li><a href="http://www.csscript.net/" rel="noreferrer">CS-Script - The C# Script Engine</a></li> <li><a href="http://www.codeproject.com/KB/cs/c__plugin_architecture.aspx" rel="noreferrer">Plugin Architecture using C#</a></li> <li><a href="http://objectplanet.com/opinio/userguide/index.htm?page=plugin_architecture.html" rel="noreferrer">Opinio plugin architecture</a></li> <li><a href="http://www.eclipse.org/articles/Article-Plug-in-architecture/plugin_architecture.html" rel="noreferrer">Notes on the Eclipse Plug-in Architecture</a></li> <li><a href="http://www.codeguru.com/cpp/misc/misc/plug-insadd-ins/article.php/c3879" rel="noreferrer">Plug-in Architecture Framework for Beginners </a></li> <li><a href="https://developer.mozilla.org/en/Plugin_Architecture" rel="noreferrer">Gecko plugin architecture</a></li> <li><a href="http://www.fungible.com/fungimol/plugin.html" rel="noreferrer">Fungimol plugin architecture</a></li> </ul>
<p>Rather than re-inventing the wheel, use the frameworks in hand. Eclipse and Netbeans both support plugin based extensions. You have to work in Java though.</p>
41,829
<p>On all my Windows servers, except for one machine, when I execute the following code to allocate a temporary files folder:</p> <pre><code>use CGI; my $tmpfile = new CGITempFile(1); print "tmpfile='", $tmpfile-&gt;as_string(), "'\n"; </code></pre> <p>The variable <code>$tmpfile</code> is assigned the value <code>'.\CGItemp1'</code> and this is what I want. But on one of my servers it's incorrectly set to <code>C:\temp\CGItemp1</code>.</p> <p>All the servers are running Windows 2003 Standard Edition, IIS6 and ActivePerl 5.8.8.822 (upgrading to later version of Perl not an option). The result is always the same when running a script from the command line or in IIS as a CGI script (where scriptmap <code>.pl</code> = <code>c:\perl\bin\perl.exe "%s" %s</code>).</p> <p>How I can fix this Perl installation and force it to return '<code>.\CGItemp1</code>' by default?</p> <p>I've even copied the whole Perl folder from one of the working servers to this machine but no joy.</p> <p><a href="https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86200#86200">@Hometoast:</a></p> <p>I checked the '<code>TMP</code>' and '<code>TEMP</code>' environment variables and also <code>$ENV{TMP}</code> and <code>$ENV{TEMP}</code> and they're identical. </p> <p>From command line they point to the user profile directory, for example: </p> <blockquote> <p><code>C:\DOCUME~1\[USERNAME]\LOCALS~1\Temp\1</code></p> </blockquote> <p>When run under IIS as a CGI script they both point to:</p> <blockquote> <p><code>c:\windows\temp</code></p> </blockquote> <p>In registry key <code>HKEY_USERS/.DEFAULT/Environment</code>, both servers have:</p> <blockquote> <p><code>%USERPROFILE%\Local Settings\Temp</code></p> </blockquote> <p>The ActiveState implementation of <code>CGITempFile()</code> is clearly using an alternative mechanism to determine how it should generate the temporary folder.</p> <p><a href="https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86993#86993">@Ranguard:</a></p> <p>The real problem is with the <code>CGI.pm</code> module and attachment handling. Whenever a file is uploaded to the site <code>CGI.pm</code> needs to store it somewhere temporary. To do this <code>CGITempFile()</code> is called within <code>CGI.pm</code> to allocate a temporary folder. So unfortunately I can't use <code>File::Temp</code>. Thanks anyway.</p> <p><a href="https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86874#86874">@Chris:</a></p> <p>That helped a bunch. I did have a quick scan through the <code>CGI.pm</code> source earlier but your suggestion made me go back and look at it more studiously to understand the underlying algorithm. I got things working, but the oddest thing is that there was originally no <code>c:\temp</code> folder on the server. </p> <p>To obtain a temporary fix I created a <code>c:\temp</code> folder and set the relevant permissions for the website's anonymous user account. But because this is a shared box I couldn't leave things that way, even though the temp files were being deleted. To cut a long story short, I renamed the <code>c:\temp</code> folder to something different and magically the correct '<code>.\</code>' folder path was being returned. I also noticed that the customer had enabled FrontPage extensions on the site, which removes write access for the anonymous user account on the website folders, so this permission needed re-applying. I'm still at a loss as to why at the start of this issue <code>CGITempFile()</code> was returning <code>c:\temp</code>, even though that folder didn't exist, and why it magically started working again.</p>
<p>The name of the temporary directory is held in <code>$CGITempFile::TMPDIRECTORY</code> and initialised in the <code>find_tempdir</code> function in CGI.pm. The algorithm for choosing the temporary directory is described in the CGI.pm documentation (search for <strong>-private_tempfiles</strong>). IIUC, if a C:\Temp folder exists on the server, CGI.pm will use it. If none of the directories checked in <code>find_tempdir</code> exist, then the current directory "." is used.</p> <p>I hope this helps.</p>
<p>If you're running this script as you, check the %TEMP% environment variable to see if if it differs.</p> <p>If IIS is executing, check the values in registry for TMP and TEMP under HKEY_USERS/.DEFAULT/Environment</p>
11,169
<p>In MS SQL 2000 and 2005, given a datetime such as '2008-09-25 12:34:56' what is the most efficient way to get a datetime containing only '2008-09-25'?</p> <p>Duplicated <a href="https://stackoverflow.com/questions/2775/whats-the-best-way-to-remove-the-time-portion-of-a-datetime-value-sql-server">here</a>.</p>
<p>I must admit I hadn't seen the floor-float conversion shown by Matt before. I had to test this out. </p> <p>I tested a pure select (which will return Date and Time, and is not what we want), the reigning solution here (floor-float), a common 'naive' one mentioned here (stringconvert) and the one mentioned here that I was using (as I thought it was the fastest).</p> <p>I tested the queries on a test-server MS SQL Server 2005 running on a Win 2003 SP2 Server with a Xeon 3GHz CPU running on max memory (32 bit, so that's about 3.5 Gb). It's night where I am so the machine is idling along at almost no load. I've got it all to myself.</p> <p>Here's the log from my test-run selecting from a large table containing timestamps varying down to the millisecond level. This particular dataset includes dates ranging over 2.5 years. The table itself has over 130 million rows, so that's why I restrict to the top million.</p> <pre><code>SELECT TOP 1000000 CRETS FROM tblMeasureLogv2 SELECT TOP 1000000 CAST(FLOOR(CAST(CRETS AS FLOAT)) AS DATETIME) FROM tblMeasureLogv2 SELECT TOP 1000000 CONVERT(DATETIME, CONVERT(VARCHAR(10), CRETS, 120) , 120) FROM tblMeasureLogv2 SELECT TOP 1000000 DATEADD(DAY, DATEDIFF(DAY, 0, CRETS), 0) FROM tblMeasureLogv2 </code></pre> <blockquote> <p>SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 1 ms.</p> <p>(1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.</p> <p>SQL Server Execution Times: CPU time = 422 ms, elapsed time = 33803 ms.</p> <p>(1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.</p> <p>SQL Server Execution Times: CPU time = 625 ms, elapsed time = 33545 ms.</p> <p>(1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.</p> <p>SQL Server Execution Times: CPU time = 1953 ms, elapsed time = 33843 ms.</p> <p>(1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.</p> <p>SQL Server Execution Times: CPU time = 531 ms, elapsed time = 33440 ms. SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 1 ms.</p> <p>SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms.</p> </blockquote> <p>What are we seeing here?</p> <p>Let's focus on the CPU time (we're looking at conversion), and we can see that we have the following numbers:</p> <pre><code>Pure-Select: 422 Floor-cast: 625 String-conv: 1953 DateAdd: 531 </code></pre> <p>From this it looks to me like the DateAdd (at least in this particular case) is slightly faster than the floor-cast method.</p> <p>Before you go there, I ran this test several times, with the order of the queries changed, same-ish results.</p> <p>Is this something strange on my server, or what?</p>
<pre><code>CONVERT(VARCHAR(10), GETDATE(), 120) AS [YYYY-MM-DD] </code></pre>
16,111
<p>How do I stop a function/procedure in a superclass from been overridden in a subclass in Delphi (2007)?</p> <p>I want to mark it so it can not be altered, I believe there is a final keyword but can not for the life of me find the documentation for it, so I am not 100% sure that's what I need.</p>
<p>The keyword is <code>final</code> as you thought. See <a href="http://dn.codegear.com/article/34324" rel="noreferrer">http://dn.codegear.com/article/34324</a> and <a href="http://blogs.teamb.com/rudyvelthuis/2005/05/13/4311" rel="noreferrer">http://blogs.teamb.com/rudyvelthuis/2005/05/13/4311</a>. Also you can mark your class as sealed to prevent anyone from inheriting from it. You need a Delphi version higher than 7.</p> <pre><code>type TSomeClass = class protected procedure SomeVirtualMethod; virtual; end; TOtherClass = class(TSomeClass) protected procedure SomeVirtualMethod; override; final; end; </code></pre>
<p>You're right - it's "final". This snippet shows it. (from one of <a href="http://www.marcocantu.com" rel="nofollow noreferrer">Marco Cantu</a>'s books)</p> <pre><code>type TDeriv1 = class (TBase) procedure A; override; final; end; TDeriv2 = class (TDeriv1) procedure A; override; // error: "cannot override a final method" end; </code></pre> <p>Compiling gives:</p> <pre><code>[Pascal Error] Unit1.pas(11): E2352 Cannot override a final method </code></pre> <p>One thing that surprised me: This feature is supported in Win32 Delphi, not just Delphi for .NET</p>
20,199
<p>I am developing a page view counter to track the amount of views a page is having on our site and displaying it to the user. (I asked an intro question before: <a href="https://stackoverflow.com/questions/246919/page-view-counter-like-on-stackoverflow">Page View Counter like on StackOverFlow</a>).</p> <p>Using the recommendations, I developed a httpHandler which will handle the request whenever this gets fired off: </p> <pre><code>&lt;link rel="stylesheet" href="cn.axd?t=1&amp;id=232" type="text/css" /&gt; </code></pre> <ol> <li><p>Just wondering if the end-user would need to wait for the request to be finish processing before they can view/interact with the page.</p></li> <li><p>Would a better choice be implementing an asynchronous queue where information gets logged to an MS Queue and eventually logged in the database via (Exception Policy)</p></li> <li><p>Would it be slower to check if a certain record exist (PageID) and increment a counter or insert the record into the database and aggregate later when needed. We would just need to run an aggregation at the end of the week to see the total amount of pageviews a particular page got over the week.</p></li> </ol> <p>Thanks all.</p>
<p>interesting questions! Like a lot of other performance-tuning questions, there are some tradeoffs.</p> <ol> <li><p>Possibly. It may be a better idea to load this handler inside an IMG href="", setting the sizes to 0 so it is invisible to the user.</p></li> <li><p>With heavy load this would be preferable, that way your handler can return immediately after queuing the operation. For most loads, however, it is probably just as quick to run a simple T-SQL query to increment a counter.</p></li> <li><p>Adding +1 to the value directly within your T-SQL query would probably be the best, "count = count + 1" etc. That would be quick to run and would result in subsequent retrieval of your data without aggregation.</p></li> </ol> <p>Hope this helps!</p> <p>Adam</p>
<p>I would go with the logging method referenced in the other page, unless you need to track specific time/date of views. My reasoning is simply due to the sheer number of items that you might get as you application starts to scale up in size.</p> <p>Linking to the handler as a CSS style, should not really stop load time very much, but it could have some effect.</p> <p>With a simple insert/update script, I can't imagine that the performance overhead of doing the statement would be worth trying to do a queue style system...</p>
32,439
<p>I have a job to enter survey results (in paper form) to excel. I've never written any macro in Office :(</p> <p>Here I what I basically need:</p> <ol> <li>I have predefined columns (|A|B|...|AG|AH|)</li> <li>All surveys are grouped into groups. All surveys from same group have few (like predefined) same columns. It's always same columns that 'define' group</li> <li>All other survey answers are in numerical type [1..10].</li> <li>Columns are not in same order as answers in servey</li> <li>I want macro that will take my input (for example '1575'), and first place predefined values to that 'group' to |A| |B| |C|, and then |E| = 1, |D| = 5, |F| = 7, |G| = 5, and automatically start entering next row.</li> </ol> <p>Anything that will give me a clue how to write this macro in more than welcome</p> <p>Huge thanks for reading this... </p> <p>EDIT1: I suppose question is not clear enough... I need macro that will read my keyboard input ( '1575' ) and write integers '1' '5' '7' and '5' to predefined rows. For now, I have an idea to make a form, but I need event handler that will change focus to next input when I press a key, as I want to avoid pressing TAB all the time...</p>
<p>It seems to me you need a small userform with just a textbox, a range to show the order of data entry, say:</p> <p>Group A | E | D | F | G</p> <p>And a little code to go with the form, say:</p> <pre><code>Dim LastCol As Integer Dim CurRow As Integer Private Sub UpdateCells() Dim Col As Variant Dim ColumnOrder As Range 'Range that specifies data entry order' Set ColumnOrder = Range("A3:A15") LastCol = LastCol + 1 If LastCol &gt; WorksheetFunction.CountA(ColumnOrder) Then LastCol = 1 CurRow = CurRow + 1 End If Col = Range("A3").Offset(0, LastCol) Range(Col &amp; CurRow) = TextBox1.Value TextBox1 = "" End Sub Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) If KeyCode = 13 Then UpdateCells End If End Sub Private Sub UserForm_Initialize() CurRow = ActiveCell.Row End Sub </code></pre> <p>Edit Re Comment</p> <p>In Excel, the last row can be a bit tricky in that Excel does not update the range after deletions until the workbook is saved. One one these may suit:</p> <pre><code>Function FindLastRow() 'Assuming that data starts in A1' r = ActiveSheet.UsedRange.Rows.Count c = ActiveSheet.UsedRange.Columns.Count FindLastRow = r End Function </code></pre> <p>.</p> <pre><code>Sub LastRow() LastRowA = ExecuteExcel4Macro("GET.DOCUMENT(10)") LastRowB = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row End Sub </code></pre> <p>Further information: <a href="http://www.tek-tips.com/faqs.cfm?fid=2115" rel="nofollow noreferrer">http://www.tek-tips.com/faqs.cfm?fid=2115</a></p>
<p>If I understand the question correctly, you want the user to be able to type numbers only, without using enter or arrow to finalize the entry.</p> <p>For example, typing "1253216..." instead of "1 2 5 ..."</p> <p>If so, unfortunately there is no event that corresponds to individual characters going into the formula bar. The only events that are remotely related are Selection Change and Change. However, I don't think there is any way to use these for this purpose (they are not triggered during formula bar typing).</p> <p>One idea: Make and entry column with text format and instruct the users to type the answers in one big string (like "1253216" etc.), then put formulas in each of the other cells that parses out the nth character from the input column and changes it to a value. For example:</p> <p>Apply range name "Inputs" to column A, range name "N" to row 1, then in any of the other cells, put this formula:</p> <pre><code>=VALUE(MID(Inputs,N,1)) </code></pre> <p>The drawback is, the user won't know if they made some error until after they finish typing the whole string of numbers and press enter or arrow.</p>
48,434
<p>As one of my hobby projects, I'm developing an image effects plugin for jQuery. It's supposed to allow you to apply a few basic effects to an image, and does this by using the canvas HTML element or Internet Explorer filters, which ever are supported.</p> <p>A demo page is available at: <a href="http://sandbox.odyniec.net/imgfx-new/" rel="nofollow noreferrer">http://sandbox.odyniec.net/imgfx-new/</a>.</p> <p>I'm having a problem with the rotation effect, which is implemented with the matrix transformation filter (DXImageTransform.Microsoft.Matrix). </p> <p>If I just rotate the image, the resulting image appears fine. But, if I use another effect on the image before rotating, the rotated image gets broken, ie. a part of it turns black or white. You can see that on the demo page.</p> <p>For example, use the <code>Invert</code> button, then <code>Rotate</code> by 20 degrees, you'll notice a black stripe where the blue tree should be. The actual filters that are applied to the image are displayed at the bottom of the page.</p> <p>Am I missing something here, or could this be a browser bug?</p>
<p>You can try to set the css zoom value to 1. If that also doesn't work. It seems that this is really a bug in IE.</p>
<p>Looks like a Browser bug to me.</p>
45,211
<p>I use db2 v.9.1 on windows 2003 server so it can not use LPAD or RPAD functions scalar. because that functions support only z/OS right?</p> <p>Now, I use this way for pad zero when COLUMN1 type is VARCHAR</p> <pre><code> RIGHT('0000' || COLUMN1 ,4) AS RPAD LEFT('0000' || COLUMN1 ,4) AS LPAD </code></pre> <p>Have better way for replace LPAD or RPAD function?</p>
<p>I think you probably want the <a href="http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0000842.htm" rel="nofollow noreferrer">REPEAT</a> scalar function.</p>
<pre><code>REPEAT('0',4) || column_name </code></pre> <p>Now if you want to limit the 0 based on the number of characters you can use the <code>RIGHT</code> function and it would look something like this assuming your column is <code>varchar(10)</code>:</p> <p><code>RIGHT(REPEAT('0',4) || column_name, 10)</code> in this case if you have characters it will fill it with 4 preceding 0s but if you have 7 characters it would fill it with 3 0s.</p> <p>So you would have:<br> 00001,<br> 000012,<br> 0000123,<br> 00001234,<br> 000012345,<br> 0000123456,<br> 0001234567,<br> 0012345678,<br> etc.</p>
36,407
<p>I have a website built using Asp.net and LinqToSql for Data Access. In a certain section of the site, LinqToSql produces a query that looks like this (from my dev machine):</p> <pre><code>select ... from table1 left outer join table2 on table1 where ... left outer join table3 on table2 where ... </code></pre> <p>Since the connection between table2 and table1 is not always there, the left outer join is appropriate in this situation. And since the link between table3 and table1 goes through table2, it also needs a left outer join. This sql returns the correct recordset.</p> <p>I just put the code up to a server. Running the identical code in the same scenario, LinqToSql produces the following query:</p> <pre><code>select ... from table1 left outer join table2 on table1 where ... join table3 on table2 where ... </code></pre> <p>For some reason, it renders the join between table2 and table3 as an inner join, instead of an outer join. This results in zero records being returned from the query.</p> <p>Both dev machine and server are using .Net 3.5 SP1. Dev machine is Vista64, Server is Windows Server 2003 SP2. A colleague of mine using Windows XP PRO also confirmed the same correct behavior on their dev machine. </p> <p>Can anyone think of a reason why the server would create different sql? How can I fix this? It seems to be something tied into the way that Linq and .Net is running on the server. However, I can't think of any way to confirm and fix this.</p> <hr> <p>Linq Code (I am only including the parts that are relevant to the section where the sql changed):</p> <pre><code>from Import_Table t in db.Import_Tables select new { CheckedOutUser = (!t.IsCheckedOut) ? "--" : t.Import_CheckoutHistory.System_User.FirstName + " " + t.Import_CheckoutHistory.System_User.LastName, CheckedOutUserID = (!t.IsCheckedOut) ? 0 : t.Import_CheckoutHistory.System_UserID}; </code></pre> <p>In the context of the description above, table1 = Import_Table, table2 = Import_CheckoutHistory, table3 = System_User. If I comment out the line here that begins with "CheckedOutUser = ..." then it works on the server - so this is definitely the culprit.</p> <p>Actual sql returned:</p> <pre><code>SELECT (CASE WHEN NOT ([t0].[IsCheckedOut] = 1) THEN CONVERT(NVarChar(401),'--') ELSE ([t2].[FirstName] + ' ') + [t2].[LastName] END) AS [CheckedOutUser], (CASE WHEN NOT ([t0].[IsCheckedOut] = 1) THEN 0 ELSE [t1].[system_UserID] END) AS [CheckedOutUserID] FROM [dbo].[import_Table] AS [t0] LEFT OUTER JOIN [dbo].[import_CheckoutHistory] AS [t1] ON [t1].[import_CheckoutHistoryID] = [t0].[import_CheckoutHistoryID] LEFT OUTER/INNER JOIN [dbo].[system_User] AS [t2] ON [t2].[system_UserID] = [t1].[system_UserID] </code></pre> <p>On the dev machines, the last line begins with "Left outer". On the server, the last line begins with "Inner"</p> <p><strong>Update:</strong> My solution is <a href="https://stackoverflow.com/questions/269594/linqtosql-producing-different-sql-queries-on-different-machines-for-identical-c#275751">below</a></p>
<p>Is your production database different to your development one, e.g. SQL Server 2008 instead of 2005? I believe LINQ to SQL will vary the SQL it generates based on the actual execution-time database it's talking to.</p> <p>Also, are the schemas exactly the same on both databases?</p>
<p>I have checked the following:</p> <ol> <li>Both use the same database</li> <li>Both have the identical code</li> <li>Both have the identical dbml file</li> </ol> <p>I know that something has to be out of synch somewhere, but I can't find it.</p> <p>So I have implemented the following workaround: I added a view to my database that includes both left outer joins. This view is now in my dbml file, and in the query above, I reference the view instead of the table. This is working fine.</p>
33,869
<p>I am a 3D printing beginner but wanted to get stuck in straight away and design my own 3D objects. I used Sketchup to design a badge of one of my logos. I make sure that all faces of my object are not inside out and show a white face in Sketchup. I also make my entire object a component before exporting into a .stl file. However, when I import into Ultimaker Cura, the base of the object is red. This to my understanding means there is an issue with that face.I have played around with Sketchup several times by not creating a component, reversing the face and I still have no luck. When I reverse the base face in Sketchup so that it is grey, it then shows up in Ultimaker Cura as okay (not red). But when I 3D print it, it still prints it very strangely. I would like to note I am 3D printing with a raft and when I do not use a raft, the object prints fine. Also I have tested printing a small 3D cube with the same settings and the results are exactly the same. Surely you can design objects in Sketchup and print with a raft?</p> <p><a href="https://i.stack.imgur.com/WdSYa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WdSYa.jpg" alt="Reverse of object"></a></p> <p><a href="https://i.stack.imgur.com/t8seY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t8seY.jpg" alt="Front of object"></a></p>
<p>A red surface coloring is normal for the bottom when viewed in Ultimaker Cura, nothing to worry about that (e.i. when that face is touching the build plate; if it is unsupported, you should add support structures but a raft is generally not necessary for PLA).</p> <p>Rafts are useful when you print high temperature materials that have a large shrinkage when cooled from print to bed temperature (this somewhat mitigates the problems of curling up corners or warping prints), for PLA it is not needed. As seen from the print that is printed on the raft, it's clear that the print to raft distance is to large, the first print object layer is not adhering to the top raft layer very well.</p> <p>The print that is printed without a raft doesn't look too bad. Some printer <a href="/q/6483">extruder calibration</a> could further improve the quality.</p>
<p>Note: This answer is curently wrong because I mentally reversed your "with raft" and "without raft" columns. I'll attempt to fix it soon.</p> <p>This doesn't look like a problem with your model, but rather a problem with your bed height or slicer settings (possibly both) that may be affecting your particular model worse than others. It's clear from the photo of the bottom of your print that the extrusions that were supposed to be circular failed to adhere to the bed, and instead got pulled to chords between points they happened to adhere at. This could be caused by a mix of:</p> <ul> <li>Excessive print speed for the first layer. Generally I would limit it to 30 mm/s or less to give the material the best chance to stick.</li> <li>Excess space between the nozzle and bed. Could be caused by improper adjustment of bed height ("leveling"), or by using a layer thickness that's too high (roughly, more than 75-80% of nozzle width).</li> <li>Underextrusion, possibly caused by insufficient print temperature, incorrect filament diameter setting, or poor quality filament with wrong diameter, among other things.</li> </ul> <p>Using a raft mitigates these things by moving the potential problem to the interface between the raft and the bed; once there's a raft sticking to the bed, printing of the model can ignore the problem. But you <em>should never need a raft</em>. It's a waste of plastic and a workaround for problems that have better fixes, not a necessary part of 3D printing.</p> <p>The "red" in Cura is not a problem; as I understand it, Cura shows all parts of the model that aren't supported <em>by other parts of the model</em> in red, and this includes the base. However, it is possible that your model has some stray part extruding below the bottom, causing the whole thing (except that stray part) to be printed starting one layer above the print bed with nothing to adhere to. You can check if this is the case in Cura by switching to layer view and looking at the first layer. You should see the whole surface that you want to adhere to the bed; if instead you see just one or a few small blobs, that's your problem.</p>
1,391
<p>I'm currently writing an interface to allow applications to send exception data to a central repository for support purposes. I'm at a quandary about how to pass extra contextual data:</p> <pre><code>public interface IExceptionNotifier { void Notify(Exception ex, NameValueCollection context); //this void Notify(Exception ex, IDictionary&lt;string, string&gt; context); //or this } </code></pre> <p>I've often found myself is a similar position when creating lookups. Ignoring whether or not the exception notifier concept is good, is it be best to use an <code>IDictionary&lt;string, string&gt;</code> or <code>NameValueCollection</code>? Why would you pick one over the other?</p>
<p>(Assuming .NET 3.5 here. Pre .NET 3.5, NameValueCollection would have the benefit of being able to tie multiple values to a key, with no direct equivalent in "normal" collections.)</p> <p>Do you want keys to have potentially multiple values? If so, I'd consider ILookup&lt;TKey, TValue>. Otherwise, I'd go for IDictionary&lt;TKey, TValue>.</p> <p>Aside from anything else, if the receiver wants to do any processing where LINQ would be of use to them, either of the generic interfaces is going to be nicer than NameValuePair. Likewise, it may be easier for the caller to produce a dictionary/lookup using LINQ if they've already got a generic or dynamic kind of context.</p>
<p>If the context is a throw-away value and (here comes the important part) will not be serialized, e.g. for sending the data to another system, I'd go with the IDictionary because it makes using your interface more flexible.</p> <p>If, on the other hand, the context is kept all the time or the context will be serialized, use NameValueCollection because then you are under control of what you'll actually get from your caller.</p> <p>Edit: mausch is right in that you should use a generic approach, but I still wouldn't use an interface if you want to serialize the data.</p>
17,428
<p>I want to put Apache 2.2.9 in front of a Weblogic 9.2 server on Windows XP. What does it take to do that ?<br></p> <p>I probably need mod_proxy on the apache side ? <br></p> <p>As far as Weblogic and apache are concerned, is there something similar to mod_jk ?<br></p> <p>I would like this setup so that I can introduce some filtering later on. But for now, the goal is to allow other computers to access weblogic appserver so that Apache forwards all requests coming to it (at a certain URL) to Weblogic.</p> <p>I have done this several times earlier BUT have forgotten how I did it.</p> <p>Thanks for any pointers,</p> <hr> <p>I guess <a href="http://e-docs.bea.com/wls/docs81/plugins/apache.html" rel="nofollow noreferrer">http://e-docs.bea.com/wls/docs81/plugins/apache.html</a> answers most of the basic fundas. Will update the forum if I have more inputs.</p>
<p>The right way to do this is to use the <em>Apache HTTP Server plug-in</em> provided by BEA/Oracle and bundled with Weblogic. </p> <p>For details, refer to the legacy <a href="http://download.oracle.com/docs/cd/E13222_01/wls/docs92/index.html" rel="nofollow noreferrer">BEA WebLogic Server 9.2 Documentation</a> and more precisely to:</p> <ul> <li><a href="http://download.oracle.com/docs/cd/E13222_01/wls/docs92/plugins/apache.html" rel="nofollow noreferrer">Installing and Configuring the Apache HTTP Server Plug-In</a></li> <li><a href="http://download.oracle.com/docs/cd/E13222_01/wls/docs92/plugins/plugin_params.html" rel="nofollow noreferrer">Parameters for Web Server Plug-Ins </a></li> </ul> <p><strong>Note</strong>: These links are the up to date links since <a href="http://edocs.bea.com/" rel="nofollow noreferrer">http://edocs.bea.com/</a> is now down. </p>
<p>We used the WebLogic plugin to load balance and front our applicatiosn, using virtual hosts and locations.</p> <p>For example:</p> <p> ServerName www.domain.com</p> <p> WebLogicCluster 10.20.30.41:7002,10.20.30.42:7002 SetHandler weblogic-handler </p> <p></p> <p>This config will balance requests to <a href="http://www.domain.com/PathToApplication" rel="nofollow noreferrer">http://www.domain.com/PathToApplication</a> to 10.20.30.41:7002 and 10.20.30.42:7002.</p>
23,052
<p>Do you know a good and free Hashtable imlementation for Delphi 5 ?</p> <p>I need to organize a huge amount of data in a hastable and I am bit worried about memory leak issues that I found in most available implementations on the web.</p> <p>Tks</p>
<p>You can also check out the open-source / formerly commercial <a href="http://sourceforge.net/projects/tpsystools/" rel="noreferrer">TurboPower SysTools</a>. Not sure how much it is being updated. At one point Julian Bucknall recommended it over his <a href="http://www.boyet.com/FixedArticles/EZDSL.html" rel="noreferrer">EZDSL library</a>, although that was back when he still worked fur TurboPower and it was being maintained / updated.</p>
<p>Peter Below just posted a rework of something he did to the Embarcadero newgroups in the public.attachments. There's something under his profile on the CodeGear site at <a href="http://cc.codegear.com/Item/24825" rel="nofollow noreferrer">http://cc.codegear.com/Item/24825</a> that describes it.</p>
21,605
<p>Here is the scenario:</p> <p>I'm writing an app that will watch for any changes in a specific directory. This directory will be flooded with thousands of files a minute each with an "almost" unique GUID. The file format is this:</p> <p>GUID.dat where GUID == xxxxxxxxxxxxxxxxxxxxxxxxxxxxx (the internal contents aren't relevant, but it's just text data)</p> <p>My app will be a form that has one single text box that shows all the files that are being added and deleted in real time. Every time a new file comes in I have to update the textbox with this file, BUT I must first make sure that this semi-unique GUID is really unique, if it is, update the textbox with this new file.</p> <p>When a file is removed from that directory, make sure it exists, then delete it, update textbox accordingly.</p> <p>The problem is that I've been using the .NET filewatcher and it seems that there is an internal buffer that gets blown up every time the (buffersize + 1)-th file comes in. I also tried to keep an internal List in my app, and just add every single file that comes in, but do the unique-GUID check later, but no dice.</p>
<p>A couple of things that I have in my head:</p> <ul> <li>If the guid is <em>not</em> unique, would it not overwrite the file with the same name, or is the check based on a lookup which does some external action (e.g. check the archive)? (i.e. is this a YAGNI moment?)</li> <li>I've used FileSystemWatcher before with pretty good success, can you give us some ideas as to <em>how</em> your actually doing things?</li> <li>When you say "no dice" when working with your custom list, what was the problem? And how were you checking for file system changes without FileSystemWatcher?!</li> </ul> <p>Sorry no answer as yet, just would like to know more about the problem :)</p>
<p>I suggest you take a look at the <a href="http://msdn.microsoft.com/en-us/library/bb762118(VS.85).aspx" rel="nofollow noreferrer">SHChangeNotify</a> API call, which can notify you of all kinds of shell events. To monitor file creation and deletion activity, you may want to pay special attention to the SHCNE_CREATE and SHCNE_DELETE arguments.</p>
4,858
<p>I have been working hard the last year on the model below. I am new to everything 3D that is modeling and especially 3D printing. I have however successfully concluded quite a good number of 3D prints which I created in blender with my Creality Ender 3 Pro so I have a bit of experience.</p> <p>All this new experience for me started with the desire to do this project I have been working on for all this year. A complex 3D model of a knight's tomb which I would like to print.</p> <p><a href="https://i.stack.imgur.com/NZ5Lx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NZ5Lx.png" alt="enter image description here"></a></p> <p>As you can see Cura is clearly indicating that there is a need for supports in these red areas. The model will be printed in a 15&nbsp;cm size. I have also managed to resize the model from a 22 million face mesh full of holes to a 900k manifold model.</p> <p>However, when I slice it I get this.</p> <p><a href="https://i.stack.imgur.com/fx5o8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fx5o8.jpg" alt="enter image description here"></a></p> <p>As you can see supports are only generated for the outer column part. None are generated for the arches which are totally absent when the model is sliced.</p> <p>I have tried to alter the model's orientation but with no result. I will try to separate this mesh in parts but it would mean restarting all from scratch since I found no good software to slice it precisely.</p> <p>I am quite sure that the main problem lies in the fact the Ender 3 pro is an FDM printer an that the vertical lines of the arches are too thin. Since I tried to upload my model on 3D printing services to see if it could be printed in other materials and could be printed in finely detailed resin. </p> <p>I would like at least to know if I am right in my problem spotting or if there could be any solution to the present problem so that not to go wrong if I will redesign this part.</p>
<p>Basically you need to write a G-code file yourself. This is a plain text file with a <code>.g</code> extension.</p> <p>You need to home the printer with <code>G28</code>, then move the Y axis all the way forward (for a Prusa style printer) with <code>G1 F1500 Y{ymax}</code> (where <code>{ymax}</code> is the length of the bed). Now raise the head with a similar command <code>G1 F500 Z{zmax}</code> (where <code>{zmax}</code> is the height of the printer volume).</p> <p>Heating the bed is done with <a href="https://reprap.org/wiki/G-code#M190:_Wait_for_bed_temperature_to_reach_target_temp" rel="nofollow noreferrer"><code>M190 S60</code></a> (set and wait to reach 60&nbsp;&deg;C).</p> <p>You can now rock the Y axis by moving it fast, e.g. with <code>G1 F5000 Y{ymax-5}</code>, <code>G1 Y{ymax-1}</code>, <code>Y{ymax-5}</code>, <code>Y{ymax-1}</code>, etc.</p>
<p>Never mind, figured the quickest dirtiest way myself - created a tall thin cylinder shape model in Blender and positioned it in Repetier so the printer head will be clear of the table as it moves. Then just broke off the filament that was currently in the printer so it will stop feeding once the current piece gets to the end of the feeder wheel. - not an endless loop but should give me a good 10 or 20 minutes of agitation before I need to restart the print if necessary.</p>
1,648
<p>I get a URL from a user. I need to know:<br/> a) is the URL a valid RSS feed?<br/> b) if not is there a valid feed associated with that URL</p> <p>using PHP/Javascript or something similar</p> <p>(Ex. <a href="http://techcrunch.com" rel="nofollow noreferrer">http://techcrunch.com</a> fails a), but b) would return their RSS feed)</p>
<p>Found something that I wanted:</p> <p>Google's <a href="http://code.google.com/apis/ajaxfeeds/" rel="noreferrer">AJAX Feed API</a> has a load feed and lookup feed function (Docs <a href="http://code.google.com/apis/ajaxfeeds/documentation/reference.html#_intro_fonje" rel="noreferrer">here</a>).</p> <p>a) <a href="http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;q=http://www.digg.com/rss/index.xml" rel="noreferrer">Load feed</a> provides the feed (and feed status) in JSON</p> <p>b) <a href="http://ajax.googleapis.com/ajax/services/feed/lookup?v=1.0&amp;q=http://www.techcrunch.com" rel="noreferrer">Lookup feed</a> provides the RSS feed for a given URL</p> <p>Theres also a find feed function that searches for RSS feeds based on a keyword.</p> <p>Planning to use this with JQuery's $.getJSON</p>
<p>Are you doing this in a specific language, or do you just want details about the RSS specification?</p> <p>In general, look for the XML prolog:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; </code></pre> <p>followed by an &lt;rss&gt; element, but you might want to validate it as XML, fully validate it against a DTD, or verify that - for example, each URL referred to is valid, etc. More detail would help.</p> <p><strong>UPDATE</strong>: Ah - PHP. I've found this library to be pretty useful: <a href="http://magpierss.sourceforge.net/" rel="nofollow noreferrer">MagpieRSS</a></p>
8,678
<p>I am doing an Financial Winforms application and am having some trouble with the controls.</p> <p>My customer needs to insert decimal values all over the place (Prices, Discounts etc) and I'd like to avoid some of the repeating validation.</p> <p>So I immediately tried the MaskedTextBox that would fit my needs (with a Mask like "€ 00000.00"), if it weren't for the focus and the length of the mask.</p> <p>I can't predict how big the numbers are my customer is going to enter into the app. </p> <p>I also can't expect him to start everything with 00 to get to the comma. Everything should be keyboard-friendly.</p> <p>Am I missing something or is there simply no way (beyond writing a custom control) to achieve this with the standard Windows Forms controls?</p>
<p>This two overriden methods did it for me (disclaimer: this code is not in production yet. You may need to modify)</p> <pre><code> protected override void OnKeyPress(KeyPressEventArgs e) { if (!char.IsNumber(e.KeyChar) &amp; (Keys)e.KeyChar != Keys.Back &amp; e.KeyChar != '.') { e.Handled = true; } base.OnKeyPress(e); } private string currentText; protected override void OnTextChanged(EventArgs e) { if (this.Text.Length &gt; 0) { float result; bool isNumeric = float.TryParse(this.Text, out result); if (isNumeric) { currentText = this.Text; } else { this.Text = currentText; this.Select(this.Text.Length, 0); } } base.OnTextChanged(e); } </code></pre>
<p>You only need to let numbers and decimal symbols through, and avoid a double decimal symbol. As an extra, this automatically adds a 0 before a starting decimal number.</p> <pre><code>public class DecimalBox : TextBox { protected override void OnKeyPress(KeyPressEventArgs e) { if (e.KeyChar == ',') { e.KeyChar = '.'; } if (!char.IsNumber(e.KeyChar) &amp;&amp; (Keys)e.KeyChar != Keys.Back &amp;&amp; e.KeyChar != '.') { e.Handled = true; } if(e.KeyChar == '.' ) { if (this.Text.Length == 0) { this.Text = "0."; this.SelectionStart = 2; e.Handled = true; } else if (this.Text.Contains(".")) { e.Handled = true; } } base.OnKeyPress(e); } } </code></pre>
30,165
<p>I need to provide users with an easy way to move documents and lists items in WSS 3.0. They want to be able to move across lists, sites and site collections without loss of version history, metadata, and author/date info. This functionality is unfortunately not available OOB. Anyone know a good solution/product?</p>
<p>None of the products out there can do it and even if they do, all of them would modify the dates and the by's (modified by). We developed a custom solution to do that.</p>
<p>Ok, we also ended up developing a custom solution to meet the requirements of the customer. It turned out pretty good and we decided to make a small product out of it. For those interested a free version is now available @ <a href="http://www.sharepointproducts.com" rel="nofollow noreferrer">www.sharepointproducts.com</a> However, the full version is not free.</p>
33,031
<p>What would be the most optimal algorithm (performance-wise) to calculate the number of divisors of a given number?</p> <p>It'll be great if you could provide pseudocode or a link to some example.</p> <p>EDIT: All the answers have been very helpful, thank you. I'm implementing the Sieve of Atkin and then I'm going to use something similar to what Jonathan Leffler indicated. The link posted by Justin Bozonier has further information on what I wanted.</p>
<p>Dmitriy is right that you'll want the Sieve of Atkin to generate the prime list but I don't believe that takes care of the whole issue. Now that you have a list of primes you'll need to see how many of those primes act as a divisor (and how often).</p> <p><strike><a href="https://web.archive.org/web/20141017041436/https://mail.python.org/pipermail/python-list/2005-March/315250.html" rel="nofollow noreferrer">Here's some python for the algo</a></strike> <a href="https://mail.python.org/pipermail/python-list/2005-March.txt" rel="nofollow noreferrer">Look here</a> and search for &quot;Subject: math - need divisors algorithm&quot;. Just count the number of items in the list instead of returning them however.</p> <p><a href="https://web.archive.org/web/20180103053938/http://mathforum.org/library/drmath/view/55843.html" rel="nofollow noreferrer">Here's a Dr. Math</a> that explains what exactly it is you need to do mathematically.</p> <p>Essentially it boils down to if your number <code>n</code> is:<br /> <code>n = a^x * b^y * c^z</code><br /> (where a, b, and c are n's prime divisors and x, y, and z are the number of times that divisor is repeated) then the total count for all of the divisors is:<br /> <code>(x + 1) * (y + 1) * (z + 1)</code>.</p> <p>Edit: BTW, to find a,b,c,etc you'll want to do what amounts to a greedy algo if I'm understanding this correctly. Start with your largest prime divisor and multiply it by itself until a further multiplication would exceed the number n. Then move to the next lowest factor and times the previous prime ^ number of times it was multiplied by the current prime and keep multiplying by the prime until the next will exceed n... etc. Keep track of the number of times you multiply the divisors together and apply those numbers into the formula above.</p> <p>Not 100% sure about my algo description but if that isn't it it's something similar .</p>
<p>I don't know the MOST efficient method, but I'd do the following:</p> <ul> <li>Create a table of primes to find all primes less than or equal to the square root of the number (Personally, I'd use the Sieve of Atkin)</li> <li>Count all primes less than or equal to the square root of the number and multiply that by two. If the square root of the number is an integer, then subtract one from the count variable.</li> </ul> <p>Should work \o/</p> <p>If you need, I can code something up tomorrow in C to demonstrate.</p>
13,560
<p>There are 3 web apps.</p> <p>Site A and B are both ASP.NET Web Application with FormsAuthentications configurations, and there is a protected folder in site B which also configured correctly in the web.config. Site C is a classic ASP web which keep authentication status with Session.</p> <p>Now please consider the following steps:</p> <p>1, There is a link with target="_blank" property on a page of site A and link to the protected folder of site B;</p> <p>2, Click this link you should open the site B in a new browser window and redirect to the log in page;</p> <p>3, Log in with your credentials then redirect to the protected page normally, now you can browse that page of site B of course;</p> <p>4, Now close the browser window which shows the protected page of site B, you can click the close button of browser or press Alt+F4;</p> <p>5, Then click the link on site A again, now you can access the protected page of site B without logging in again.</p> <p>6, There is another link also with target="_blank" on a page of site A and link to the protected page of site C, site C is an ASP site;</p> <p>7, First open the protected page of site C, log in is required exactly;</p> <p>8, Logging in the site C and you can view the protected page of course, then close the browser;</p> <p>9, Click the link to site C again, you can find yourself already authenticated on site C.</p> <p>Oops. there are 10 steps already, I think these are boring but they are really make me confused for few days.</p> <p>Anybody know about this issue? Great Thanks.</p>
<p>Both ASP and ASP.NET use a session cookie which is stored in memory of the browser process. Opening a new browser window from a link doesn't start a new process just opens a new window owned by the same process as the original window.</p> <p>Closing a window doesn't 'logoff' the session because the session cookie will still be in the process memory, when yet another window visits the site the existing session cookie will be sent hence from the sites point of view this is still the same sesssion and that is the correct inferrence to draw.</p> <p><strong>Edit</strong>: The question is raised in a comment, 'How would this be avoided'. The best answer would be: don't avoid it, absorbe it as normal operation and save yourself a bucket load of trouble.</p> <p>What you're asking for is a means of detecting that no windows are currently displaying content for a specific application. This really difficult to acheive. Even if you only have one window on an application (which can't be guaranteed) you'd have to ensure all pages trapped the onunload event on the window the informed the server that the application is being logged off.</p> <p>If its critical that users have the ability to Logoff an application then that is best acheived by providing a logout link on each page in some common header as in this page you're looking at right now.</p> <p>Typically a session in ASP is marked as 'logged on' by storing some kind of token in the session object. Pages that form part of that application would check for that token and if its not present redirect to a login page.</p> <p>To logout the session value is deleted and the client redirected to the login page.</p> <p>In ASP.NET FormsAuthentication has SignOut and a RedirectToLoginPage methods and Forms Authentication handles redirection to the Login page automatically.</p>
<p>Use session.abandoned on window.close event for example.</p> <p>Create function which will be loaded in header and catch event window.close. Do not forget to verify if previous page is from the same domain/IP. Because your user can forgot to logoff and go to some other website and then click back button...</p>
33,603
<p>How can you get MSSQL server to accept Unicode data by default into a VARCHAR or NVARCHAR column?</p> <p>I know that you can do it by placing a N in front of the string to be placed in the field but to by quite honest this seems a bit archaic in 2008 and particuarily with using SQL Server 2005.</p>
<p>The <code>N</code> syntax is how you specify a unicode string literal in SQL Server.</p> <pre><code>N'Unicode string' 'ANSI string' </code></pre> <p>SQL Server will auto convert between the two when possible, using either a column's collation or the database's collation.</p> <p>So if your string literals don't actually contain unicode characters, you do not need to specify the <code>N</code> prefix.</p> <p>But if your string literals <strong>do</strong> contain unicode characters then using the <code>N</code> prefix is necessary.</p>
<p>While you can simply store UTF8 content in a VARCHAR field in MSSQL Server as long as charset translation is not done you should be aware that:</p> <ol> <li><p>No management/reporting/data tools outside of your application will be able to understand your non-english characters.</p></li> <li><p>Language specific handling such as sorting a list of names may not be done in the order acceptable for every language.</p></li> <li><p>Must be careful about data truncation. Truncating a multi-byte UTF8 character ususally causes data corruption for the character involved. You should always reject input if it exceeds the field length.</p></li> <li><p>It may not be as easy as you think to disable charset translation..Even if you turn it off in your client driver it can still be overriden in some cases if there is a significant locale difference between client and RDBMS codepage used which instantly leads to data corruption.</p></li> <li><p>If you think this is all you will have to worry about your fooling yourself.</p></li> </ol> <p>In summary while you might be tempted to go down this path its not a good idea. Code change is required when going multi-byte.</p>
20,187
<p>I know that there is no official API for Google Analytics but is there a way to access Google Analytics Reports with C#?</p>
<p><strong>Update</strong>: Google launched a Google Analytics API today. <a href="http://analytics.blogspot.com/2009/04/attention-developers-google-analytics.html" rel="noreferrer">Google Analytics Blog - API Launched</a></p>
<p>Yet another analytics API for C# <a href="https://github.com/igooana/igooana" rel="nofollow">https://github.com/igooana/igooana</a></p> <p>This project is aimed at C# 5 and uses <code>async/await</code> and <code>dynamic</code> extensively. I tried to make this API as simple as possible and maximum type-safe.</p>
3,657
<p>Is it possible to get Mercurial to show progress of long-running push or pull operation? Google tells me basically "no", but does somebody know better? I was expecting something like <code>hg pull -v</code>...</p>
<pre><code>hg pull -v </code></pre> <p>-v / --verbose</p> <p>is a global option that applies to all sub-functions. </p> <p>If you want extra data: </p> <pre><code> hg --debug -v pull </code></pre>
<pre><code>hg pull -v </code></pre> <p>-v / --verbose</p> <p>is a global option that applies to all sub-functions. </p> <p>If you want extra data: </p> <pre><code> hg --debug -v pull </code></pre>
39,741
<p>Yesterday, I asked <a href="https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p> <p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ:</p> <pre><code> static void Main(string[] args) { var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q; } private static IEnumerable GetRandomNumbers(int max) { Random r = new Random(); while (true) { yield return r.Next(max); } } </code></pre> <p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p> <p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p> <p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem. Thanks!</p> <p><strong>Edit:</strong><br /> Why all the downvotes?</p> <p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p> <p><strong>Apology:</strong><br /> I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
<pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; print random.sample(xrange(100), 5) [61, 54, 91, 72, 85] </code></pre> <p>This should yield 5 unique values in the range <code>0 — 99</code>. The <code>xrange</code> object generates values as requested so no memory is used for values that aren't sampled.</p>
<p>I can't really read your LINQ, but I think you're trying to get 5 random numbers up to 100 and then remove duplicates.</p> <p>Here's a solution for that:</p> <pre><code>def random(max) (rand * max).to_i end # Get 5 random numbers between 0 and 100 a = (1..5).inject([]){|acc,i| acc &lt;&lt; random( 100)} # Remove Duplicates a = a &amp; a </code></pre> <p>But perhaps you're actually looking for 5 distinct random numbers between 0 and 100. In which case:</p> <pre><code>def random(max) (rand * max).to_i end a = [] while( a.size &lt; 5) a &lt;&lt; random( 100) a = a &amp; a end </code></pre> <p>Now, this one might violate your sense of "not too many loops," but presumably Take and Distinct are just hiding the looping from you. It would be easy enough to just add methods to Enumerable to hide the while loop.</p>
14,832
<p>While the built-in analytics of MOSS2007 are nice to have - they are inadequate at the same time. Any ideas where I can look for a more comprehensive package? Am I missing something?</p> <p>Thanks, Carl</p>
<pre><code>var=`svn ls` if [[ $? == 0 ]] then export var else unset var fi </code></pre> <p><code>$?</code> is the exit code of the last command executed, which is <code>svn ls</code> here.</p> <p>jmohr's solution is short and sweet. Adapted mildly,</p> <pre><code>var=`svn ls` &amp;&amp; export var || unset var </code></pre> <p>would be approximately equivalent to the above (<code>export</code> of a valid identifier will never fail, unless you've done something horrible and run out of environment space). Take whatever you want -- I use <code>unset</code> just to avoid <code>$var</code> possibly having a value even though it's not exported.</p>
<pre><code>export FOO=$(your-command) || echo "your-command failed" </code></pre>
30,770
<p>By default the session expiry seems to be 20 minutes. </p> <p>Update: I do not want the session to expire until the browser is closed.</p> <p>Update2: This is my scenario. User logs into site. Plays around the site. Leaves computer to go for a shower (>20 mins ;)). Comes back to computer and <em>should</em> be able to play around. He closes browser, which deletes session cookie. The next time he comes to the site from a new browser instance, he would need to login again.</p> <p>In PHP I can set session.cookie_lifetime in php.ini to zero to achieve this. </p>
<p>If you want to extend the session beyond 20 minutes, you change the default using the IIS admin or you can set it in the web.config file. For example, to set the timeout to 60 minutes in web.config:</p> <pre><code>&lt;configuration&gt; &lt;system.web&gt; &lt;sessionState timeout="60" /&gt; ... other elements omitted ... &lt;/system.web&gt; ... other elements omitted .... &lt;/configuration&gt; </code></pre> <p>You can do the same for a particular user in code with:</p> <pre><code>Session.Timeout = 60 </code></pre> <p>Whichever method you choose, you can change the timeout to whatever value you think is reasonable to allow your users to do other things and still maintain their session.</p> <p>There are downsides of course: for the user, there is the possible security issue of leaving their browser unattended and having it still logged in when someone else starts to use it. For you there is the issue of memory usage on the server - the longer sessions last, the more memory you'll be using at any one time. Whether or not that matters depends on the load on your server.</p> <p>If you don't want to guesstimate a reasonable extended timeout, you'll need to use one of the other techniques already suggested, requiring some JavaScript running in the browser to ping the server periodically and/or abandon the session when a page is unloaded (provided the user isn't going to another page on your site, of course).</p>
<p>There's no way to explicitly clear the session if you don't communicate in some way between the client and the server at the point of window closing, so I would expect sending a special URI request to clear the session at the point of receiving a window close message.</p> <p>My Javascript is not good enough to give you the actual instructions to do that; sorry :(</p>
11,952
<p>I'm trying to start <code>iexplore.exe</code> let it run for 5 seconds and then close it again.</p> <p><code>iexplore</code> opens just fine however it doesn't close when I call the PostThreadMessage. Can anyone see what I'm doing wrong? Here is my code:</p> <pre><code>CString IEPath = "C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE";//GetIEPath(); //IEPath += ' ' + url; std::string strCommand((LPCTSTR)IEPath); PROCESS_INFORMATION procinfo; STARTUPINFO startupinfo; GetStartupInfo(&amp;startupinfo); CreateProcess( NULL, (char *)strCommand.c_str(),// name of executable module NULL, // lpProcessAttributes NULL, // lpThreadAttributes false, // handle inheritance option CREATE_SHARED_WOW_VDM, // creation flags NULL, // new environment block NULL, // current directory name &amp;startupinfo, // startup information &amp;procinfo // process information ); Sleep(5000); ::PostThreadMessage(procinfo.dwThreadId, WM_QUIT, 0, 0); //&lt;---Dosent Close internet explorer! </code></pre> <p>Anyone have an idea of what I'm doing wrong? Or is there better way what to do the trick?</p>
<p>if you can enumerate the windows on the desktop and send a WM_CLOSE to the IE window , it might work .. you can use the spy programme to get the window class of the IE window </p>
<p>I don't have an answer specifically why PostThreadMessage didn't work. But, perhaps if you elaborate on why you want to do this, there is a better solution?</p> <p>For example, if you just want to show a web page for 5 seconds, you can create and show your own window with an embedded Internet Explorer ActiveX control. You'll be also able to add a sink to detect when the web page is loaded in the ActiveX control, so that you start your 5-second counter only after the web page is loaded and displayed.</p>
35,446
<p>I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet</p> <p>Which would you recommend and why?</p>
<p>As Tony said, this is really going to depend on your goals. If you're "tinkering" to try to learn about OpenGL or 3D rendering in general that I would dispense with all pleasantries and start working with PyOpenGL, which is as close are you're going to get to "raw" 3D programming using Python.</p> <p>On the other hand, if you're "tinkering" by way of mocking up a game or multimedia application, or trying to learn about programming practices in general than Pyglet will save you lots of up-front development time by providing hooks for input events, sounds, text/billboarding, etc. Often, this up-front investment is what prevents people from completing their projects, so having it done for you is not something to be ignored. (It is also very Pythonic to avoid reinventing the wheel.)</p> <p>If you are looking to do any sort of heavy-duty lifting (which normally falls outside my definition of "tinkering", but maybe not if you're tinkering with 3D engine design) then you might want to take a look at Python-Ogre, which wraps the <em>very</em> full-featured and robust <a href="http://www.ogre3d.org/" rel="noreferrer">OGRE 3D</a> graphics engine.</p>
<p>pyglet has a lot of nice extras included with it (like image loading and sound). If you're starting out, I'd try pyglet first, and then switch to PyOpenGL if you feel like you want to get closer to the metal.</p> <p>The real important question though is: what are you trying to accomplish? </p>
35,380
<p>In my database application I sometimes have to deal with <code>null</code> strings in the database. In most cases this is fine, but when it comes do displaying data in a form the Swing components - using <code>JTextField</code> for example - cannot handle null strings. (<code>.setText(null)</code> fails)</p> <p>(<strong>EDIT:</strong> I just noticed that <code>JTextField</code> actually accepts a <code>null</code> string, but the question remains for all other cases where unexpected <code>null</code> values can lead to problems.)</p> <p>The null values have no special meaning, they can (must) be treated as empty strings. </p> <p>What is the best practice to deal with this problem? <em>Unfortunatly I cannot change the database</em>.</p> <ul> <li>Checking every value if it is <code>null</code> before calling <code>setText()</code>?</li> <li>Adding a try-catch handler to every <code>setText()</code> call?</li> <li>Introducing a static method which filters all <code>null</code> strings?</li> <li>Replace all <code>null</code> values to empty strings immediatly after reading from the database?</li> <li>... [your suggestions]</li> </ul>
<p>If you are using any ORM tool or somehow you map your DB fields to Java bean you can allways have:</p> <pre> public void setFoo(String str) { this.foo = str != null ? str : ""; } </pre>
<p>If you can, add a default value - empty string - for a field in DB .</p>
34,209
<p>I would like to pass an x amount of geo-locations to the Google Maps API and have it centered around these locations and set the appropriate zoom level so all locations are visible on the map. I.e. show all the markers that are currently on the map.</p> <p>Is this possible with what the Google Maps API offers by default or do I need to resolve to build this myself?</p>
<p>There are a number of ways of doing this but it is pretty easy if you are using the V2 API. See this <a href="http://blog.jeromeparadis.com/archive/2007/02/08/1468.aspx" rel="nofollow noreferrer">post for an example</a>, <a href="http://groups.google.com/group/Google-Maps-API/browse_thread/thread/996f83e075e51fdf/d1d67c0e17c5a490" rel="nofollow noreferrer">this group post</a> or <a href="http://econym.googlepages.com/basic14.htm" rel="nofollow noreferrer">this post</a>.</p>
<p>Gray's Idea is great but does not work as is. I had to work out a hack for a <strong>zoomToMarkers</strong> API V3:</p> <pre><code>function zoomToMarkers(map, markers) { if(markers[0]) // make sure at least one marker is there { // Get LatLng of the first marker var tempmark =markers[0].getPosition(); // LatLngBounds needs two LatLng objects to be constructed var bounds = new google.maps.LatLngBounds(tempmark,tempmark); // loop thru all markers and extend the LatLngBounds object for (var i = 0; i &lt; markers.length; i++) { bounds.extend(markers[i].getPosition()); } // Set the map viewport map.fitBounds(bounds); } } </code></pre>
41,789
<p>I am using VMware Workstation 6.5 on Windows Vista x64. I would like to automate some of the VM management tasks. I know that there is a COM API (<a href="http://www.vmware.com/support/developer/vix-api/" rel="noreferrer">http://www.vmware.com/support/developer/vix-api/</a>) available which I could use directly.</p> <p>Is there a C# wrapper for this COM API?</p> <p>Thanks,</p> <p>Arnie</p>
<p>ArnieZ.</p> <p>Any COM DLL can be used from .NET. Adding it as reference in visual studio will generate a DLL called</p> <p>"YourDll.Interop.dll"</p> <p>This is a .NET -> COM marshaling library, and will do what you need.</p> <p>You can also generate this from the command line using tlbimp.exe</p> <p>Of course, you'll have to keep in mind that you are invoking COM components, and remember to use the .NET Marshaling API to decrease reference counts when you are done using them, otherwise you will cause memory leaks.</p> <p>I've wrapped the interop implementation in another library that implements IDisposable on its objects so that cleanup is handled automatically before, but if it is a large library, this might not be worth the effort.</p>
<p>How 'bout adding a reference to this API in your VS.Net and let VS.Net create a managed wrapper for you? I'm not aware of any "managed" API for this. Let me know if you find it :)</p>
49,283
<p>I'm having some trouble understanding how command parameter binding works.</p> <p>When I create an instance of the widget class before the call to InitializeComponent it seems to work fine. Modifications to the parameter(Widget) in the ExecuteCommand function will be "applied" to _widget. This is the behavior I expected. </p> <p>If the instance of _widget is created after InitializeComponent, I get null reference exceptions for e.Parameter in the ExecuteCommand function.</p> <p>Why is this? How do I make this work with MVP pattern, where the bound object may get created after the view is created?</p> <pre><code>public partial class WidgetView : Window { RoutedCommand _doSomethingCommand = new RoutedCommand(); Widget _widget; public WidgetView() { _widget = new Widget(); InitializeComponent(); this.CommandBindings.Add(new CommandBinding(DoSomethingCommand, ExecuteCommand, CanExecuteCommand)); } public Widget TestWidget { get { return _widget; } set { _widget = value; } } public RoutedCommand DoSomethingCommand { get { return _doSomethingCommand; } } private static void CanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { if (e.Parameter == null) e.CanExecute = true; else { e.CanExecute = ((Widget)e.Parameter).Count &lt; 2; } } private static void ExecuteCommand(object sender, ExecutedRoutedEventArgs e) { ((Widget)e.Parameter).DoSomething(); } } &lt;Window x:Class="CommandParameterTest.WidgetView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WidgetView" Height="300" Width="300" DataContext="{Binding RelativeSource={RelativeSource Self}}"&gt; &lt;StackPanel&gt; &lt;Button Name="_Button" Command="{Binding DoSomethingCommand}" CommandParameter="{Binding TestWidget}"&gt;Do Something&lt;/Button&gt; &lt;/StackPanel&gt; &lt;/Window&gt; public class Widget { public int Count = 0; public void DoSomething() { Count++; } } </code></pre>
<p>InitializeCompenent processes the xaml associated with the file. It is at this point in time that the CommandParameter binding is first processed. If you initialize your field before InitializeCompenent then your property will not be null. If you create it after then it is null.</p> <p>If you want to create the widget after InitializeCompenent then you will need to use a dependency property. The dependency proeprty will raise a notification that will cause the CommandParameter to be updated and thus it will not be null.</p> <p>Here is a sample of how to make TestWidget a dependency property.</p> <pre><code>public static readonly DependencyProperty TestWidgetProperty = DependencyProperty.Register("TestWidget", typeof(Widget), typeof(Window1), new UIPropertyMetadata(null)); public Widget TestWidget { get { return (Widget) GetValue(TestWidgetProperty); } set { SetValue(TestWidgetProperty, value); } } </code></pre>
<p>Even with the dependency property, you still need to call CommandManager.InvalidateRequerySuggested to force the CanExecute of the Command being evaluated.</p>
32,118
<p>For various reasons, such as cookies, SEO, and to keep things simple, I would like to make apache automatically redirect any requests for <a href="http://www.foobar.com/anything" rel="nofollow noreferrer">http://www.foobar.com/anything</a> to <a href="http://foobar.com/anything" rel="nofollow noreferrer">http://foobar.com/anything</a>. The best I could come up with is a mod_rewrite-based monstrosity, is there some easy simple way to tell it "Redirect all requests for domain ABC to XYZ"? </p> <p>PS: I found <a href="https://stackoverflow.com/questions/50931/redirecting-non-www-url-to-www">this somewhat related question</a>, but it's for IIS and does the opposite of what I want. Also it's still complex.</p>
<p>It's as easy as:</p> <pre><code>&lt;VirtualHost 10.0.0.1:80&gt; ServerName www.example.com Redirect permanent / http://example.com/ &lt;/VirtualHost&gt; </code></pre> <p>Adapt host names and IPs as needed :)</p>
<pre><code>RewriteEngine On RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC] RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L] </code></pre> <p>That should do the trick.</p>
11,366
<p>We're in the process of setting up a new framework and way of doing business for our new internal apps. Our current design dictates that all security logic should be handled by our database, and all information (and I mean all) will be going in and out of the database via stored procedures.</p> <p>The theory is, the data access layer requests info from a stored procedure and passes over authentication to the database. The database determines the user's role/permissions and decides whether or not to perform the task (whether that be retrieving data or making an update).</p> <p>I guess this means fewer database transactions. One call to the database. If the security was in our data access layer, this would require 1 database call to determine if the user had proper permissions, and then 1 separate database call to perform the action.</p> <p>I, for one, find the SQL Management studio completely lacking as an IDE. My main concern is we will end up having to maintain some nasty amount of business logic in our stored procedures for some very minimal performance gains.</p> <p>Right now, we're using LINQ for our ORM. It seems light and fast, but best of all, its really easy to rapidly develop in.</p> <p>Is the maintenance cost worth the performance gain? Are we fooling ourselves into thinking there will even be a noticeable performance gain? Or are we just making a nightmare for ourselves?</p> <p>Our environment:</p> <ul> <li>Internal, non-mission critical business apps</li> <li>C#/ASP.NET 3.5</li> <li>Windows 2003</li> <li>MS SQL Server 2005</li> <li>35 Medium sized web apps with approx 500 users</li> </ul>
<p><strong>Don't do that</strong>. We recently had a <strong>VERY BAD</strong> experience when the "database guru" decided to go to another company. The maintenance of all the logic in the procedures are just horrible!!</p> <p>Yes, you're going to have some performance improvement, but that's not worth it. In fact, performance is not even a big concern in internal application. Invest more money in good servers. It'll pay off.</p>
<p>My opinion is that the application itself should handle authentication and authorisation. On the database side you should only handle encryption of data as needed.</p>
7,967
<p>In history-books you often have timeline, where events and periods are marked on a line in the correct relative distance to each other. How is it possible to create something similar in LaTeX?</p>
<p>The <a href="http://ctan.org/pkg/pgf" rel="noreferrer">tikz</a> package seems to have what you want.</p> <pre><code>\documentclass{article} \usepackage{tikz} \usetikzlibrary{snakes} \begin{document} \begin{tikzpicture}[snake=zigzag, line before snake = 5mm, line after snake = 5mm] % draw horizontal line \draw (0,0) -- (2,0); \draw[snake] (2,0) -- (4,0); \draw (4,0) -- (5,0); \draw[snake] (5,0) -- (7,0); % draw vertical lines \foreach \x in {0,1,2,4,5,7} \draw (\x cm,3pt) -- (\x cm,-3pt); % draw nodes \draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $}; \draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $}; \draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $}; \draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$ $}; \draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $}; \draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $}; \draw (6,0) node[below=3pt] {$ $} node[above=3pt] {$ $}; \draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $}; \end{tikzpicture} \end{document} </code></pre> <p>I'm not too expert with tikz, but this does give a good timeline, which looks like:</p> <p><img src="https://i.stack.imgur.com/8hk5B.png" alt="enter image description here"></p>
<p>There is <a href="http://www.tex.ac.uk/tex-archive/macros/latex209/contrib/timeline/timeline.sty" rel="nofollow noreferrer">timeline.sty</a> floating around.</p> <p>The syntax is simpler than using tikz:</p> <pre><code>%%% In LaTeX: %%% \begin{timeline}{length}(start,stop) %%% . %%% . %%% . %%% \end{timeline} %%% %%% in plain TeX %%% \timeline{length}(start,stop) %%% . %%% . %%% . %%% \endtimeline %%% in between the two, we may have: %%% \item{date}{description} %%% \item[sortkey]{date}{description} %%% \optrule %%% %%% the options to timeline are: %%% length The amount of vertical space that the timeline should %%% use. %%% (start,stop) indicate the range of the timeline. All dates or %%% sortkeys should lie in the range [start,stop] %%% %%% \item without the sort key expects date to be a number (such as a %%% year). %%% \item with the sort key expects the sort key to be a number; date %%% can be anything. This can be used for log scale time lines %%% or dates that include months or days. %%% putting \optrule inside of the timeline environment will cause a %%% vertical rule to be drawn down the center of the timeline. </code></pre> <p>I've used python's datetime.data.toordinal to convert dates to 'sort keys' in the context of the package.</p>
26,776
<p>I'm trying to start using LINQ and specifically LINQ to SQL but I'm having some difficulties</p> <p>I've tried this with SqlMetal and now using the database table designer in Visual Studio and I keep getting similar errors, like in this code, using the data context I created with the database layout designer in VS2008.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { string usn = UserNameBox.Text; string pss = PassBox.Text; if (usn == "" || pss == "") return; DataClassesDataContext dc = new DataClassesDataContext(); var user = from u in User where u.UserName == usn select u; } } } </code></pre> <p>I get an error on the where saying: Could not find an implementation of the query pattern for source type 'System.Security.Principal.IPrincipal'. And also: 'Where' not found.</p> <p>I had something similar to this when I tried to use the results of SqlMetal. I deleted that source and started over using the designer. I must be missing something here but I can't figure out what. Shouldn't the tables implement what I need since I'm using LINQ to SQL, or do I need to do something extra to make that happen?</p>
<p>Try </p> <pre><code>var user = from u in dc.User where u.UserName == usn select u; </code></pre>
<p>The User you are referring to (when you don't use dc.User) is the Page.User member. That's why intellisense isn't complaining.</p>
25,054
<p>I am looking to integrate Crystal Reports 2008 into a Windows Forms application. I would like to avoid direct connections from my client application to the database, while giving the user the "complete" report experience. Is it possible to for Crystal Reports 2008 to execute a report on a server into a client-side Windows Forms client control, similar to Microsoft Reporting Services?</p>
<p>I don't know if it is exactly what you are after, but I can think of 2 ways you could fudge it :</p> <ol> <li>You can set up your report so that the 'database' is an XSD file, with no knowledge of the real backend. Then at runtime you push the data to the report.</li> </ol> <p>// Create an instance at runtime appropriate to your environment - example only :</p> <p>ReportClass rc = new ReportClass();</p> <p>rc.Load(crystalReportFileName);</p> <p>rc.SetDataSource(myIEnumerableData); </p> <p>CrystalReportViewer crv = new CrystalReportViewer();</p> <p>crv.ReportSource = rc;</p> <p>// Display the crystal viewer.</p> <p>2 - You could do the same as 1 on a server (regardless of the database approach) , then save the report and push it out to the client.</p> <p>// Some Server-side service / method etc</p> <p>public byte[] GetMyReport() {</p> <p>ReportClass rc = new ReportClass();</p> <p>rc.Load(crystalReportFileName);</p> <p>rc.SetDataSource(myIEnumerableData);</p> <p>rc.SaveAs(serverSideFile, True); // True is critical to save data with report</p> <p>return .... // convert the created file to a byte array I suppose</p> <p>}</p> <p>// Client side</p> <p>byte[] rep = Server. GetMyReport()</p> <p>ReportClass rc = ..... // convert rep back to a crystal report</p> <p>CrystalReportViewer crv = new CrystalReportViewer();</p> <p>crv.ReportSource = rc;</p>
<p>This isn't really what you're asking, but Crystal Reports Server does server-side reporting. </p> <p>On the downside, it's annoyingly expensive.</p> <p><a href="http://www.businessobjects.com/product/catalog/crystalreports_server/" rel="nofollow noreferrer">http://www.businessobjects.com/product/catalog/crystalreports_server/</a></p>
20,423
<p>MSDN displays the following for CreatePatternBrush:</p> <blockquote> <p>You can delete a pattern brush without affecting the associated bitmap by using the DeleteObject function. Therefore, you can then use this bitmap to create any number of pattern brushes.</p> </blockquote> <p>My question is the opposite. If the HBRUSH is long lived, can I delete the HBITMAP right after I create the brush? IE: does the HBRUSH store its own copy of the HBITMAP?</p> <p>In this case, I'd like the HBRUSH to have object scope while the HBITMAP would have method scope (the method that creates the HBRUSH).</p>
<p>The HBRUSH and HBITMAP are entirely independent. The handles can be deleted entirely independent from each other, and, once created, no changes to either object will effect the other.</p>
<p>I think the bitmap must outlive the brush: the brush just references the existing bitmap rather than copying it.</p> <p>You could always try it and see what happened.</p>
7,977
<p>Imagine the following Ruby Module:</p> <pre><code>module Foo def inst_method puts "Called Foo.inst_method" end def self.class_method puts "Called Foo.class_method" end end </code></pre> <p>Obviously <code>Foo.class_method</code> can be called without any class instances. However, what's happening to <code>Foo.inst_method</code>? Is it possible to call <code>Foo.inst_method</code> without previously including/extending a class?</p> <p>Disclaimer: The question isn't focused on solving a real problem. I'm just trying to improve my understanding of the Ruby object system.</p>
<p>The primary purpose of instance methods within modules is to give that functionality to classes that include it.</p> <p>"Mixing in" a module this way is most commonly used as a method of simulating <a href="http://en.wikipedia.org/wiki/Multiple_inheritance" rel="noreferrer">multiple inheritance</a>, or in other situations where inheritance is not the right paradigm (not quite a perfect "is a" relationship) but you want to share behavior. It's one more tool to keep your code <a href="http://en.wikipedia.org/wiki/DRY" rel="noreferrer">DRY</a>.</p> <p>A good example of this in core Ruby is noting how <a href="http://ruby-doc.org/core/classes/Array.html" rel="noreferrer"><code>Array</code></a> and <a href="http://ruby-doc.org/core/classes/Hash.html" rel="noreferrer"><code>Hash</code></a> can both be traveled and sorted, etc. They each get this functionality from the <a href="http://ruby-doc.org/core/classes/Enumerable.html" rel="noreferrer"><code>Enumerable</code></a> module (<code>each_with_index</code>, <code>select</code>, <code>reject</code>, <code>sort</code> and more are all defined in the included module, not in the classes).</p>
<p>My answer would be : "no you can't call module instance methods without first extending or including that module in a class" </p> <p>now knowing ruby and all the meta programming trickery it contains there probably <em>is</em> a way to call it but it would be outside the intended use of modules</p> <pre><code>module Tester def inst_meth puts "test inst meth\n" end def self.meth puts "test self meth\n" end end begin Tester.meth rescue; puts $! end begin Tester.inst_meth rescue puts $! end begin Tester.new.inst_meth rescue puts $! end begin extend Tester inst_meth rescue puts $! end begin include Tester inst_meth rescue puts $! end </code></pre> <p>gives</p> <pre><code>&gt;ruby test.rb test self meth undefined method `inst_meth' for Tester:Module undefined method `new' for Tester:Module test inst meth test inst meth </code></pre>
19,529
<p>I've used jdom in the past, and have looked briefly at XOM and <code>DOM4j</code>. Each seems to provide essentially the same thing, as they each provide a simplified wrapper over the (very obtuse) standard W3C DOM APIs. </p> <p>I know that JDOM went through some effort to develop a JSR and standardization process at one point, but as far as I know that effort never went anywhere. All of the project appear to be in stasis with little new development in the past several years.</p> <p>Is there a consensus as to which is the best? Also what are the pros and cons of each ?</p>
<p>I like <a href="http://www.xom.nu/" rel="nofollow noreferrer">XOM</a>, because I like the way Elliotte Rusty Harold thinks. Of the ones you mention I belive it's the one that strays away from the DOM standard API:s the most, but I consider that a benefit.</p> <p>I once implemented a DOM library for Cocoa, and XOM was my inspiration.</p> <p>I've worked with JDOM as well, and there's absolutely nothing wrong with it, although I do prefer XOM.</p>
<p>It all depends on the feature set. If you want to benefit from an XSL Transformation Engine (Like Xalan) or an XPath Engine (Like Jaxen or Saxon) I would recommend sticking to the more popular framework available like Apache Xerces, JDOM.</p> <p>After that, it's all a matter of taste. I personnally use a W3C compliant ( org.w3c.* ) like Apache Xerces because they are common enough, reasonably fast and well supported by the Java Community.</p> <p>Of course, if you need blinding speed and do not care about XPath, XQuery or XSL, you can surely find yourself something that is much faster and/or resource-hungry. (i.e. A StAX Implementation)</p>
4,521
<p>I have an after_save filter which I dont want to trigger in a specific instance. Is there a way to do this similar to save_without_validation?</p> <p>Thanks,</p>
<p>When using rails 2, you can invoke the private method <code>create_without_callbacks</code> by doing:</p> <pre><code>@my_obj.send(:create_without_callbacks) </code></pre>
<p>There is a good example of extending ActiveRecord to provide callback skipping here: <a href="http://weareintegrum.com/?p=10" rel="nofollow noreferrer">http://weareintegrum.com/?p=10</a></p> <p>The idea is to create a method on ActiveRecord called skip_callback that accepts a block:</p> <pre><code>def self.skip_callback(callback, &amp;block) method = instance_method(callback) remove_method(callback) if respond_to?(callback) define_method(callback){ true } begin result = yield ensure remove_method(callback) define_method(callback, method) end result end </code></pre> <p>Then anything you do within the block does not execute the callback.</p>
40,759
<p>the question I am having is: when running my app with a launch code other than sysAppLaunchCmdNormalLaunch, I can not use code outside the default code segment - but could I use a shared library that is multi-segmented, thus circumventing this problem?</p> <p>A bit of background information: I am evaluating the possibility of porting an existing mobile application to PalmOS. A core part of this app is that it is doing some network communication in the background every 10 minutes or so, or when it receives incoming data (via a network/socket callback). During this time, I do not have access to globals and hence not to any code segments in my application other than the default one.</p> <p>The problem now is that the actions involved in the communication (protocol, data handling, etc) require a lot of code that just does not fit into one segment. Apart from the question whether it makes sense to have that much code run in the 'background', the obvious problem is: how would I run it in the first place? Hence the question, whether putting the code in a shared (multi-segment) library would help.</p> <p>Looking forward to your insights.</p>
<p>I don't have experience with using shared libraries, but we've had this problem with our software, and we've come across three different ways to solve the problem.</p> <p>Possibly the easiest is to enable Expanded Mode when using the Metrowerks compiler, but I'm not completely certain that this works. This special mode allows you to access certain constant global data when called from a non-global launch. However, there are a lot of caveats to using this approach. Also, I have not confirmed that Expanded Mode allows inter-segment jumps for sure. There's a white paper out there written by Ben Combee that explains in detail how to use Expanded Mode. It's titled "Supporting Expanded Mode on Palm OS". I could not find it on the web, so I put up a copy on my website: <a href="http://www.normsoft.com/tim/technical/Codewarrior_Expanded_Mode.pdf" rel="nofollow noreferrer" title="CodeWarrior Expanded Mode">http://www.normsoft.com/tim/technical/Codewarrior_Expanded_Mode.pdf</a></p> <p>Another more complicated option is to load the globals yourself and put a pointer to them in A5. In order to do this, you must modify (or duplicate) the Metrowerks startup code that loads globals and then call this modified code when you receive a non-global launch. Metrowerks includes the full source to this portion of the runtime, so you can do this pretty easily, though some of that code is pretty arcane. We successfully used this technique in one version of Pocket Tunes to access globals and an unlimited number of segments when called from a non-global launch code. Just be sure to restore A5 when returning from the launch code.</p> <p>The final option is to move all (or some of) the code into PNOlets. This can be a pain because you have to segment your code into 68K and PNO, which can quickly become a nightmare to maintain. We've also successfully used this method, but the maintenance of the interworking code was awful. We finally ended up moving our entire code to a PNOlet using the PEAL loader, which works really well for large code because it automatically segments the code into 64KB chunks and runs the ARM code in-place. However, that is a very large effort because PNOlet development is not well-supported on ARM, so you have to provide a lot of low-level support yourself (like thunks for calling each API function).</p>
<p>Store a pointer to a nice large structure you allocate with MemPtr in Ftr memory using FtrSet. This can be retrieved anywhere in your application that needs global access using FtrGet.</p> <p>Alternately use <code>__STANDALONE_CODE_RESOURCE__</code> to put each function into a seperate code segment and use a shared functions.c with wrappers to load and lock these into memory to call them.</p> <pre><code>//segment 1000 UInt32 foobar( char* hi ) { return 12; } // functions.c typedef (UInt32)(*fooPtr)( char* ); // this is now a type representing a pointer to your function. UInt32 foobar( char* hi ) { LocalID id; UInt16 cn; SysCurAppDatabase(&amp;cn,&amp;id); DmOpenRef ref = DmOpenDatabase (cn, id, dmModeReadOnly ); MemHandle H = DmGetResource('code',1000); fooPtr code = MemHandleLock(H); UInt32 result = (*fooPtr)( hi); return result; } </code></pre>
23,626
<p>I'm currently using Magento 1.1.6. My store only sells unique items (shirts with exclusive designs) which means at any one time, only 1 unit is available for each items.</p> <p>How do I omit those items which are already sold from being displayed in the front page?</p> <p>BTW, I'm using these code to show products on the front page:</p> <pre><code>{{block type="catalog/product_list" category_id="3" template="catalog/product/list_home_batik.phtml"}} </code></pre>
<p>Go to System>Configuration>Catalog>Inventory>Stock Options. the dropdown for "Display Out of Stock Products" change to No.</p>
<p>I supposed the file catalog/product/list_home_batik.phtml is based on catalog/product/list.phtml</p> <p>You can modify the file catalog/product/list_home_batik.phtml by adding</p> <pre><code>&lt;?php if($_product-&gt;isSaleable()): ?&gt; </code></pre> <p>just after</p> <pre><code>&lt;?php foreach ($_productCollection as $_product): ?&gt; </code></pre> <p>and by adding</p> <pre><code>&lt;?php foreach ($_productCollection as $_product): ?&gt; </code></pre> <p>just before</p> <pre><code>&lt;?php endforeach; ?&gt; </code></pre> <p>If it doesn't work, you should provide the complete file so I can have a look at it.</p>
49,399
<p>I've started refactoring some legacy code recently and came across two functions for drawing a coordinate grid, the problem is that these functions differ only in orthogonal variables they treat, something like that</p> <pre><code>void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1) { for(int x = x0; x &lt; x1; x += step) { MoveToEx(dc, x, y0, NULL); LineTo(dc, x, y1); } } void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1) { for(int y = y0; y &lt; y1; y += step) { MoveToEx(dc, x0, y, NULL); LineTo(dc, x1, y); } } </code></pre> <p>So if I decide to add some fancy stuff, like antialiasing or merely change drawing pencil or whatever I'll have to put the same code in both of them and it's code duplication and it's bad we all know why.</p> <p>My question is how would you rewrite these two functions into a single one to avoid this problem?</p>
<p>Why you just do not extract the body of the for cycle into a separate function? Then you can do the funny stuff in the extracted function. </p> <pre><code>void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1) { for(int x = x0; x &lt; x1; x += step) { DrawScale(dc, x, y0, x, y1); } } void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1) { for(int y = y0; y &lt; y1; y += step) { DrawScale(dc, x0, y, x1, y); } } private void DrawScale(HDC dc, int x0, int y0, int x1, int y1) { //Add funny stuff here MoveToEx(dc, x0, y0, NULL); LineTo(dc, x1, y1); //Add funny stuff here } </code></pre>
<p>Here is my own solution</p> <pre><code> class CoordGenerator { public: CoordGenerator(int _from, int _to, int _step) :from(_from), to(_to), step(_step), pos(_from){} virtual POINT GetPoint00() const = 0; virtual POINT GetPoint01() const = 0; bool Next() { if(pos > step) return false; pos += step; } protected: int from; int to; int step; int pos; }; class GenX: public CoordGenerator { public: GenX(int x0, int x1, int step, int _y0, int _y1) :CoordGenerator(x0, x1, step),y0(_y0), y1(_y1){} virtual POINT GetPoint00() const { const POINT p = {pos, y0}; return p; } virtual POINT GetPoint01() const { const POINT p = {pos, y1}; return p; } private: int y0; int y1; }; class GenY: public CoordGenerator { public: GenY(int y0, int y1, int step, int _x0, int _x1) :CoordGenerator(y0, y1, step),x0(_x0), x1(_x1){} virtual POINT GetPoint00() const { const POINT p = {x0, pos}; return p; } virtual POINT GetPoint01() const { const POINT p = {x1, pos}; return p; } private: int x1; int x0; }; void DrawScale(HDC dc, CoordGenerator* g) { do { POINT p = g->GetPoint00(); MoveToEx(dc, p.x, p.y, 0); p = g->GetPoint01(); LineTo(dc, p.x, p.y); }while(g->Next()); } </code></pre> <p>But I it seems to me too complicated for such a tiny problem, so I'm looking forward to still see your solutions.</p>
10,621
<p>I'd like to learn assembler. However, there are very few resources for doing assembler with OS X.</p> <p>Is there anyone out there who has programmed in assembly on a Mac? Where did you learn?</p> <p>And, is there any reason I shouldn't be doing assembly? Do I risk (significantly) crashing my computer irreparably?</p>
<p>If you're using a PowerPC Mac, look into gcc inline assembler. Otherwise, look into nasm. I can't give any decent references to PPC ASM (they're few and far between), but I suggest the following things to learn x86 asm:</p> <ul> <li>The book <a href="https://rads.stackoverflow.com/amzn/click/com/0764574817" rel="noreferrer" rel="nofollow noreferrer">Reversing by Eldad Eilam</a></li> <li>Compile simple C source with gcc -S and read the assembly generated</li> <li>Use <a href="http://sandpile.org/" rel="noreferrer">Sandpile</a></li> <li>Join #openrce on irc.freenode.net and use <a href="http://openrce.org/" rel="noreferrer">OpenRCE</a></li> </ul> <p>Also, if you're not in kernel mode then there's no chance of screwing anything up, really, and even if you are in kernel mode it's hard to really destroy anything.</p> <p>Edit: Also, get gcc and such from XCode not Macports or somesuch. You're in for a world of malformed Mach-O files if you don't. Not fun to diagnose file format issues when you're just starting asm hacking.</p>
<p>There's no reason why you shouldn't; there is nothing you can do in assembly language that you can't do in a higher level language like C.</p> <p>As far as tools go, you might want to install <a href="http://macports.org" rel="nofollow noreferrer">MacPorts</a> and get the GNU assembler. That may or may not be the easiest way, but it's free and you can probably find tutorial documentation for writing Unix programs in GNU assembler somewhere on the net.</p>
16,633
<p>Is there a <code>HTMLHelper</code> for file upload? Specifically, I am looking for a replace of</p> <pre><code>&lt;input type="file"/&gt; </code></pre> <p>using ASP.NET MVC HTMLHelper. </p> <p>Or, If I use </p> <pre><code>using (Html.BeginForm()) </code></pre> <p>What is the HTML control for the file upload? </p>
<p><strong>HTML Upload File ASP MVC 3.</strong></p> <p><strong>Model</strong>: (<em>Note that FileExtensionsAttribute is available in MvcFutures. It will validate file extensions client side and server side.</em>)</p> <pre><code>public class ViewModel { [Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv", ErrorMessage = "Specify a CSV file. (Comma-separated values)")] public HttpPostedFileBase File { get; set; } } </code></pre> <p><strong>HTML View</strong>:</p> <pre><code>@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.TextBoxFor(m =&gt; m.File, new { type = "file" }) @Html.ValidationMessageFor(m =&gt; m.File) } </code></pre> <p><strong>Controller action</strong>:</p> <pre><code>[HttpPost] public ActionResult Action(ViewModel model) { if (ModelState.IsValid) { // Use your file here using (MemoryStream memoryStream = new MemoryStream()) { model.File.InputStream.CopyTo(memoryStream); } } } </code></pre>
<p>This is a little hacky I guess, but it results in the correct validation attributes etc being applied</p> <pre><code>@Html.Raw(Html.TextBoxFor(m =&gt; m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\"")) </code></pre>
39,153
<p>Hey all, I need some advice on this...</p> <p>We have certain permissions setup in the database for certain levels of control a user can have over the application. Disabled, ReadOnly and Edit. </p> <p>My question is: Are there more generic/better ways to handle permissions applied to a form element on the page than writing a security method/check per page to enable/disable/hide/show proper controls depending on the permissions allowed?</p> <p>Anyone have any experience handling this in different ways?</p> <p>Edit:</p> <p>I just thought about the possibility of adding constants for each layer that needs security and then adding an IsAuthorized function in the user class that would accept a constant from the form that the control is on, and return boolean to enable/disable controls, this would really reduce the amount of places I'd have to hit when/if I ever need to modify the security for all forms.</p> <p>Cheers!</p>
<p>Sorry for going slightly off-topic here, but learn from my mistake:</p> <p>I had a simple web app one time that I was developing and I thought that I'd setup 3 levels of security: limited read-only (public), read-limited write (user), read-write (admin). The users table had a level of security in it and everything worked fine... until I needed finer control over security levels as the project grew. It all started with a user that needed more than user control in one area of the program but not full admin control.</p> <p>What I should have done was setup an expandable system with finer control even though I didn't need it at first. This would have saved me sooo much time.</p>
<p>To work properly, I have found that access levels should be in this increasing order: NONE, VIEW, REQUIRED, EDIT.</p> <p>Note that REQUIRED is NOT the top level as you may think it would be since EDIT (both populate &amp; de-populate permission) is a greater privilege than REQUIRED (populate-only permission).</p> <p>The enum would look like this:</p> <pre><code>/** NO permissions. * Presentation: "hidden" * Database: "no access" */ NONE(0), /** VIEW permissions. * Presentation: "read-only" * Database: "read access" */ VIEW(1), /** VIEW and POPULATE permissions. * Presentation: "required/highlighted" * Database: "non-null" */ REQUIRED(2), /** VIEW, POPULATE, and DEPOPULATE permissions. * Presentation: "editable" * Database: "nullable" */ EDIT(3); </code></pre> <p>From the bottom layer (database constraints), create a map of fields-to-access. This map then gets updated (further restrained) at the next layer up (business rules + user permissions). Finally, the top layer (presentation rules) can then further restrain the map again if desired.</p> <p>Important: The map must be wrapped so that it only allows access to be <em>decreased</em> with any subsequent update. Updates which attempt to increase access should just be ignored without triggering any error. This is because it should act like a voting system on what the access should look like. In essence, the subsequent layering of access levels as mentioned above can happen in any order since it will result in an access-level low-water-mark for each field once all layers have voted.</p> <p>Ramifications:</p> <p>1) The presentation layer CAN hide a field (set access to NONE) for a database-specified read-only (VIEW) field.</p> <p>2) The presentation layer CANNOT display a field when the business rules say that the user does not have at least VIEW access.</p> <p>3) The presentation layer CANNOT move a field's access up to "editable" (nullable) if the database says it's only "required" (non-nullable).</p> <p>Note: The presentation layer should be made (custom display tags) to render the fields by reading the access map without the need for any "if" statements.</p> <p>The same access map that is used for setting up the display can also be using during the submit validations. A generic validator can be written to read any form and its access map to ensure that all the rules have been followed.</p> <p>(Also see thread: <a href="https://stackoverflow.com/questions/368904/best-practices-for-controlling-access-to-form-fields/1743719#1743719">Best Practices for controlling access to form fields</a>)</p>
34,464
<p>Every time I call this method my NSMutableData is leaking and I cannot figure out how to plug it. theData's retain count is upped by one after the decoder is allocated and initialized and I have no idea why. I am stuck with a retain count of 2 at the end of the method and attempting to release it causes an app crash.</p> <pre><code>- (void)readVenueArchiveFile:(NSString *)inFile key:(NSString *)inKey { NSMutableData *theData; NSKeyedUnarchiver *decoder; theData = [NSData dataWithContentsOfFile:inFile]; decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData]; venueIOList = [[decoder decodeObjectForKey:inKey] mutableCopy]; [decoder finishDecoding]; [decoder release]; } </code></pre>
<p>I would suggest replacing this line:</p> <pre><code>venueIOList = [[decoder decodeObjectForKey:inKey] mutableCopy]; </code></pre> <p>with:</p> <pre><code>ListClassName *decodedList = [decoder decodeObjectForKey:inKey]; self.venueIOList = decodedList; </code></pre> <p>This makes the memory management of <code>decodedList</code> clear. It is considered best practice to assign instance variables using an accessor method (except in init methods). In your current implementation, if you ever invoke <code>readVenueArchiveFile:</code> a second time on the same object, you <strong>will</strong> leak (as you will if <code>decodedList</code> already has a value). Moreover, you can put the copy logic in your accessor method and forget about it rather than having to remember mutableCopy every time you assign a new value (assuming there's a good reason to make a mutable copy anyway?).</p>
<p>Your code is correct; there is no memory leak.</p> <pre><code>theData = [NSData dataWithContentsOfFile:inFile];</code></pre> <p>is equivalent to </p> <pre><code>theData = [[[NSData alloc] initWithContentsOfFile:inFile] autorelease];</code></pre> <p>At this point theData has a reference count of 1 (if less, it would be deallocated). The reference count will be automatically decremented at some point in the future by the autorelease pool.</p> <pre><code>decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];</code></pre> <p>The decoder object keeps a reference to theData which increments its reference count to 2.</p> <p>After the method returns, the autorelease pool decrements this value to 1. If you release theData at the end of this method, the reference count will become 0, the object will be deallocated, and your app will crash when you try to use it.</p>
20,401
<p>I'm trying to pass u url as parameter to a get method. I defined a route that accepts a {*url} parameter so I can send "/" characters without it separating my parameter. As soon as there is a ":" in the url (like in http: or localhost:3857 for example), the method never gets hit.</p> <p>The Html.ActionLink method escapes it's parameter itself, but it doesn't seem to escape the ':'. I cannot escape it manually because then the escape characters get escaped by the very same Html.Actionlink method.</p> <p>any ideas?</p>
<p>Use EncodeUrl before you pass it, and then decode it on the other side.</p>
<p>It's a bit of a hack, but you could replace the ':' with '%3A' (which is the escaped form), and see what the ActionLink does with it. If it's escaped once more, you'd have to replace the twice-escaped version back to ':' at the server, otherwise just replace '%3A' back to ':'</p>
45,935
<p>Can some one specify the windows API, one need to use in order to be able to change programmatically the screen refresh rate?</p>
<p>I found this via a google search. Hope it helps some.</p> <p><a href="http://www.codeproject.com/KB/winsdk/changerefresh.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/winsdk/changerefresh.aspx</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/ms533260(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms533260(VS.85).aspx</a></p>
<p>I found this via a google search. Hope it helps some.</p> <p><a href="http://www.codeproject.com/KB/winsdk/changerefresh.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/winsdk/changerefresh.aspx</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/ms533260(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms533260(VS.85).aspx</a></p>
17,639
<p>I'm trying to copy a bunch of files below a directory and a number of the files have spaces and single-quotes in their names. When I try to string together <code>find</code> and <code>grep</code> with <code>xargs</code>, I get the following error:</p> <pre><code>find .|grep "FooBar"|xargs -I{} cp "{}" ~/foo/bar xargs: unterminated quote </code></pre> <p>Any suggestions for a more robust usage of xargs?</p> <p>This is on <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="noreferrer">Mac&nbsp;OS&nbsp;X 10.5.3</a> (Leopard) with BSD <code>xargs</code>.</p>
<p>You can combine all of that into a single <code>find</code> command:</p> <pre><code>find . -iname "*foobar*" -exec cp -- "{}" ~/foo/bar \; </code></pre> <p>This will handle filenames and directories with spaces in them. You can use <code>-name</code> to get case-sensitive results. </p> <p>Note: The <code>--</code> flag passed to <code>cp</code> prevents it from processing files starting with <code>-</code> as options.</p>
<p>If you are using Bash, you can convert <em>stdout</em> to an array of lines by <code>mapfile</code>:</p> <pre><code>find . | grep "FooBar" | (mapfile -t; cp "${MAPFILE[@]}" ~/foobar) </code></pre> <p>The benefits are:</p> <ul> <li>It's built-in, so it's faster.</li> <li>Execute the command with all file names in one time, so it's faster.</li> <li><p>You can append other arguments to the file names. For <code>cp</code>, you can also:</p> <pre><code>find . -name '*FooBar*' -exec cp -t ~/foobar -- {} + </code></pre> <p>however, some commands don't have such feature.</p></li> </ul> <p>The disadvantages:</p> <ul> <li>Maybe not scale well if there are too many file names. (The limit? I don't know, but I had tested with 10&nbsp;MB list file which includes 10000+ file names with no problem, under Debian)</li> </ul> <p>Well... who knows if Bash is available on OS X?</p>
17,293
<p>Here's a very simple question. I have an SP that inserts a row into a table and at the end there's the statement RETURN @@IDENTITY. What I can't seem to find is a way to retrieve this value in C#. I'm using the Enterprise library and using the method:</p> <pre><code>db.ExecuteNonQuery(cmd); </code></pre> <p>I've tried <strong>cmd.Parameters[0].Value</strong> to get the value but that returns 0 all the time. Any ideas?</p>
<pre><code>Dim c as new sqlcommand("...") Dim d As New SqlParameter() d.Direction = ParameterDirection.ReturnValue c.parameters.add(d) c.executeNonQuery (@@IDENTITY) = d.value </code></pre> <p>It is more or less like this...either this or just return the value from a stored procedure as an output parameter.</p>
<p>Sounds to me like you want to execute with a scalar value</p> <pre><code>SqlCommand.ExecuteScalar() </code></pre> <p>as others have mentioned I think using SCOPE_IDENTITY() is more secure than the @@IDENTITY variable</p>
30,573
<p>I have data coming from the database in the form of a <code>DataSet</code>. I then set it as the <code>DataSource</code> of a grid control before doing a <code>DataBind()</code>. I want to sort the <code>DataSet</code>/<code>DataTable</code> on one column. The column is to complex to sort in the database but I was hoping I could sort it like I would sort a generic list i.e. using a deligate.</p> <p>Is this possible or do I have to transfer it to a different data structure?</p> <p><strong>Edit</strong> I can't get any of these answer to work for me, I think because I am using <strong>.Net 2.0.</strong></p>
<p>Because of how DataTable (and DataView) sorting works, you can't use the delegate approach directly. One workaround is to add a column to the data-table that represents the order, and set the value (per row) based on the desired sequence. You can then add a Sort to the view on this new column. For example (using LINQ to do the sort, just for brevity):</p> <pre><code>var sorted = table.Rows.Cast&lt;DataRow&gt;().OrderBy(row =&gt; your code); int sequence = 0; foreach(var row in sorted) { row["sequence"] = sequence++; } </code></pre> <p>(if you have a typed data-set, then I don't think you need the Cast step, or you would use your typed DataRow subclass)</p> <p>[edit to include 2.0]</p> <p>In 2.0 (i.e. without LINQ etc) you could use a <code>List&lt;T&gt;</code> to do the sort - a bit more long-winded, but:</p> <pre><code> List&lt;DataRow&gt; sorted = new List&lt;DataRow&gt;(); foreach(DataRow row in table.Rows) { sorted.Add(row); } sorted.Sort(delegate(DataRow x, DataRow y) { your code }); int sequence = 0; foreach(DataRow row in sorted) { row["sequence"] = sequence++; } </code></pre> <p>(again, substitute DataRow if you are using a typed data-set)</p>
<p>You can sort the Database in memory , but I don't know what "too complex to sort in the database" would be. If I were you I would try to get it sorted in the database, use Views, Redundancy Indexes, complex SQL statements, it's probably going to be faster than sorting a large Dataset in memory, with the added advantage that it keeps the sort for other kind of clients ( e.g. Web Services, etc)</p>
28,327
<p>Consider two web pages with the following in their body respectively:</p> <pre><code>&lt;body&gt; &lt;script&gt; document.writeln('&lt;textarea&gt;&lt;/textarea&gt;') &lt;/script&gt; &lt;/body&gt; </code></pre> <p>and</p> <pre><code>&lt;body&gt; &lt;script&gt; var t = document.createElement('textarea'); document.body.appendChild(t); &lt;/script&gt; &lt;/body&gt; </code></pre> <p>(think of them as part of something larger, where the textareas <em>have</em> to be generated from JavaScript and can't be hard-coded into the page). They both produce the same output, but the former is considered "bad", while the latter is considered the "right" way to do it. (Right?)</p> <p>On the other hand, if you type something in the page and then either refresh it, or go somewhere else and hit Back, then in the former case, what you typed in the textarea is preserved, while in the later it is lost. (At least on Firefox.)</p> <p>Is there a way to use the latter method and still have the useful feature that what the user has typed into a form is saved even if they accidentally hit refresh or come back via the Back button (at least on Firefox)?</p>
<p>I believe the document.write version actually blows away an existing content on the page. Ie, the body and script tags will no longer be there. That is why people usually use appendChild.</p> <p>Keeping the text or not is very browser specific. I wouldn't bet that Firefox would not change it's behavior on that in a future version, either. I would suggest implementing an alert dialog when the user trys to navigate away from the page and there is unsaved content in edit fields. Usually you would do this with an unload event.</p>
<p>Would it be possible for you to add a hook which you could use to target the new textarea into? eg. a &lt;div&gt;</p> <pre><code>&lt;div id="addtextarea"&gt;&lt;/div&gt; var e = document.getElementByID('addtextarea'); e.innerHTML = '&lt;textarea&gt;&lt;/textarea&gt;'; </code></pre> <p>Then if you needed to remember the contents you could take either the innerHTML value to include the HTML or just the text node value of the textarea to extract the text.</p>
47,929
<p>In WinForms, I can design a form and have a TabValue to control which control is selected each time the user hits 'Tab'. My question, in a Webform, is there a mechanism for doing the same thing? </p> <p>Edit: Does the same apply to an Ajax heavy application?</p>
<p>You can set this with the TabIndex property on the ASP controls. If you want to do this on something that isn't an ASP control, you could also try something like the <a href="http://fluidproject.org/blog/2008/01/11/jquery-tabindex-plugin/" rel="noreferrer">jQuery tabIndex plugin</a>.</p>
<p>Web controls have a TabIndex property that you can set.</p>
29,051
<p>Suppose we have some named enums:</p> <pre><code>enum MyEnum { FOO, BAR = 0x50 }; </code></pre> <p>What I googled for is a script (any language) that scans all the headers in my project and generates a header with one function per enum.</p> <pre><code>char* enum_to_string(MyEnum t); </code></pre> <p>And a implementation with something like this:</p> <pre><code>char* enum_to_string(MyEnum t){ switch(t){ case FOO: return "FOO"; case BAR: return "BAR"; default: return "INVALID ENUM"; } } </code></pre> <p>The gotcha is really with typedefed enums, and unnamed C style enums. Does anybody know something for this?</p> <p>EDIT: The solution should not modify my source, except for the generated functions. The enums are in an API, so using the solutions proposed until now is just not an option.</p>
<p>You may want to check out <a href="http://www.gccxml.org/HTML/Index.html" rel="noreferrer">GCCXML</a>.</p> <p>Running GCCXML on your sample code produces:</p> <pre><code>&lt;GCC_XML&gt; &lt;Namespace id="_1" name="::" members="_3 " mangled="_Z2::"/&gt; &lt;Namespace id="_2" name="std" context="_1" members="" mangled="_Z3std"/&gt; &lt;Enumeration id="_3" name="MyEnum" context="_1" location="f0:1" file="f0" line="1"&gt; &lt;EnumValue name="FOO" init="0"/&gt; &lt;EnumValue name="BAR" init="80"/&gt; &lt;/Enumeration&gt; &lt;File id="f0" name="my_enum.h"/&gt; &lt;/GCC_XML&gt; </code></pre> <p>You could use any language you prefer to pull out the Enumeration and EnumValue tags and generate your desired code.</p>
<p>That's pretty much the only way it can be done (an array of string could work also).</p> <p>The problem is, once a C program is compiled, the binary value of the enum is all that is used, and the name is gone.</p>
24,617
<p>I heard somewhere that you can drop down to C++ directly inside C# code. How is this done? Or did I hear wrong?</p> <p>Note: I do not mean C++ / CLI.</p>
<p>You might be thinking of <a href="http://msdn.microsoft.com/en-us/library/chfa2zb8(VS.71).aspx" rel="nofollow noreferrer"><code>unsafe</code> blocks</a> where you can write code that looks a lot like C++, since you can use pointers.</p>
<p>Why would you need to do that? You can reference native C libraries, but I doubt very much that you can run native code from within managed code.</p>
23,857
<p>Does any one know of a control that i can use with a ASP.Net gridview that provides the functionality of the ASP.Net Ajax Control PagingBulletedList. I want to provide the users with a easier way to access the data in the grid.</p> <p>It should ideally work in the same way paging for the grid works except that it should show all the data for the selected option i.e. if the letter a is selected all items that begin with a are shown to the user.</p> <p>I would prefer not to have to re develop something like this as i am sure it exists, i just have no idea what would you call it.</p> <p>Thanks in advance.</p>
<p>Unfortunatly there is nothing already buildt for this. To build your own you will have to create your own <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.pagertemplate.aspx" rel="nofollow noreferrer">PagerTemplate</a>.</p> <p>There is something similiar with code in it in this <a href="http://www.highoncoding.com/Articles/209_GridView%20Alphabet%20Paging.aspx" rel="nofollow noreferrer">tutorial</a>. This tutorial migh help you well to achieve what you require. I would have done it differently with PagerTemplate instead of GridView Footer as show.</p> <p>So basically to create the paging bar it would have give :</p> <pre><code>&lt;asp:UpdatePanel runat="server" ID="UpdatePanel"&gt; &lt;asp:GridView runat="server" ID="GridView"&gt; &lt;PagerTemplate&gt; &lt;asp:LinkButton runat="server" Text="A" Command="A" /&gt; - &lt;asp:LinkButton runat="server" Text="B" Command="B" /&gt; - &lt;asp:LinkButton runat="server" Text="C" Command="C" /&gt; - &lt;asp:LinkButton runat="server" Text="D" Command="D" /&gt; - &lt;asp:LinkButton runat="server" Text="E" Command="E" /&gt; &lt;%-- Continue at will... --%&gt; &lt;/PagerTemplate&gt; &lt;/asp:GridView&gt; &lt;/asp:UpdatePanel&gt; </code></pre> <p>Then you catch in the code behind the command and re create a new Datasource with only the data for the letter you need. You have to understand that GridView is bind to a Datasource that can't be manipulated. So when you initially show it, the datasource provider will only send the data with letter A. When you will click F then you will request you data provider to retreive only the information with Letter F and reassign the data to gridview : GridView.Datasource = mynewdata</p> <p>Hope this helps</p>
<p>DataGrid has its own set of data sorting that you can tap, for example, you can page a GridView by adding 'AllowPaging="true"' in the gridview markup (or by code-behind, doesn't matter). You can also allow for sorting ('AllowSorting="true"').</p> <p>Unfortunately, I haven't come across a control of such nature where you can filter based on letter. However, I did create a custom control for it that merely did a DataTable.Select() and rebounded the GridView to the new DataSet. It's really not all that hard to develop it, and it's good to have a control of such nature. One other thing too is you could add a textbox that will filter based on the results entered by the user - but that's more of a suggestion than solution.</p> <p>Hope this helps!</p>
48,015
<p>Is it possible to access the database backend of a sharepoint server? My company uses Sharepoint to store data and pictures of various assets. Ideally I would be able to access the data and display it in my application to allow users both methods of access.</p> <p>Before I go talk to the IT department I would like to find out if this is even possible?</p> <p>Edit: From rails on linux? (Yes, I know I'm crazy)</p>
<p>Agree with Adam. Querying the Sharepoint Database is a big no-no, as Microsoft does not guarantee that the Schema is in any way stable. Only access the database if there is really no other way.</p> <p>As for Sharepoint, usually the Lists.asmx Web Service is what you want to look at first.</p> <p><a href="https://www.c-sharpcorner.com/article/access-sharepoint-portal-server-using-web-services-in-net/" rel="nofollow noreferrer">http://www.c-sharpcorner.com/UploadFile/mahesh/WSSInNet01302007093018AM/WSSInNet.aspx</a></p> <p><a href="https://web.archive.org/web/20200221152136/http://geekswithblogs.net:80/mcassell/archive/2007/08/22/Accessing-Sharepoint-Data-through-Web-Services.aspx" rel="nofollow noreferrer">http://geekswithblogs.net/mcassell/archive/2007/08/22/Accessing-Sharepoint-Data-through-Web-Services.aspx</a></p>
<p>Just a small comment. Never ever go to the database direct. If there is no way to do it via published and supported API's, then there is no way to do it. End of story. This applies even to when you are "just reading data", as this can still cause significant issues.</p>
5,316
<p>I just want ask the steps when trying to create a simple SQL select statement in UNIX inside/within IF..THEN..FI statement.</p> <p>I know how to use the 'select' and 'if..then' statements in SQL*Plus, but I'm having a difficulties having a UNIX script to point to variables: If 'ABC' to 'Select...'</p> <h2>Example:</h2> <p>if [ "$?" = 'ABC' ] then SELECT employid, name, age FROM tablename; else exit 1 fi</p> <p>if [ "$?" = 'XYZ' ] then SELECT employid, name, age FROM tablename; else exit 1 fi</p> <p>How do I put it in a UNIX script more correctly syntax wise and right to the point?</p> <p>Thanks.</p>
<p>This sounds like you're trying to embed SQLPlus in a shell script. From memory the incantation should look something like:</p> <pre><code>if [ $? -eq ABC ]; then SQLPLUS /S USER/PASS@Instance &lt;&lt;EOF SET echo off; SET pagesize 0; SET heading off; SPOOL foo.out select foo from bar EOF fi </code></pre> <p>Everything between the SQLPLUS and EOF is passed to SQLPlus, so we have some statements to control the formatting (you may want different ones) and the actual query. The SPOOL command in the SQLPlus script sends the output to a file. For more detailed docs on using SQLPlus, You can download them from <a href="http://www.oracle.com/technology/docs/tech/sql_plus/index.html" rel="nofollow noreferrer">Oracle's web site.</a></p>
<p>The above answer was ok. However, I knew that, using SQLPlus in a shell script and unfortunately, I don't need the SQLPlus script to send the output to a file. In other words: Is there any other way of doing this, just print the output to a log?</p>
35,738
<p>I have a small C library in a DLL and I need to call a handful of its methods.</p> <p>It uses pointers and a few structs but is otherwise quite simple. Problem is I'm not terribly knowledgable on .NET's interop with the unmanaged world and my attempts so far keep hitting memory access violation exceptions (presumably due to me not getting the pointers quite right).</p> <p>Could anyone give me some pointers (ooh a pun!) on the best way to approach this?</p> <p>Thank you</p> <pre><code>extern vconfig_t *Pobsopen(Ppoly_t ** obstacles, int n_obstacles); extern int Pobspath(vconfig_t * config, Ppoint_t p0, int poly0, Ppoint_t p1, int poly1, Ppolyline_t * output_route); extern void Pobsclose(vconfig_t * config); struct vconfig_t { int Npoly; int N; Ppoint_t *P; int *start; int *next; int *prev; }; typedef struct Ppoly_t { Ppoint_t *ps; int pn; } Ppoly_t; typedef Ppoly_t Ppolyline_t; typedef struct Pxy_t { double x, y; } Pxy_t; typedef struct Pxy_t Ppoint_t; typedef struct Pxy_t Pvector_t; </code></pre>
<p>You should check out the <a href="http://download.microsoft.com/download/f/2/7/f279e71e-efb0-4155-873d-5554a0608523/CLRInsideOut2008_01.exe" rel="noreferrer">tool</a> given in this MSDN Magazine <a href="http://msdn.microsoft.com/en-us/magazine/cc164193.aspx" rel="noreferrer">article</a> that can translate a C snippet to C# P/Invoke signatures, and of course the post as well.</p> <p>Running the tool for your code snippet gives you this:</p> <pre><code>[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct vconfig_t { /// int public int Npoly; /// int public int N; /// Ppoint_t* public System.IntPtr P; /// int* public System.IntPtr start; /// int* public System.IntPtr next; /// int* public System.IntPtr prev; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct Ppoly_t { /// Ppoint_t* public System.IntPtr ps; /// int public int pn; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct Pxy_t { /// double public double x; /// double public double y; } public partial class NativeMethods { /// Return Type: vconfig_t* ///obstacles: Ppoly_t** ///n_obstacles: int [System.Runtime.InteropServices.DllImportAttribute("&lt;Unknown&gt;", EntryPoint="Pobsopen")] public static extern System.IntPtr Pobsopen(ref System.IntPtr obstacles, int n_obstacles) ; /// Return Type: int ///config: vconfig_t* ///p0: Ppoint_t-&gt;Pxy_t ///poly0: int ///p1: Ppoint_t-&gt;Pxy_t ///poly1: int ///output_route: Ppolyline_t* [System.Runtime.InteropServices.DllImportAttribute("&lt;Unknown&gt;", EntryPoint="Pobspath")] public static extern int Pobspath(ref vconfig_t config, Pxy_t p0, int poly0, Pxy_t p1, int poly1, ref Ppoly_t output_route) ; /// Return Type: void ///config: vconfig_t* [System.Runtime.InteropServices.DllImportAttribute("&lt;Unknown&gt;", EntryPoint="Pobsclose")] public static extern void Pobsclose(ref vconfig_t config) ; } </code></pre>
<p>Maybe you should write your wrapper in C++/CLI, because the interop between managed code and unmanaged code is very seamless.</p> <p><strong>Update</strong></p> <p>Here is a link to a trivial example: <a href="https://stackoverflow.com/questions/343654/c-data-structure-to-mimic-cs-listlistint#343683">C data structure to mimic C#’s List>?</a></p>
46,901
<p>In c#, is there any difference in the excecution speed for the order in which you state the condition?</p> <pre><code>if (null != variable) ... if (variable != null) ... </code></pre> <p>Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.</p> <p>If there is no difference, what is the advantage of the first one?</p>
<p>It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code):</p> <pre><code>// Probably wrong if (x = 5) </code></pre> <p>when you actually probably meant</p> <pre><code>if (x == 5) </code></pre> <p>You can work around this in C by doing:</p> <pre><code>if (5 == x) </code></pre> <p>A typo here will result in invalid code.</p> <p>Now, in C# this is all piffle. Unless you're comparing two Boolean values (which is rare, IME) you can write the more readable code, as an "if" statement requires a Boolean expression to start with, and the type of "<code>x=5</code>" is <code>Int32</code>, not <code>Boolean</code>.</p> <p>I suggest that if you see this in your colleagues' code, you educate them in the ways of modern languages, and suggest they write the more natural form in future.</p>
<p>One more thing... If you are comparing a variable to a constant (integer or string for ex.), putting the constant on the left is good practice because you'll never run into NullPointerExceptions :</p> <pre><code>int i; if(i==1){ // Exception raised: i is not initialized. (C/C++) doThis(); } </code></pre> <p>whereas</p> <pre><code>int i; if(1==i){ // OK, but the condition is not met. doThis(); } </code></pre> <p>Now, since by default C# instanciates all variables, you shouldn't have that problem in that language.</p>
34,153
<p>I have an Anet A8 printer for about 4 months, set up pretty well (or so I thought) and printing a number of models pretty well. I made a large 3" x 6" box with a sliding lid yesterday and when it was done there was a gap on one side when the lid was slid on. I checked the parts and it turns out they are not square - which means the X and Y axes are not square to each other.</p> <p>I'm wondering how to adjust this - I'm thinking that extending the distance between the back of the frame and the front by adjusting the threaded rods that separate them to a wider distance on the side where the angle is obtuse. Obviously one of the first things I'll check is that the distance between the front and back is the same (I can't imagine why I never checked that before, come to think of it).</p> <p>Does this sound like a sound plan?</p>
<p><strong>Quick, low-tech solution:</strong></p> <p>There might be several issues in your question, but in relation to bed adhesion, I'll share one of the most useful tips I wish someone had told me when I started out: <em>Spread some glue-stick over the area to be printed</em>.</p> <p>I used ordinary school/craft glue stick (which I stole from my daughter's school pencil case) - the kind for gluing paper. I use a purple one, so it's easy to see and easy to clean up. I apply a little glue then smear it around with a wet finger to make it a bit uniform.</p> <p>I have a heated bed (FlashForge Creator Pro) and have used this little trick with a range of filaments. In almost every case, it helps adhesion enormously. Parts and supports stick like mad! But they still come off easily enough the usual way. It is a weak glue, so it won't lock the part to the bed. Once the part is off, the purple glue is visible when wet, so it is dead easy to clean up the part and the bed in a minute or two.</p> <p>This trick is so easy that it is worth trying first for any adhesion issues, before digging deeper.</p>
<p>It is hard to determine the exact source of the problem as there are few possibilities (I am assuming that you have a single nozzle and only one filament in use):</p> <ol> <li><p>One of the hardest issues for me to get on my printer was fact that my auto-level sensor was mounted about 0.5mm too high - so please check that as this will give you a bit higher Z than expected.</p></li> <li><p>Printing speed matters - for some prints I was slowing my printer to 20% of nominal speed to get adhesion</p></li> <li><p>a hair-spray layer or a masking tape on the bed could help with getting the grip</p></li> <li><p>also you could play with nozzle temperature de/increasing by 5 degrees and see how it is going</p></li> </ol>
864
<p>We just ran into a problem where everything was compiling correctly, but not being deployed to the mobile device during debugging. Of course this caused weird errors that were hard to track down. The solution was simple, just delete the directories on the mobile device. Is there a way to ensure/force the files to be deployed every time? A VS setting? Is it version ing on our assembly not changing? </p>
<p>Using VS2005 and unmanaged code (C++), I notice that VS will not deploy a new binary if there is already one on the device with a higher version number. If it is the same or lower, then everything is fine.</p>
<p>In my experience, ActiveSync is not very consistent.<br> Also, if the application deploys correctly if you first remove it from the device, it is probably not a configuration problem either. At least with VS2005 there are no magic knobs to twist in this regard. Does the deployment go very quickly, or does it look like it is actually deploying?<br> My suggestion would be to try ActiveSync over Bluetooth. IMHO it is more stable than over USB. (Unless, ofcourse, you are running on the emulator...)</p>
38,851
<p>I'm trying to figure out what the following line does exactly - specifically the %%s part?</p> <pre><code>cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n)) </code></pre> <p>Any good mini-tutorial about string formatting and inserting variables into strings with Python?</p>
<p>The <code>%%</code> becomes a single <code>%</code>. This code is essentially doing two levels of string formatting. First the <code>%sourcedest</code> is executed to turn your code essentially into:</p> <pre><code>cursor.execute('INSERT INTO mastertickets (BLAH, FOO) VALUES (%s, %s)', (self.tkt.id, n)) </code></pre> <p>then the db layer applies the parameters to the slots that are left.</p> <p>The double-% is needed to get the db's slots passed through the first string formatting operation safely.</p>
<p>It does the same:</p> <pre><code>cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (:%s, :%s)' % \ tuple(sourcedest + sourcedest), dict(zip(sourcedest, (self.tkt.id, n)))) </code></pre> <p>Never do that.</p>
40,993
<p>Recently our team was facing the task to build the 2D slice between a plane and some set of 3D geometry (set of triangles). Google hasn't been as helpful as we have wanted it to be, so we turn our attention here to see if anyone has encountered this problem with a possible solution. Links are also wanted.</p> <p>Finding the intersection points in itself isn't a hard task, but ensuring triangles being generated correctly with correct corner composition is playing a hard game with us. We simply lack the math/understanding of how triangle construction from an arbirtrary model is done.</p> <p>If you have problems understanding what we're trying to do, imagine this scenario: </p> <p>A bunny model is loaded into the program. Next a "laser" travels across space, cutting the bunny in half. That thin slice that the laser cut is the slice we want to generate. It should be a 2D triangle set. If laser doesn't cut it for you (no pun intended), think knife, plane, anything that slices something across a plane.</p> <p>Thanks in advance.</p>
<p>If you're not tied to any particular software, open your data set in ParaView (paraview.org) or ParaViewGeo (paraviewgeo.mirarco.org). </p> <p>Both have a filter called Slice that does excactly what you're talking about and both allow you to save your data back out. </p> <p>ParaViewGeo supports data formats (GoCad, DataMine, and others) commonly used by the exploration/mining/geology industry and that is the only real difference between the two pieces of software. </p> <p>There are also many other filters available in these software packages you may find interesting, such as Clip (cut your bunny in half and view one of the halves), and Threshold (say you assigned values to parts of your bunny, e.g. region id's like ears, nose, eyes, feet, etc you could "threshold" so that only those parts are left over to view)</p>
<p>The intersection of a plane and a triangle is a line segment or nothing (ignoring the degenerate case of the triangle being exactly in the plane).</p> <p>So the result of your laser/knife scanning/slicing across the bunny model triangles is a collection of line segments. I'm not sure how/why you'd expect to get a "2D triangle set" out as a result.</p> <p>If you want to take the (possibly non-convex) polygon(s) formed by those line segments and "fill them in" with triangles, <a href="http://www.cgal.org/Manual/3.3/doc_html/cgal_manual/Partition_2/Chapter_main.html" rel="nofollow noreferrer">CGAL's polygon tools</a> might do the job (my guess is the couple of pictures on that page are something like what you're trying to achieve).</p>
25,500
<p>Is there a one button way to save a screenshot directly to a file in Windows?</p> <br> TheSoftwareJedi accurately answered above question for Windows 8 and 10. Below original extra material remains for posterity. <blockquote> <p>This is a very important question as the 316K views shows as of 2021. Asked in 2008, SO closed this question around 2015 as being off-topic, probably because of the last question below.</p> </blockquote> <blockquote> <p>In Windows XP, one can press Alt-PrintScreen to copy an image of the active window, or Ctrl-PrintScreen to copy an image of the full desktop.</p> <p>This can then be pasted into applications that accept images: Photoshop, Microsoft Word, etc.</p> <p>I'm wondering: <b>Is there a way to save the screenshot directly to a file?</b> Do I <i>really</i> have to open an image program, like Paint.net or Photoshop, simply to paste an image, then save it?</p> </blockquote>
<p>You can code something pretty simple that will hook the PrintScreen and save the capture in a file.</p> <p>Here is something to start to capture and save to a file. You will just need to hook the key "Print screen".</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Drawing; using System.IO; using System.Drawing.Imaging; using System.Runtime.InteropServices; public class CaptureScreen { static public void Main(string[] args) { try { Bitmap capture = CaptureScreen.GetDesktopImage(); string file = Path.Combine(Environment.CurrentDirectory, "screen.gif"); ImageFormat format = ImageFormat.Gif; capture.Save(file, format); } catch (Exception e) { Console.WriteLine(e); } } public static Bitmap GetDesktopImage() { WIN32_API.SIZE size; IntPtr hDC = WIN32_API.GetDC(WIN32_API.GetDesktopWindow()); IntPtr hMemDC = WIN32_API.CreateCompatibleDC(hDC); size.cx = WIN32_API.GetSystemMetrics(WIN32_API.SM_CXSCREEN); size.cy = WIN32_API.GetSystemMetrics(WIN32_API.SM_CYSCREEN); m_HBitmap = WIN32_API.CreateCompatibleBitmap(hDC, size.cx, size.cy); if (m_HBitmap!=IntPtr.Zero) { IntPtr hOld = (IntPtr) WIN32_API.SelectObject(hMemDC, m_HBitmap); WIN32_API.BitBlt(hMemDC, 0, 0,size.cx,size.cy, hDC, 0, 0, WIN32_API.SRCCOPY); WIN32_API.SelectObject(hMemDC, hOld); WIN32_API.DeleteDC(hMemDC); WIN32_API.ReleaseDC(WIN32_API.GetDesktopWindow(), hDC); return System.Drawing.Image.FromHbitmap(m_HBitmap); } return null; } protected static IntPtr m_HBitmap; } public class WIN32_API { public struct SIZE { public int cx; public int cy; } public const int SRCCOPY = 13369376; public const int SM_CXSCREEN=0; public const int SM_CYSCREEN=1; [DllImport("gdi32.dll",EntryPoint="DeleteDC")] public static extern IntPtr DeleteDC(IntPtr hDc); [DllImport("gdi32.dll",EntryPoint="DeleteObject")] public static extern IntPtr DeleteObject(IntPtr hDc); [DllImport("gdi32.dll",EntryPoint="BitBlt")] public static extern bool BitBlt(IntPtr hdcDest,int xDest,int yDest,int wDest,int hDest,IntPtr hdcSource,int xSrc,int ySrc,int RasterOp); [DllImport ("gdi32.dll",EntryPoint="CreateCompatibleBitmap")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport ("gdi32.dll",EntryPoint="CreateCompatibleDC")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport ("gdi32.dll",EntryPoint="SelectObject")] public static extern IntPtr SelectObject(IntPtr hdc,IntPtr bmp); [DllImport("user32.dll", EntryPoint="GetDesktopWindow")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll",EntryPoint="GetDC")] public static extern IntPtr GetDC(IntPtr ptr); [DllImport("user32.dll",EntryPoint="GetSystemMetrics")] public static extern int GetSystemMetrics(int abc); [DllImport("user32.dll",EntryPoint="GetWindowDC")] public static extern IntPtr GetWindowDC(Int32 ptr); [DllImport("user32.dll",EntryPoint="ReleaseDC")] public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDc); } </code></pre> <p><strong>Update</strong> Here is the code to hook the PrintScreen (and other key) from C#:</p> <p><a href="http://forum.cheatengine.org/viewtopic.php?t=192699&amp;sid=d25bb4a9d48a3518bba28ec63d6510a2" rel="noreferrer">Hook code</a></p>
<p>Is this possible:</p> <ol> <li>Press Alt PrintScreen</li> <li>Open a folder</li> <li>Right click -> paste screenshot</li> </ol> <p>Example:</p> <p>Benchmark result window is open, take a screenshot. Open C:\Benchmarks Right click -> Paste screenshot A file named screenshot00x.jpg appears, with text screenshot00x selected. Type Overclock5</p> <p>Thats it. No need to open anything. If you do not write anything, default name stays. </p>
19,119
<p>I want to use Perl to extract information from a <a href="http://en.wikipedia.org/wiki/Certificate_signing_request" rel="nofollow noreferrer">Certificate Signing Request</a>, preferably without launching an external openssl process. Since a CSR is stored in a base64-encoded ASN.1 format, I tried the <a href="http://search.cpan.org/~btrott/Convert-PEM-0.07/lib/Convert/PEM.pm" rel="nofollow noreferrer">Convert::PEM</a> module. But it requires an ASN.1 description of the content, which I haven't been able to put together (ASN.1 being the beast it is).</p> <p>Does anybody have the right ASN.1 description for a CSR or a module that parses such a request ? </p>
<p>Maybe <a href="http://search.cpan.org/dist/Convert-X509/" rel="nofollow noreferrer">Convert::X509</a> can help you. See also <a href="http://search.cpan.org/src/LEO/Convert-X509-0.1/X509/Parser.pm" rel="nofollow noreferrer">Convert::X509::Parser</a>.</p>
<p>Your real question is what format are CSRs using? There are two formats to do it, PKCS #10 and SPKAC. The former is described in <a href="https://www.rfc-editor.org/rfc/rfc2986" rel="nofollow noreferrer">RFC 2986</a>. I don't know where the latter is described.</p>
27,959
<p>Why can't I create a <code>class</code> in <code>VB.NET</code> that <code>inherits</code> <code>System.IO.Directory</code>? According to Lutz Roeder, it is <em>not</em> declared as <code>NotInheritable</code>!</p> <p>I want to create a <code>utility class</code> that adds functionality to the <code>Directory class</code>. For instance, I want to add a <code>Directory.Move</code> function.</p> <p>Please advise and I will send you a six pack. OK nevermind I'm not sending you anything but if you come to the bar tonight I will hook you up and then beat you in pool.</p>
<p>From the Meta Data of .NET</p> <pre><code>namespace System.IO { // Summary: // Exposes static methods for creating, moving, and enumerating through directories // and subdirectories. This class cannot be inherited. [ComVisible(true)] public static class Directory </code></pre> <p>You cannot inherit from a Static Class.</p>
<p>I'd guess that Reflector isn't picking up the sealed attribute correctly for VB (or perhaps just not displaying it properly). If you look at the IL, it is sealed:</p> <p>class public abstract auto ansi <strong>sealed</strong> beforefieldinit Directory</p>
16,437
<p>I was surprised recently to find that it's possible to have a return statement in a finally block in Java.</p> <p>It seems like lots of people think it's a bad thing to do as described in '<a href="https://web.archive.org/web/20070922061412/http://weblogs.java.net/blog/staufferjames/archive/2007/06/_dont_return_in.html" rel="noreferrer">Don't return in a finally clause</a>'. Scratching a little deeper, I also found '<a href="https://web.archive.org/web/20190528011825/http://www.cs.arizona.edu/projects/sumatra/hallofshame/" rel="noreferrer">Java's return doesn't always</a>' which shows some pretty horrible examples of other types of flow control in finally blocks.</p> <p>So, my question is, can anyone give me an example where a return statement (or other flow control) in a finally block produces better / more readable code?</p>
<p>The examples you provided are reason enough to <i>not</i> use flow-control from finally.</p> <p>Even if there's a contrived example where it's "better," consider the developer who has to maintain your code later and who might not be aware of the subtleties. That poor developer might even be you....</p>
<p>Returning from inside a <code>finally</code> block will cause <code>exceptions</code> to be lost.</p> <p><strong>A return statement inside a finally block will cause any exception that might be thrown in the try or catch block to be discarded.</strong> </p> <p>According to the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2" rel="nofollow noreferrer"><strong>Java Language Specification:</strong></a></p> <blockquote> <p>If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice:</p> <pre><code> If the finally block completes normally, then the try statement completes abruptly for reason R. If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded). </code></pre> </blockquote> <p><em>Note: As per <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.17" rel="nofollow noreferrer">JLS 14.17</a> - a return statement always completes abruptly.</em></p>
7,045
<p>Assuming a largish template library with around 100 files containing around 100 templates with overall more than 200,000 lines of code. Some of the templates use multiple inheritance to make the usage of the library itself rather simple (i.e. inherit from some base templates and only having to implement certain business rules).</p> <p>All that exists (grown over several years), "works" and is used for projects.</p> <p>However, compilation of projects using that library consumes a growing amount of time and it takes quite some time to locate the source for certain bugs. Fixing often causes unexpected side effects or is quite difficult, because some interdependent templates need changing. Testing is nearly impossible due to the sheer amount of functions.</p> <p>Now, I would really like to simplify the architecture to use less templates and more specialized smaller classes.</p> <p>Is there any proven way to go about that task? What would be a good place to start?</p>
<p>I'm not sure I see how/why templates are the problem, and why plain non-templated classes would be an improvement. Wouldn't that just mean even <em>more</em> classes, less type safety and so larger potential for bugs?</p> <p>I can understand simplifying the architecture, refactoring and removing dependencies between the various classes and templates, but automatically assuming that "fewer templates will make the architecture better" is flawed imo.</p> <p>I'd say that templates <em>potentially</em> allow you to build a much cleaner architecture than you'd get without them. Simply because you can make separate classes <em>totally</em> independent. Without templates, classes functions which call into another class must know about the class, or an interface it inherits, in advance. With templates, this coupling isn't necessary. </p> <p>Removing templates would only lead to <em>more</em> dependencies, not fewer. The added type-safety of templates can be used to detect a lot of bugs at compile-time (Sprinkle your code liberally with static_assert's for this purpose)</p> <p>Of course, the added compile-time may be a valid reason to avoid templates in some cases, and if you only have a bunch of Java programmers, who are used to thinking in "traditional" OOP terms, templates might confuse them, which can be another valid reason to avoid templates.</p> <p>But from an architecture point of view, I think avoiding templates is a step in the wrong direction.</p> <p>Refactor the application, sure, it sounds like that's needed. But don't throw away one of the most useful tools for producing extensible and robust code just because the original version of the app misused it. Especially if you're already concerned with the amount of code, removing templates will most likely lead to <em>more</em> lines of code.</p>
<p>As mentioned, unit tests are a good idea. Indeed, rather than breaking your code by introducing "simple" changes that are likely to ripple out, just focus on creating a suite of tests, and fixing non-compliance with the tests. Have an activity to update the tests when bugs come to light.</p> <p>Beyond that, I would suggest upgrading your tools, if possible, to help with debugging template-related problems.</p>
41,955
<p>I've got a cool piece of code taken from a VC++ project which gets complete information of the hard disk drive WITHOUT using WMI (since WMI has got its own problems).</p> <p>I ask those of you who are comfortable with API functions to try to convert this VB6 code into VB.NET (or C#) and help A LOT of people who are in great need of this utility class.</p> <p>I've spent lots of time and searched the entire net to find ways to get the actual model and serial number of HDD and eventually found this one, if only it were in .NET...</p> <p>Here is the code and sorry about its formatting problems, just paste it into VB6 IDE:</p> <pre><code>Option Explicit ''// Antonio Giuliana, 2001-2003 ''// Costanti per l'individuazione della versione di OS Private Const VER_PLATFORM_WIN32S = 0 Private Const VER_PLATFORM_WIN32_WINDOWS = 1 Private Const VER_PLATFORM_WIN32_NT = 2 ''// Costanti per la comunicazione con il driver IDE Private Const DFP_RECEIVE_DRIVE_DATA = &amp;H7C088 ''// Costanti per la CreateFile Private Const FILE_SHARE_READ = &amp;H1 Private Const FILE_SHARE_WRITE = &amp;H2 Private Const GENERIC_READ = &amp;H80000000 Private Const GENERIC_WRITE = &amp;H40000000 Private Const OPEN_EXISTING = 3 Private Const CREATE_NEW = 1 ''// Enumerazione dei comandi per la CmnGetHDData Private Enum HDINFO HD_MODEL_NUMBER HD_SERIAL_NUMBER HD_FIRMWARE_REVISION End Enum ''// Struttura per l'individuazione della versione di OS Private Type OSVERSIONINFO dwOSVersionInfoSize As Long dwMajorVersion As Long dwMinorVersion As Long dwBuildNumber As Long dwPlatformId As Long szCSDVersion As String * 128 End Type ''// Struttura per il campo irDriveRegs della struttura SENDCMDINPARAMS Private Type IDEREGS bFeaturesReg As Byte bSectorCountReg As Byte bSectorNumberReg As Byte bCylLowReg As Byte bCylHighReg As Byte bDriveHeadReg As Byte bCommandReg As Byte bReserved As Byte End Type ''// Struttura per l'I/O dei comandi al driver IDE Private Type SENDCMDINPARAMS cBufferSize As Long irDriveRegs As IDEREGS bDriveNumber As Byte bReserved(1 To 3) As Byte dwReserved(1 To 4) As Long End Type ''// Struttura per il campo DStatus della struttura SENDCMDOUTPARAMS Private Type DRIVERSTATUS bDriveError As Byte bIDEStatus As Byte bReserved(1 To 2) As Byte dwReserved(1 To 2) As Long End Type ''// Struttura per l'I/O dei comandi al driver IDE Private Type SENDCMDOUTPARAMS cBufferSize As Long DStatus As DRIVERSTATUS ''// ovvero DriverStatus bBuffer(1 To 512) As Byte End Type ''// Per ottenere la versione del SO Private Declare Function GetVersionEx _ Lib &quot;kernel32&quot; Alias &quot;GetVersionExA&quot; _ (lpVersionInformation As OSVERSIONINFO) As Long ''// Per ottenere un handle al device IDE Private Declare Function CreateFile _ Lib &quot;kernel32&quot; Alias &quot;CreateFileA&quot; _ (ByVal lpFileName As String, _ ByVal dwDesiredAccess As Long, _ ByVal dwShareMode As Long, _ ByVal lpSecurityAttributes As Long, _ ByVal dwCreationDisposition As Long, _ ByVal dwFlagsAndAttributes As Long, _ ByVal hTemplateFile As Long) As Long ''// Per chiudere l'handle del device IDE Private Declare Function CloseHandle _ Lib &quot;kernel32&quot; _ (ByVal hObject As Long) As Long ''// Per comunicare con il driver IDE Private Declare Function DeviceIoControl _ Lib &quot;kernel32&quot; _ (ByVal hDevice As Long, _ ByVal dwIoControlCode As Long, _ lpInBuffer As Any, _ ByVal nInBufferSize As Long, _ lpOutBuffer As Any, _ ByVal nOutBufferSize As Long, _ lpBytesReturned As Long, _ ByVal lpOverlapped As Long) As Long ''// Per azzerare buffer di scambio dati Private Declare Sub ZeroMemory _ Lib &quot;kernel32&quot; Alias &quot;RtlZeroMemory&quot; _ (dest As Any, _ ByVal numBytes As Long) ''// Per copiare porzioni di memoria Private Declare Sub CopyMemory _ Lib &quot;kernel32&quot; Alias &quot;RtlMoveMemory&quot; _ (Destination As Any, _ Source As Any, _ ByVal Length As Long) Private Declare Function GetLastError _ Lib &quot;kernel32&quot; () As Long Private mvarCurrentDrive As Byte ''// Drive corrente Private mvarPlatform As String ''// Piattaforma usata Public Property Get Copyright() As String ''// Copyright Copyright = &quot;HDSN Vrs. 1.00, (C) Antonio Giuliana, 2001-2003&quot; End Property ''// Metodo GetModelNumber Public Function GetModelNumber() As String ''// Ottiene il ModelNumber GetModelNumber = CmnGetHDData(HD_MODEL_NUMBER) End Function ''// Metodo GetSerialNumber Public Function GetSerialNumber() As String ''// Ottiene il SerialNumber GetSerialNumber = CmnGetHDData(HD_SERIAL_NUMBER) End Function ''// Metodo GetFirmwareRevision Public Function GetFirmwareRevision() As String ''// Ottiene la FirmwareRevision GetFirmwareRevision = CmnGetHDData(HD_FIRMWARE_REVISION) End Function ''// Proprieta' CurrentDrive Public Property Let CurrentDrive(ByVal vData As Byte) ''// Controllo numero di drive fisico IDE If vData &lt; 0 Or vData &gt; 3 Then Err.Raise 10000, , &quot;Illegal drive number&quot; ''// IDE drive 0..3 End If ''// Nuovo drive da considerare mvarCurrentDrive = vData End Property ''// Proprieta' CurrentDrive Public Property Get CurrentDrive() As Byte ''// Restituisce drive fisico corrente (IDE 0..3) CurrentDrive = mvarCurrentDrive End Property ''// Proprieta' Platform Public Property Get Platform() As String ''// Restituisce tipo OS Platform = mvarPlatform End Property Private Sub Class_Initialize() ''// Individuazione del tipo di OS Dim OS As OSVERSIONINFO OS.dwOSVersionInfoSize = Len(OS) Call GetVersionEx(OS) mvarPlatform = &quot;Unk&quot; Select Case OS.dwPlatformId Case Is = VER_PLATFORM_WIN32S mvarPlatform = &quot;32S&quot; ''// Win32S Case Is = VER_PLATFORM_WIN32_WINDOWS If OS.dwMinorVersion = 0 Then mvarPlatform = &quot;W95&quot; ''// Win 95 Else mvarPlatform = &quot;W98&quot; ''// Win 98 End If Case Is = VER_PLATFORM_WIN32_NT mvarPlatform = &quot;WNT&quot; ''// Win NT/2000 End Select End Sub Private Function CmnGetHDData(hdi As HDINFO) As String ''// Rilevazione proprieta' IDE Dim bin As SENDCMDINPARAMS Dim bout As SENDCMDOUTPARAMS Dim hdh As Long Dim br As Long Dim ix As Long Dim hddfr As Long Dim hddln As Long Dim s As String Select Case hdi ''// Selezione tipo caratteristica richiesta Case HD_MODEL_NUMBER hddfr = 55 ''// Posizione nel buffer del ModelNumber hddln = 40 ''// Lunghezza nel buffer del ModelNumber Case HD_SERIAL_NUMBER hddfr = 21 ''// Posizione nel buffer del SerialNumber hddln = 20 ''// Lunghezza nel buffer del SerialNumber Case HD_FIRMWARE_REVISION hddfr = 47 ''// Posizione nel buffer del FirmwareRevision hddln = 8 ''// Lunghezza nel buffer del FirmwareRevision Case Else Err.Raise 10001, &quot;Illegal HD Data type&quot; End Select Select Case mvarPlatform Case &quot;WNT&quot; ''// Per Win NT/2000 apertura handle al drive fisico hdh = CreateFile(&quot;\\.\PhysicalDrive&quot; &amp; mvarCurrentDrive, _ GENERIC_READ + GENERIC_WRITE, FILE_SHARE_READ + FILE_SHARE_WRITE, _ 0, OPEN_EXISTING, 0, 0) Case &quot;W95&quot;, &quot;W98&quot; ''// Per Win 9X apertura handle al driver SMART ''// (in \WINDOWS\SYSTEM da spostare in \WINDOWS\SYSTEM\IOSUBSYS) ''// che comunica con il driver IDE hdh = CreateFile(&quot;\\.\Smartvsd&quot;, _ 0, 0, 0, CREATE_NEW, 0, 0) Case Else ''// Piattaforma non supportata (Win32S) Err.Raise 10002, , &quot;Illegal platform (only WNT, W98 or W95)&quot; End Select ''// Controllo validità handle If hdh = 0 Then Err.Raise 10003, , &quot;Error on CreateFile&quot; End If ''// Azzeramento strutture per l'I/O da driver ZeroMemory bin, Len(bin) ZeroMemory bout, Len(bout) ''// Preparazione parametri struttura di richiesta al driver With bin .bDriveNumber = mvarCurrentDrive .cBufferSize = 512 With .irDriveRegs If (mvarCurrentDrive And 1) Then .bDriveHeadReg = &amp;HB0 Else .bDriveHeadReg = &amp;HA0 End If .bCommandReg = &amp;HEC .bSectorCountReg = 1 .bSectorNumberReg = 1 End With End With ''// Richiesta al driver DeviceIoControl hdh, DFP_RECEIVE_DRIVE_DATA, _ bin, Len(bin), bout, Len(bout), br, 0 ''// Formazione stringa di risposta ''// da buffer di uscita ''// L'ordine dei byte e' invertito s = &quot;&quot; For ix = hddfr To hddfr + hddln - 1 Step 2 If bout.bBuffer(ix + 1) = 0 Then Exit For s = s &amp; Chr(bout.bBuffer(ix + 1)) If bout.bBuffer(ix) = 0 Then Exit For s = s &amp; Chr(bout.bBuffer(ix)) Next ix ''// Chiusura handle CloseHandle hdh ''// Restituzione informazione richiesta CmnGetHDData = Trim(s) End Function </code></pre>
<p>I found it! Here is the equivalent VB.NET code. It's not exactly the converted version of the VB6 code, but does the same thing. Enjoy!</p> <pre><code>Public Class HDDInfo #Region " Declatrations " Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Integer, ByVal dwShareMode As Integer, ByVal lpSecurityAttributes As Integer, ByVal dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer, ByVal hTemplateFile As Integer) As Integer &lt;System.Runtime.InteropServices.DllImport("kernel32.dll")&gt; _ Private Shared Function CloseHandle(ByVal hObject As Integer) As Integer End Function &lt;System.Runtime.InteropServices.DllImport("kernel32.dll")&gt; _ Private Shared Function DeviceIoControl(ByVal hDevice As Integer, ByVal dwIoControlCode As Integer, &lt;[In](), Out()&gt; ByVal lpInBuffer As SENDCMDINPARAMS, ByVal lpInBufferSize As Integer, &lt;[In](), Out()&gt; ByVal lpOutBuffer As SENDCMDOUTPARAMS, ByVal lpOutBufferSize As Integer, _ ByRef lpBytesReturned As Integer, ByVal lpOverlapped As Integer) As Integer End Function Private Const FILE_SHARE_READ As Short = &amp;H1 Private Const FILE_SHARE_WRITE As Short = &amp;H2 Private Const GENERIC_READ As Integer = &amp;H80000000 Private Const GENERIC_WRITE As Integer = &amp;H40000000 Private Const OPEN_EXISTING As Short = 3 Private Const CREATE_NEW As Short = 1 Private Const VER_PLATFORM_WIN32_NT As Integer = 2 Private Const DFP_RECEIVE_DRIVE_DATA As Integer = &amp;H7C088 Private Const INVALID_HANDLE_VALUE As Integer = -1 #End Region #Region " Classes " &lt;StructLayout(LayoutKind.Sequential, Size:=8)&gt; _ Private Class IDEREGS Public Features As Byte Public SectorCount As Byte Public SectorNumber As Byte Public CylinderLow As Byte Public CylinderHigh As Byte Public DriveHead As Byte Public Command As Byte Public Reserved As Byte End Class &lt;StructLayout(LayoutKind.Sequential, Size:=32)&gt; _ Private Class SENDCMDINPARAMS Public BufferSize As Integer Public DriveRegs As IDEREGS Public DriveNumber As Byte &lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=3)&gt; _ Public Reserved As Byte() &lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=4)&gt; _ Public Reserved2 As Integer() Public Sub New() DriveRegs = New IDEREGS() Reserved = New Byte(2) {} Reserved2 = New Integer(3) {} End Sub End Class &lt;StructLayout(LayoutKind.Sequential, Size:=12)&gt; _ Private Class DRIVERSTATUS Public DriveError As Byte Public IDEStatus As Byte &lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)&gt; _ Public Reserved As Byte() &lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)&gt; _ Public Reserved2 As Integer() Public Sub New() Reserved = New Byte(1) {} Reserved2 = New Integer(1) {} End Sub End Class &lt;StructLayout(LayoutKind.Sequential)&gt; _ Private Class IDSECTOR Public GenConfig As Short Public NumberCylinders As Short Public Reserved As Short Public NumberHeads As Short Public BytesPerTrack As Short Public BytesPerSector As Short Public SectorsPerTrack As Short &lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=3)&gt; _ Public VendorUnique As Short() &lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=20)&gt; _ Public SerialNumber As Char() Public BufferClass As Short Public BufferSize As Short Public ECCSize As Short &lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=8)&gt; _ Public FirmwareRevision As Char() &lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=40)&gt; _ Public ModelNumber As Char() Public MoreVendorUnique As Short Public DoubleWordIO As Short Public Capabilities As Short Public Reserved1 As Short Public PIOTiming As Short Public DMATiming As Short Public BS As Short Public NumberCurrentCyls As Short Public NumberCurrentHeads As Short Public NumberCurrentSectorsPerTrack As Short Public CurrentSectorCapacity As Integer Public MultipleSectorCapacity As Short Public MultipleSectorStuff As Short Public TotalAddressableSectors As Integer Public SingleWordDMA As Short Public MultiWordDMA As Short &lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=382)&gt; _ Public Reserved2 As Byte() End Class &lt;StructLayout(LayoutKind.Sequential)&gt; _ Private Class SENDCMDOUTPARAMS Public BufferSize As Integer Public Status As DRIVERSTATUS Public IDS As IDSECTOR Public Sub New() Status = New DRIVERSTATUS() IDS = New IDSECTOR() End Sub End Class #End Region #Region " Methods and Functions " Private Shared Function SwapChars(ByVal chars As Char()) As String For i As Integer = 0 To chars.Length - 2 Step 2 Dim t As Char t = chars(i) chars(i) = chars(i + 1) chars(i + 1) = t Next Dim s As New String(chars) Return s End Function Public Shared Function GetHDDInfoString() As String Dim serialNumber As String = " ", model As String = " ", firmware As String = " " Dim handle As Integer, returnSize As Integer = 0 Dim driveNumber As Integer = 0 Dim sci As New SENDCMDINPARAMS() Dim sco As New SENDCMDOUTPARAMS() If Environment.OSVersion.Platform = PlatformID.Win32NT Then handle = CreateFile("\\.\PhysicalDrive" &amp; "0", GENERIC_READ + GENERIC_WRITE, FILE_SHARE_READ + FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0) Else handle = CreateFile("\\.\Smartvsd", 0, 0, 0, CREATE_NEW, 0, 0) End If If handle &lt;&gt; INVALID_HANDLE_VALUE Then sci.DriveNumber = CByte(driveNumber) sci.BufferSize = Marshal.SizeOf(sco) sci.DriveRegs.DriveHead = CByte((&amp;HA0 Or driveNumber &lt;&lt; 4)) sci.DriveRegs.Command = &amp;HEC sci.DriveRegs.SectorCount = 1 sci.DriveRegs.SectorNumber = 1 If DeviceIoControl(handle, DFP_RECEIVE_DRIVE_DATA, sci, Marshal.SizeOf(sci), sco, Marshal.SizeOf(sco), _ returnSize, 0) &lt;&gt; 0 Then serialNumber = SwapChars(sco.IDS.SerialNumber) model = SwapChars(sco.IDS.ModelNumber) firmware = SwapChars(sco.IDS.FirmwareRevision) End If CloseHandle(handle) End If Return model.Trim &amp; " " &amp; serialNumber.Trim End Function #End Region End Class </code></pre>
<p>You can get this data of WMI. Let me get you an example</p>
35,103
<p>I want to put users into an instance of ADAM so that ADAM looks similar to a typical, real, Active Directory server.</p> <p>I'm developing an application that integrates with LDAP. I've tested with OpenLDAP and its core.schema. Now I'd like to test with with Active Directory, but the closest I can get to that using my equipment is by testing with Microsoft ADAM.</p> <p>I don't know exactly how to begin with ADAM. Zero experience with it and Active Directory. I'm guessing I need to import the MS-AdamSchemaW2K3.LDF because I see "sAMAccountName" in there, and I think I want that to be like Active Directory?</p> <hr> <p>Added after reading a couple answers...</p> <p>The answers so far aren't specific enough for what I'm looking for. I did get ADAM to work and my app can talk to it, but what I want to do is to have ADAM working the way a typical (if there is such a thing) Active Directory installation would work, same schema, authentication, even though I'm just using ADAM in a workgroup network, on Windows XP.</p>
<p>ADAM isn't really a complete replacement for Active Directory. For example, ADAM doesn't understand different group types, and doesn't include a RootDSE by default. You could test against ADAM but you may run into slight differences in your query structures.</p> <p>If you are developing an application that will depend on Active Directory then you really should be building your application against an Active Directory. I have been able to get several Domain Controllers running just fine in <a href="http://www.microsoft.com/downloads/details.aspx?familyid=04D26402-3199-48A3-AFA2-2DC0B40A73B6&amp;displaylang=en" rel="nofollow noreferrer">Virtual PC</a> (free) using only 300mb of memory and a <a href="http://www.microsoft.com/windowsserver2008/en/us/try-it.aspx" rel="nofollow noreferrer">free evaluation version of Windows Server</a>.</p> <p>If, however, you are building an application that simply needs an LDAP directory and isn't going to be using Active Directory than ADAM may work out just fine. The schema extension file you mentioned (MS-AdamSchemaW2K3.LDF) would work just fine but you would want to setup RootDSE for easier binds.</p> <p>Lastly, Microsoft AD/AM isn't really Admin friendly, especially in terms of troubleshooting. <a href="http://www.dscoduc.com/post/2008/01/ADAM-Services-Debug.aspx" rel="nofollow noreferrer">I ended up writing an application</a> to help troubleshoot AD/AM issues that you may find useful.</p>
<p>I am only aware of importing MS-Users file. I see ther is a step-step guide</p> <p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=5163b97a-7df3-4b41-954e-0f7c04893e83&amp;DisplayLang=en" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyID=5163b97a-7df3-4b41-954e-0f7c04893e83&amp;DisplayLang=en</a></p>
20,633
<p>I configured Marlin 1.1.3 for auto-leveling with a fix mounted sensor connected to the Z end-stop pin.</p> <p>I have the following settings in my config:</p> <pre><code>#define X_PROBE_OFFSET_FROM_EXTRUDER 25 #define Y_PROBE_OFFSET_FROM_EXTRUDER 20 #define Z_PROBE_OFFSET_FROM_EXTRUDER 0 // Z offset: -below +above [the nozzle] #define Z_CLEARANCE_DEPLOY_PROBE 10 // Z Clearance for Deploy/Stow #define Z_CLEARANCE_BETWEEN_PROBES 5 // Z Clearance between probe points #define AUTO_BED_LEVELING_BILINEAR #define GRID_MAX_POINTS_X 7 #define GRID_MAX_POINTS_Y GRID_MAX_POINTS_X // The Z probe minimum outer margin (to validate G29 parameters). #define MIN_PROBE_EDGE 10 // Set the boundaries for probing (where the probe can reach). #define LEFT_PROBE_BED_POSITION 25 #define RIGHT_PROBE_BED_POSITION 150 #define FRONT_PROBE_BED_POSITION 30 #define BACK_PROBE_BED_POSITION 180 </code></pre> <p>I enter <code>M111 S38</code> to enable LEVELING+INFO+ERROR debugging. Then I enter <code>G28</code> to home all axes and then enter <code>G29</code> to start auto-leveling.</p> <p>The auto-leveling starts successfully and after finishing I see the scan grid in console:</p> <pre><code>12:41:35.983 : Bilinear Leveling Grid: 12:41:35.983 : 0 1 2 3 4 5 6 12:41:35.983 : 0 -3.127 -3.405 -3.405 -3.292 -3.595 -3.487 -3.537 12:41:35.983 : 1 -3.110 -3.367 -3.337 -3.220 -3.470 -3.350 -3.365 12:41:35.983 : 2 -3.138 -3.367 -3.330 -3.215 -3.442 -3.345 -3.385 12:41:35.984 : 3 -3.013 -3.225 -3.182 -3.047 -3.225 -3.132 -3.150 12:41:35.984 : 4 -2.970 -3.165 -3.097 -2.972 -3.160 -3.045 -3.065 12:41:35.984 : 5 -2.875 -3.075 -3.005 -2.847 -2.990 -2.872 -2.875 12:41:35.984 : 6 -2.680 -2.845 -2.755 -2.615 -2.753 -2.617 -2.622 12:41:35.985 : G29 uncorrected Z:10.00 12:41:35.985 : corrected Z:12.85 12:41:35.985 : &lt;&lt;&lt; gcode_G29 12:41:35.985 : X:120.00 Y:160.00 Z:12.85 E:0.00 Count X:9600 Y:12800 Z:4000 12:41:35.985 : current_position=(120.00, 160.00, 12.85) : sync_plan_position </code></pre> <p>So the auto-leveling scanning seems to be successful.</p> <p>Here is a visual of the leveling grid (but upside down to make it easier to view):</p> <p><a href="https://i.stack.imgur.com/TOas7.jpg" rel="nofollow noreferrer" title="Inverted visual of the leveling grid"><img src="https://i.stack.imgur.com/TOas7.jpg" alt="Inverted visual of the leveling grid" title="Inverted visual of the leveling grid"></a></p> <p>Naturally I <strong>DO NOT</strong> enter <code>G28</code> after the scanning. </p> <p>I enter <code>G0 Z1</code> to down nozzle almost to table. But when I enter for example <code>G0 X25 Y30</code> and look at level and then I enter <code>G0 X150 Y150</code> I see the big difference between nozzle levels relatively to table. So it seems that height compensation does not work. I expect that Z axis would lift up or down depending on auto-leveling results but Z motor do not work when I move X/Y. </p> <p>By the way I tried 3 point autoleveling. It was pretty rough but Z axis corrected it's level when I moved axes using <code>G0</code> commands. And to avoid questions "why my table is inclined so much?" I deliberately inclined the table to be sure that auto leveling works. By the way, I tried different <code>Z_PROBE_OFFSET_FROM_EXTRUDER</code> so the current 0 setting is not actual but situation is the same with any value of this option.</p> <p>What I am doing wrong?</p>
<p>Yes, with the proper equipment.</p> <p>Printing wax filament (at 51 seconds): <a href="https://youtu.be/tibkVZB_n9c?t=51s" rel="noreferrer">https://youtu.be/tibkVZB_n9c?t=51s</a></p> <p>There are also options for melting wax, filling a heated reservoir head, and printing with that. I recommend doing this with a cold ambient temperature, so that the wax solidifies quickly. There's no point in just printing a puddle. :)</p>
<p>Just make a silicone mold of any of your prints and pour you wax in the silicone,you silicone putty is pretty cheap so is wax ,no need to break the bank as printers have become less expensive and can do a pretty good job </p>
630
<p>I want to check out all files in all subdirectories of a specified folder.</p> <p>(And it is painful to do this using the GUI, because there is no recursive checkout option).</p>
<p>Beware: ClearCase is File-centric, not repository centric (like SVN or CVS).</p> <p>That means it is rarely a good solution to checkout all files (and it can be fairly long with ClearCase ;) )</p> <p>That being said, the question is perfectly legitimate and I would like to point out another way:</p> <p>open a <code>cleartool</code> session in the 'specified folder':</p> <pre><code>c:\MyFolder&gt; cleartool cleartool&gt; co -c "Reason for massive checkout" .../* </code></pre> <p>does the trick too. But as the aku's answer, it does checkout <em>everything</em>: files and directories... and you may most <em>not need</em> to checkout directories! </p> <pre><code>cleartool find somedir -type f -exec "cleartool checkout -c \"Reason for massive checkout\" \"%CLEARCASE_PN%\"" </code></pre> <p>would only checkout files...</p> <p>Now the problem is to checkin everything that has changed. It is problematic since often <em>not everything</em> has changed, and CleaCase will trigger an error message when trying to check in an identical file. Meaning you will need 2 commands:</p> <pre><code>ct lsco -r -cvi -fmt "ci -nc \"%n\"\n" | ct ct lsco -r -cvi -fmt "unco -rm %n\n" | ct </code></pre> <p>(with '<code>ct</code> being '<code>cleartool</code>' : type '<code>doskey ct=cleartool $*</code>' on Windows to set that alias)</p> <p>Note that <code>ct ci -nc</code> will check-in with the comment used for the checkout stage.<br> So it is <em>not</em> a checkin without a comment (like the <code>-nc</code> option -- or "no comment" -- could make believe).</p>
<pre><code>cleartool find somedir -exec "cleartool checkout -nc \"%CLEARCASE_PN%\"" </code></pre> <p>Also an article "<a href="http://www.ibm.com/developerworks/rational/library/4687.html" rel="noreferrer">ClearCase: The ten best scripts</a>" might be helpful</p>
5,366
<p>I'm looking for an algorithm that places tick marks on an axis, given a range to display, a width to display it in, and a function to measure a string width for a tick mark.</p> <p>For example, given that I need to display between 1e-6 and 5e-6 and a width to display in pixels, the algorithm would determine that I should put tickmarks (for example) at 1e-6, 2e-6, 3e-6, 4e-6, and 5e-6. Given a smaller width, it might decide that the optimal placement is only at the even positions, i.e. 2e-6 and 4e-6 (since putting more tickmarks would cause them to overlap).</p> <p>A smart algorithm would give preference to tickmarks at multiples of 10, 5, and 2. Also, a smart algorithm would be symmetric around zero.</p>
<p>As I didn't like any of the solutions I've found so far, I implemented my own. It's in C# but it can be easily translated into any other language.</p> <p>It basically chooses from a list of possible steps the smallest one that displays all values, <strong>without leaving any value exactly in the edge</strong>, lets you easily select which possible steps you want to use (without having to edit ugly <code>if-else if</code> blocks), and supports any range of values. I used a C# <code>Tuple</code> to return three values just for a quick and simple demonstration.</p> <pre><code>private static Tuple&lt;decimal, decimal, decimal&gt; GetScaleDetails(decimal min, decimal max) { // Minimal increment to avoid round extreme values to be on the edge of the chart decimal epsilon = (max - min) / 1e6m; max += epsilon; min -= epsilon; decimal range = max - min; // Target number of values to be displayed on the Y axis (it may be less) int stepCount = 20; // First approximation decimal roughStep = range / (stepCount - 1); // Set best step for the range decimal[] goodNormalizedSteps = { 1, 1.5m, 2, 2.5m, 5, 7.5m, 10 }; // keep the 10 at the end // Or use these if you prefer: { 1, 2, 5, 10 }; // Normalize rough step to find the normalized one that fits best decimal stepPower = (decimal)Math.Pow(10, -Math.Floor(Math.Log10((double)Math.Abs(roughStep)))); var normalizedStep = roughStep * stepPower; var goodNormalizedStep = goodNormalizedSteps.First(n =&gt; n &gt;= normalizedStep); decimal step = goodNormalizedStep / stepPower; // Determine the scale limits based on the chosen step. decimal scaleMax = Math.Ceiling(max / step) * step; decimal scaleMin = Math.Floor(min / step) * step; return new Tuple&lt;decimal, decimal, decimal&gt;(scaleMin, scaleMax, step); } static void Main() { // Dummy code to show a usage example. var minimumValue = data.Min(); var maximumValue = data.Max(); var results = GetScaleDetails(minimumValue, maximumValue); chart.YAxis.MinValue = results.Item1; chart.YAxis.MaxValue = results.Item2; chart.YAxis.Step = results.Item3; } </code></pre>
<p>I've been using the jQuery <a href="https://github.com/flot/flot/blob/master/API.md" rel="nofollow noreferrer">flot</a> graph library. It's open source and does axis/tick generation quite well. I'd suggest looking at it's code and pinching some ideas from there.</p>
29,357
<p>Is there a <code>SQL</code> or <code>PHP</code> script that I can run that will change the default collation in all tables and fields in a database?</p> <p>I can write one myself, but I think that this should be something that readily available at a site like this. If I can come up with one myself before somebody posts one, I will post it myself.</p>
<p>Be careful! If you actually have utf stored as another encoding, you could have a real mess on your hands. Back up first. Then try some of the standard methods:</p> <p>for instance <a href="http://www.cesspit.net/drupal/node/898" rel="noreferrer">http://www.cesspit.net/drupal/node/898</a> <a href="http://www.hackszine.com/blog/archive/2007/05/mysql_database_migration_latin.html" rel="noreferrer">http://www.hackszine.com/blog/archive/2007/05/mysql_database_migration_latin.html</a></p> <p>I've had to resort to converting all text fields to binary, then back to varchar/text. This has saved my ass. </p> <p>I had data is UTF8, stored as latin1. What I did:</p> <p>Drop indexes. Convert fields to binary. Convert to utf8-general ci</p> <p>If your on LAMP, don’t forget to add set NAMES command before interacting with the db, and make sure you set character encoding headers. </p>
<p>Use my custom shell <a href="https://github.com/abdennour/miscs.sh/blob/master/collatedb" rel="nofollow">collatedb</a>, it should work : </p> <pre><code>collatedb &lt;username&gt; &lt;password&gt; &lt;database&gt; &lt;collation&gt; </code></pre> <p>Example :</p> <pre><code>collatedb root 0000 myDatabase utf8_bin </code></pre>
13,105
<p>I have a Canvas where I'm drawing a bunch of shapes and other UI elements. This canvas can be very large so I want to put this in a panel which allows me to zoom in/out using the mouse and scroll by dragging the mouse, just like Google Maps. The closest thing I could find was the ScrollViewer but obviously this isn't close enough.</p> <p>Has anyone done this in WPF and have any XAML and/or C# code?</p>
<p>Would this link be of any help? I havent gotten into WPF but a quick search yields this link and hopefully it helps you out:</p> <p><a href="http://blogs.vertigo.com/personal/swarren/Blog/Lists/Posts/Post.aspx?ID=7" rel="nofollow noreferrer">http://blogs.vertigo.com/personal/swarren/Blog/Lists/Posts/Post.aspx?ID=7</a></p>
<p>if I remember correctly here you can find something like you want.</p> <p><a href="http://www.codeproject.com/KB/vista/swordfishcharts.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/vista/swordfishcharts.aspx</a></p>
16,295
<p>In a web application, if it doesn't have a domain name (like a web service for example), can you still add a SSL certificate to a IP address?</p> <p>If yes, how?</p>
<p>You can easily put an ip address into the CN (common name) of an ssl certificate by the same procedure you would use for an ordinary hostname (ssl certificates contain hostnames, not domain names).</p> <p>How this is done precisely in your case cannot be answered, since you have not stated what your case is.</p> <p>Browsers should match the CN of a certificate against what the user has put into the URL bar. If it's an ip address, it's an ip address.</p>
<p>There's some good information here: <a href="https://www.thawte.com/ssl-digital-certificates/technical-support/browserfaqs.html" rel="nofollow noreferrer">https://www.thawte.com/ssl-digital-certificates/technical-support/browserfaqs.html</a></p> <p>I'm almost certain you need a domain to go with the SSL.</p>
39,942
<p>I am looking to use quartz to schedule emails, but I'm not sure which approach to take:</p> <ol> <li>Create a new job and trigger whenever an email is scheduled OR</li> <li>Create a single job, and create a new trigger each time an email is scheduled</li> </ol> <p>I need to pass the message/recipient etc either way, and I'm not sure whether creating heaps of jobs will start adding considerable memory overheads, as there will quite possibly be thousands of emails scheduled.</p> <p><strong>Update</strong>: These emails will be scheduled by users, not by me - so I will be adding these programmatically at runtime, they aren't scheduled to go out at any particular time.</p>
<p>Quartz is intended to handle tens of thousands of triggers. The main limit to scalability here is the space available in your JobStore. A JDBCJobStore backed with a reasonable database should be able to handle hundreds of thousands of triggers.</p> <p>If a single job can be parameterized through the trigger's job data map, create a single job and one trigger for each email. Quartz polls the job store periodically to look for triggers that are ready to fire. Quartz is designed to safely handle arbitrarily large result sets from this query.</p> <p>What matters&mdash;and this really has nothing to do Quartz itself&mdash;is that you have the necessary bandwidth to execute peak loads. If users tend to schedule mails in clumps, you need to make sure that you have the computing resources to get the emails out. This would include network bandwidth, processing, and enough worker threads configured to utilize the available resources.</p> <p>Note that you can configure what Quartz should do with a trigger if it does get too far behind in executing jobs. You can keep trying, skip the trigger, etc.</p>
<p>You might consider queuing or otherwise grouping a set of emails and have a single, or maybe a few, periodic (or scheduled) job(s) that then takes care of the 'batch'.</p> <p>You could even have the Quartz job queue the emails for a collection of workers to consume and send.</p> <p>I would not recommend thousands of Quartz jobs/triggers - it just isn't the intended use of the tool (IMHO).</p> <hr> <p>EDIT: In response to the comment below:</p> <p>I would not recommend thousands of Quartz jobs/triggers when used as part of a framework executing an application in the same JVM, The jobs/triggers will be competing for resources with the rest of the application.</p>
33,084
<p>It looks like I had a fundamental misunderstanding about C++ :&lt;</p> <p>I like the polymorphic container solution. Thank you SO, for bringing that to my attention :)</p> <hr> <p>So, we have a need to create a relatively generic container type object. It also happens to encapsulate some business related logic. However, we need to store essentially arbitrary data in this container - everything from primitive data types to complex classes.</p> <p>Thus, one would immediately jump to the idea of a template class and be done with it. However, I have noticed C++ polymorphism and templates do not play well together. Being that there is some complex logic that we are going to have to work, I would rather just stick with either templates OR polymorphism, and not try to fight C++ by making it do both.</p> <p>Finally, given that I want to do one or the other, I would prefer polymorphism. I find it much easier to represent constraints like "this container contains Comparable types" - a la java.</p> <p>Bringing me to the topic of question: At the most abstract, I imagine that I could have a "Container" pure virtual interface that has something akin to "push(void* data) and pop(void* data)" (for the record, I am not actually trying to implement a stack).</p> <p>However, I don't really like void* at the top level, not to mention the signature is going to change every time I want to add a constraint to the type of data a concrete container can work with.</p> <p>Summarizing: We have relatively complex containers that have various ways to retrieve elements. We want to be able to vary the constraints on the elements that can go into the containers. Elements should work with multiple kinds of containers (so long as they meet the constraints of that particular container).</p> <p>Edit: I should also mention that the containers themselves need to be polymorphic. That is my primary reason for not wanting to use templated C++.</p> <p>So - should I drop my love for Java type interfaces and go with templates? Should I use void* and statically cast everything? Or should I go with an empty class definition "Element" that declares nothing and use that as my top level class in the "Element" hierarchy?</p> <p>One of the reasons why I love stack overflow is that many of the responses provide some interesting insight on other approaches that I hadn't not have even considered. So thank you in advance for your insights and comments.</p>
<p>You can look at using a standard container of <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/any.html" rel="noreferrer">boost::any</a> if you are storing truly arbitrary data into the container.</p> <p>It sounds more like you would rather have something like a <a href="http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/ptr_container.html" rel="noreferrer">boost::ptr_container</a> where anything that <em>can</em> be stored in the container has to derive from some base type, and the container itself can only give you reference's to the base type.</p>
<p>You could not have to give up Java-like interfaces and use templates as well. <a href="https://stackoverflow.com/questions/168408/c-alternatives-to-void-pointers-that-isnt-templates#168509" title="Josh&#39;s suggestion">Josh's suggestion</a> of a generic base template Container would certainly allow you do polymorphically pass Containers and their children around, but additionally you could certainly implement interfaces as abstract classes to be the contained items. There's no reason you couldn't create an abstract IComparable class as you suggested, such that you could have a polymorphic function as follows:</p> <pre><code>class Whatever { void MyPolymorphicMethod(Container&lt;IComparable*&gt; &amp;listOfComparables); } </code></pre> <p>This method can now take any child of Container that contains any class implementing IComparable, so it would be extremely flexible.</p>
20,331
<p>Is it possible to convert a <code>com.vividsolutions.jts.geom.Geometry</code> (or a subclass of it) into a class that implements <code>java.awt.Shape</code>? Which library or method can I use to achieve that goal?</p>
<p>According to:</p> <p><a href="http://lists.jump-project.org/pipermail/jts-devel/2007-May/001954.html" rel="nofollow noreferrer">http://lists.jump-project.org/pipermail/jts-devel/2007-May/001954.html</a></p> <p>There's a class:</p> <pre><code>com.vividsolutions.jump.workbench.ui.renderer.java2D.Java2DConverter </code></pre> <p>which can do it?</p>
<p>According to:</p> <p><a href="http://lists.jump-project.org/pipermail/jts-devel/2007-May/001954.html" rel="nofollow noreferrer">http://lists.jump-project.org/pipermail/jts-devel/2007-May/001954.html</a></p> <p>There's a class:</p> <pre><code>com.vividsolutions.jump.workbench.ui.renderer.java2D.Java2DConverter </code></pre> <p>which can do it?</p>
15,786
<p>When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?</p>
<p>In addition to using server side compression, using intelligent coding is the best way to keep bandwidth costs low. You can always use tools like <a href="http://dean.edwards.name/download/#packer" rel="nofollow noreferrer">Dean Edward's Javascript Packer</a>, but for CSS, take the time to learn <a href="http://www.webcredible.co.uk/user-friendly-resources/css/css-shorthand-properties.shtml" rel="nofollow noreferrer" title="CSS Shorthand Examples">CSS Shorthand</a>. E.g. use:</p> <pre class="lang-css prettyprint-override"><code>background: #fff url(image.gif) no-repeat top left; </code></pre> <p>...instead of:</p> <pre class="lang-css prettyprint-override"><code>background-color: #fff; background-image: url(image.gif); background-repeat: no-repeat; background-position: top left; </code></pre> <p>Also, use the cascading nature of CSS. For example, if you know that your site will use one font-family, define that for all elements that are in the body tag like this:</p> <pre class="lang-css prettyprint-override"><code>body{font-family:arial;} </code></pre> <p>One other thing that can help is including your CSS and JavaScript as files instead of inline or at the head of each page. That way your server only has to serve them once to the browser after that browser will go from cache.</p> <h3>Including Javascript</h3> <pre><code>&lt;script type="text/javascript" src="/scripts/loginChecker.js"&gt;&lt;/script&gt; </code></pre> <h3>Including CSS</h3> <pre><code>&lt;link rel="stylesheet" href="/css/myStyle.css" type="text/css" media="All" /&gt; </code></pre>
<p>I'd give a test-drive to the new runtime optimizers in ASP.Net published on <a href="http://www.codeplex.com/NCOptimizer" rel="nofollow noreferrer">http://www.codeplex.com/NCOptimizer</a></p>
9,123
<p>Looking to get a list of all the files (commit comments would be nice too) of a user in cvs. </p>
<pre><code>cvs log -t -wJellyJoe </code></pre>
<p>You could also use external tools, such as <a href="http://www.viewvc.org/" rel="nofollow noreferrer">ViewVC</a>, which lets you input queries using web forms. The output is also formatted nicely in the web browser.</p>
46,194
<p>How do I learn PLC programming? Would it differ greatly for different brands of PLCs? Is ladder programming the same as PLC programming?</p>
<p>I did a lot of PLC programming, and now do quite a bit of .NET programming. It's very dangerous to make the switch either way, because a lot of the skills that you think should be transferrable (patterns and such) lead you very far astray.</p> <p>The biggest difference that I tell people is that PC program code should be written as if other programmers are the audience, but PLC programs (ladder logic) must be written as if maintenance people are the audience. Maintainance in most facilities (particularly manufacturing) frequently connect directly to PLCs and in online mode they can watch the code execute graphically to figure out what's wrong. </p> <p>For instance, if an output isn't turning on, they'll type the output electrical device ID into the find function of the programming software, find that output coil, and start tracing back from there looking for issues. One of the frequent mistakes that some PLC programmers make is to "map" their I/O into a structure (in PLCs, these are called user-defined types), and they use a copy instruction to move all the inputs or outputs over to the structure at once. Makes sense from a PC programming perspective, but it makes the maintenance person want to kill you. Typically the programming software provides a cross reference feature where they can specify that output coil, and it will tell them everywhere in the program that it's used. If you use a copy instruction to move 10 words of I/O into a 10 word data structure, he's got to sit there and count bits to figure out which bit in the source of the copy maps to which bit on the destination side of the copy. True, comments can help, but there's a problem with that too... PLCs store the whole program and allow you to upload the program from it in an emergency if you need to troubleshoot and you don't have a copy of the original program. The problem is that for space reasons, the PLC doesn't store the comments. So if the line is down, it's costing $5000 per minute in downtime, and a guy runs out there with a laptop, he might have to do a quick upload without comments and try to troubleshoot it. Having those copy instructions in there, wasting 10 minutes of his time, just cost the company $50,000 in downtime. These are the things you have to be aware of when writing PLC programs.</p> <p>Some other tips: some PLCs have support for FOR loops. <strong>Never</strong> use them. For the same reason above, they make the code very difficult to troubleshoot for a maintenance person. This is because if you have one piece of code in the PLC that gets scanned more than once per scan (like the contents of a loop), then when you go into online debugging mode, the software can't show you the values for each of 10 loops that executed this scan, so you really have no idea what value you're looking at. Then you have to write all this tricky code to pull the loop values for a specific loop index out into some other tags (variables) that you can monitor. That's just one more impedance to fixing the problem in an emergency. Using a subroutine more than once per scan suffers from the same problem.</p> <p>Indirect addressing (what we would call Arrays) are very difficult for maintenance people to understand. It's generally OK to use them when you're dealing with recipe management (storing and retrieving values for how to build your part) but you should try to stay away from it in the control part of the program.</p> <p>In PC programming, of course we seek to re-use code as much as possible. However, in PLCs and control systems, downtime is extremely expensive, and hardware is expensive. Memory is cheap, and actually PLC programmers are cheap. Therefore, it's expected that if you have 10 identical things on your machine (like conveyor drives or something) that you will have 10 different files (subroutines), one for each drive, and each drive will have its own variables associated with them: e.g. Drive1_Run, Drive2_Run, Drive3_Run, etc. This is going to feel very "wrong" to you when you come from a PC programming background, but this is all because of the points I've made above. When you're in a downtime situation, and someone says that Drive 3 isn't working, you crack open the laptop, go to the file for Drive 3 and you look at the Run output rung. You start troubleshooting from there, while the program is executing. There's no breakpoints (the program never stops).</p> <p>Good luck on your endeavors. I wrote up some more <a href="http://www.contactandcoil.com/" rel="noreferrer">insights from my years of programming PLCs</a>, if you want to check them out.</p>
<p>PLC is the term used for the devices that use ladder logic. The devices that are programmed in more typical programming languages are generally called microcontrollers. However, there are some of us that on occasion lump them all under the PLC name. :-) Not sure how much ladder logic varies, but microcontroller code can vary significantly.</p>
39,937
<p>Why do Linux distros have different package managers?</p> <p>I find this very strange because other software such as text editors, desktop environments and graphics software (Inkscape, Blender, GIMP) are shared among distributions. Why not have a common setup tool?</p>
<p>Like most things in the UNIX world where there are duplications of behaviour, it's a combination of many things, but mostly history, politics/religion, and the desire to build a better mousetrap / NiH syndrome. The existence of multiple system compononents that perform equivalent tasks is often praised as a useful feature, by open source proponents.</p> <p>Broadly speaking you mostly need to worry about four flavours of package management system. You have the debian derived systems, like debian, ubuntu which use <code>.deb</code> and the <strong>apt/dpkg</strong> family of management tools. You have the redhat derived systems which use the <code>.rpm</code> format and the <strong>rpm / yum</strong> family of management tools. Feature wise these both are broadly equivalent, in my opinion. </p> <p>The important thing is try and learn the toolset you're working with well, they're all well documented. Learn about how to check dependencies and verify package signatures and integrity, and find out what services a package provides, and conversely what package is responsible for a particular installed file or program, using the native package tools for your distribution of choice. Ideally learn the command line options to do this for yum and rpm and then dpkg and aptitude and you'll have most bases covered. Then use the GUI tools if you prefer.</p> <p>I think the most important thing to remember is that it's generally a mistake to mix packages from different distributions or releases in the same system even if they use the same package format e.g. do not install debian .deb files on your ubuntu system, or SuSE rpm files on your Fedora system, unless you really understand what you're doing.</p> <p>The other two flavours I mentioned are less mainstream, but I list them for completeness sake. These are </p> <ul> <li><p>a) no package system outside of binary/source tarball <em>a la</em> classic slackware , and </p></li> <li><p>b) source build tools modelled after BSD ports, <em>a la</em> classic gentoo.</p></li> </ul> <p>Again, you don't want to be here, until you understand <strong>why</strong> you might want to, in my opinion.</p>
<p>There are also many different text-editors, desktop-environments and so on. The different distributions share this only, because they provide all these programs.</p> <p>But they have to decide for one package-manager. Different package-manager wouldn't know about software installed by another package-manager. So distributions decide for one or develop one themself, tailored to their specific needs.</p> <p>Two very common package managers are RPM and apt, that are both used by different distributions.</p>
35,127
<p>I'm trying to use cygwin as a build environment under Windows. I have some dependencies on 3rd party packages, for example, GTK+. </p> <p>Normally when I build under Linux, in my Makefile I can add a call to pkg-config as an argument to gcc, so it comes out like so:</p> <pre> gcc example.c `pkg-config --libs --cflags gtk+-2.0` </pre> <p>This works fine under Linux, but in cygwin I get:</p> <pre> :Invalid argument make: *** [example] Error 1 </pre> <p>Right now, I am just manually running pkg-config and pasting the output into the Makefile, which is truly terrible. Is there a good way to workaround or fix for this issue?</p> <p>Make isn't the culprit. I can copy and paste the command line that make uses to call gcc, and that by itself will run gcc, which halts with ": Invalid argument". </p> <p>I wrote a small test program to print out command line arguments:</p> <pre><code>for (i = 0; i &lt; argc; i++) printf("'%s'\n", argv[i]); </code></pre> <p>Notice the single quotes.</p> <pre> $ pkg-config --libs gtk+-2.0 -Lc:/mingw/lib -lgtk-win32-2.0 -lgdk-win32-2.0 -latk-1.0 -lgdk_pixbuf-2.0 -lpang owin32-1.0 -lgdi32 -lpangocairo-1.0 -lpango-1.0 -lcairo -lgobject-2.0 -lgmodule- 2.0 -lglib-2.0 -lintl </pre> <p>Running through the test program:</p> <pre> $ ./t `pkg-config --libs gtk+-2.0` 'C:\cygwin\home\smo\pvm\src\t.exe' '-Lc:/mingw/lib' '-lgtk-win32-2.0' '-lgdk-win32-2.0' '-latk-1.0' '-lgdk_pixbuf-2.0' '-lpangowin32-1.0' '-lgdi32' '-lpangocairo-1.0' '-lpango-1.0' '-lcairo' '-lgobject-2.0' '-lgmodule-2.0' '-lglib-2.0' '-lintl' ' </pre> <p>Notice the one single quote on the last line. It looks like argc is one greater than it should be, and argv[argc - 1] is null. Running the same test on Linux does not have this result.</p> <p>That said, is there, say, some way I could have the Makefile store the result of pkg-config into a variable, and then use that variable, rather than using the back-tick operator?</p>
<blockquote> <p>That said, is there, say, some way I could have the Makefile store the result of pkg-config into a variable, and then use that variable, rather than using the back-tick operator?</p> </blockquote> <p>GTK_LIBS = $(shell pkg-config --libs gtk+-2.0)</p>
<p>My guess would be that cygwin's gcc can't handle -Lc:/mingw/lib. Try translating that to a cygwin path.</p> <pre><code>GTK_LIBS = $(patsubst -Lc:/%,-L/cygdrive/c/%,$(shell pkg-config --libs gtk+-2.0)) </code></pre>
12,724
<p>How can I create 7-Zip archives from my C# console application? I need to be able to extract the archives using the regular, widely available <a href="http://www.7-zip.org/" rel="noreferrer">7-Zip</a> program.</p> <hr> <h2>Here are my results with the examples provided as answers to this question</h2> <ul> <li>"Shelling out" to 7z.exe - this is the simplest and most effective approach, and I can confirm that <strong>it works nicely</strong>. As <a href="https://stackoverflow.com/questions/222030/how-do-i-create-7-zip-archives-with-net#222047">workmad3 mentions</a>, I just need to guarantee that 7z.exe is installed on all target machines, which is something I can guarantee.</li> <li><a href="http://www.eggheadcafe.com/tutorials/aspnet/064b41e4-60bc-4d35-9136-368603bcc27a/7zip-lzma-inmemory-com.aspx" rel="noreferrer">7Zip in memory compression</a> - this refers to compressing cookies "in-memory" before sending to the client; this method seems somewhat promising. The wrapper methods (wrapping the <a href="http://www.7-zip.org/sdk.html" rel="noreferrer">LZMA SDK</a>) return type <code>byte[]</code>. When I write the <code>byte[]</code> array to a file, I can't extract it using 7-Zip (<code>File.7z is not supported archive</code>).</li> <li><a href="http://www.codeplex.com/7zsharp" rel="noreferrer">7zSharp</a> Wrapper (found on CodePlex) - this wraps the 7z exe/<a href="http://www.7-zip.org/sdk.html" rel="noreferrer">LZMA SDK</a>. I referenced the project from my app, and it successfully created some archive files, but I was unable to extract the files using the regular 7-Zip program (<code>File.7z is not supported archive</code>).</li> <li><a href="http://www.7-zip.org/sdk.html" rel="noreferrer">7Zip SDK aka LZMA SDK</a> - I guess I'm not smart enough to figure out how to use this (which is why I posted here)... Any working code examples that demonstrate creating a 7zip archive that is able to be extracted by the regular 7zip program?</li> <li><a href="http://www.codeproject.com/KB/DLL/cs_interface_7zip.aspx" rel="noreferrer">CodeProject C# (.NET) Interface for 7-Zip Archive DLLs</a> - only supports extracting from 7zip archives... I need to create them!</li> <li><a href="http://sharpdevelop.net/OpenSource/SharpZipLib/Default.aspx" rel="noreferrer">SharpZipLib</a> - According to their <a href="http://wiki.sharpdevelop.net/SharpZipLib_FAQ.ashx" rel="noreferrer">FAQ</a>, SharpZipLib doesn't support 7zip.</li> </ul>
<p><a href="http://www.eggheadcafe.com/tutorials/aspnet/064b41e4-60bc-4d35-9136-368603bcc27a/7zip-lzma-inmemory-com.aspx" rel="noreferrer">EggCafe 7Zip cookie example</a> This is an example (zipping cookie) with the DLL of 7Zip.</p> <p><a href="http://www.codeplex.com/7zsharp" rel="noreferrer">CodePlex Wrapper</a> This is an open source project that warp zipping function of 7z.</p> <p><a href="http://www.7-zip.org/sdk.html" rel="noreferrer">7Zip SDK</a> The official SDK for 7zip (C, C++, C#, Java) &lt;---My suggestion</p> <p>.Net zip library by <a href="http://sharpdevelop.net/OpenSource/SharpzipLib/" rel="noreferrer">SharpDevelop.net</a></p> <p><a href="http://www.codeproject.com/KB/DLL/cs_interface_7zip.aspx" rel="noreferrer">CodeProject</a> example with 7zip</p> <p><a href="http://community.sharpdevelop.net/blogs/johnreilly/default.aspx" rel="noreferrer">SharpZipLib</a> Many zipping</p>
<p>These easiest way is to work with .zip files instead of .7z and use <a href="http://dotnetzip.codeplex.com/" rel="nofollow">Dot Net Zip</a></p> <p>When spinning off 7zip commands to shell there are other issues like user privileges, I had issue with SevenZipSharp.</p> <pre><code>Private Function CompressFile(filename As String) As Boolean Using zip As New ZipFile() zip.AddFile(filename &amp; ".txt", "") zip.Save(filename &amp; ".zip") End Using Return File.Exists(filename &amp; ".zip") End Function </code></pre>
27,384
<p>In Reporting Services I would like to add a parameter that contains data from a custom code block. Ideally, I would be able to run the following code (this is a simple testing example):</p> <pre><code>Function GetPeriods() As String() Dim values As System.Collections.ArrayList = New System.Collections.ArrayList() For i as integer = 1 to 24 values.Add(i) Next Return values.ToArray() End Function </code></pre> <p>and put the following in the "Text Field" of the parameter:</p> <pre><code>=Code.GetPeriods() </code></pre> <p>However, when I run the report, the parameter I apply this to is disabled and empty. Is there a different technique that should be used? Or am I doing something wrong?</p>
<p>If you're using SQL 2008 Reporting Services then you can have a look at <a href="http://msdn.microsoft.com/en-au/library/ms153561.aspx" rel="nofollow noreferrer">this page</a> which introduces the concept of using custom assemblies.</p> <p>If you're using SQL 2005 Reporting Services then <a href="http://msdn.microsoft.com/en-au/library/ms153561(SQL.90).aspx" rel="nofollow noreferrer">this link</a> is the one you want.</p> <p>It's a mostly trivial thing, simply compile your code into a class library and follow the instructions provided to allow your report to reference it.</p>
<p>Everything I've seen requires parameters and their respective settings to be part of the RDL. </p> <p>That being said, if you're going to "hardcode" the values, you could create a dataset just for the report, perhaps in XML, or if it needs to be programmatically driven, do it in a web service.</p>
33,985
<p>I'm trying to get a Server application to expose some status information using WCF. In particular I'm after using WCF services with RESTful "API". I'm hitting somewhat of a wall when it comes to consuming the REST api from a silverlight app/page that I want to have as an additional type of client...</p> <p>So far I've been successful in defining a status interface:</p> <pre><code>public static class StatusUriTemplates { public const string Status = "/current-status"; public const string StatusJson = "/current-status/json"; public const string StatusXml = "/current-status/xml"; } [ServiceContract] public interface IStatusService { [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = StatusUriTemplates.StatusJson)] StatusResultSet GetProgressAsJson(); [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = StatusUriTemplates.StatusXml)] StatusResultSet GetProgressAsXml(); [OperationContract] [WebGet(UriTemplate = StatusUriTemplates.Status)] StatusResultSet GetProgress(); } </code></pre> <p>Implementing it in the server:</p> <pre><code> [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] public class ServerStatusService : IStatusService { public StatusResultSet GetProgressAsJson() { return GetProgress(); } public StatusResultSet GetProgressAsXml() { return GetProgress(); } public StatusResultSet GetProgress() { return StatusResultSet.Empty; } } </code></pre> <p>Exposing it from my code at runtime:</p> <pre><code> var service = new ServerStatusService(); var binding = new WebHttpBinding(); var behavior = new WebHttpBehavior(); var host = new WebServiceHost(service, new Uri("http://localhost:8000/server")); host.AddServiceEndpoint(typeof(IStatusService), binding, "status"); host.Open(); </code></pre> <p>I've even been successful with consuming the service from a .NET console/winfoems/WPF application using something along the line of this:</p> <pre><code> var cf = new WebChannelFactory&lt;IStatusService&gt;(new Uri("http://localhost:8000/server/status")); var ss = cf.CreateChannel(); Console.WriteLine(ss.GetProgress().TimeStamp); </code></pre> <p>The "wall" I'm hitting is that there is NO WebChannelFactory for SliverLight.</p> <p>Period.</p> <p>This means that when it comes to silverlight code, my options are:</p> <ul> <li>Write ugly code using WebClient, which ultimately means I will have to update two sets of code whenever I have a change to my API </li> <li>Use SOAP/WS for the WebService and keep updating the service reference from Visual Studio</li> </ul> <p>Is there a way to keep the "clean" implementation with WebChannelFactory in SilverLight? Perhaps a public domain / open source WebChannelFactory for SilverLight?</p> <p>Any help with this will be greatly appreciated!</p>
<p>I almost hate to suggest it but would you feel comfortable with <a href="http://msdn.microsoft.com/en-us/library/ms405827(VS.95).aspx" rel="nofollow noreferrer" title="ChannelFactoryBase&lt;TChannel&gt;">reimplementing the WebChannelFactory&lt;T&gt; class</a>?</p> <p>From a cursory glance through the Silverlight API it looks like you won't get much help from Microsoft out of the box. You'd need to reimplement a channel class and a factory for it.</p> <p>Perhaps another way to create the channel and to isolate yourself from the platform-specific code is to create a custom implementation of it? Specifically what I mean is, you create yet another factory class, and the factory class either calls to the WebChannelFactory when it's available, or goes through the hoops of setting it up for you.</p> <p>Sorry I don't have a more in-depth suggestion. :)</p>
<p>I recently ran into the same problem and decided to create a class that has a simplified REST client interface for Silverlight, more or less like WebChannelFactory. Has synchronous-like behavior also.</p> <p><a href="http://regular-language.blogspot.com/2011/06/wcf-webhttp-rest-client-for-silverlight.html" rel="nofollow">http://regular-language.blogspot.com/2011/06/wcf-webhttp-rest-client-for-silverlight.html</a></p>
35,038
<p>Is it always possible to ping localhost and it resolves to 127.0.0.1?</p> <p>I know Windows Vista, XP, Ubuntu and Debian do it but does everyone do it?</p>
<p>Any correct implementation of TCP/IP will reserve the address 127.0.0.1 to refer to the local machine. However, the mapping of the name "localhost" to that address is generally dependent on the system <code>hosts</code> file. If you were to remove the localhost entry from <code>hosts</code>, then the localhost name may no longer resolve properly at all.</p>
<p>Ok. </p> <p>The reason why it resolves it is record in %WINDOWS_DIR%\System32\drivers\etc\hosts file like this:</p> <p>127.0.0.1 localhost</p>
13,839
<p>I am looking for a tool that can detect malicious requests (such as obvious SQL injection gets or posts) and will immediately ban the IP address of the requester/add to a blacklist. I am aware that in an ideal world our code should be able to handle such requests and treat them accordingly, but there is a lot of value in such a tool even when the site is safe from these kinds of attacks, as it can lead to saving bandwidth, preventing bloat of analytics, etc.</p> <p>Ideally, I'm looking for a cross-platform (<code>LAMP/.NET</code>) solution that sits at a higher level than the technology stack; perhaps at the web-server or hardware level. I'm not sure if this exists, though.</p> <p>Either way, I'd like to hear the community's feedback so that I can see what my options might be with regard to implementation and approach.</p>
<p>Your almost looking at it the wrong way, no 3party tool that is not aware of your application methods/naming/data/domain is going to going to be able to perfectly protect you.</p> <p>Something like SQL injection prevention is something that has to be in the code, and best written by the people that wrote the SQL, because they are the ones that will know what should/shouldnt be in those fields (unless your project has very good docs)</p> <p>Your right, this all has been done before. You dont quite have to reinvent the wheel, but you do have to carve a new one because of a differences in everyone's axle diameters.</p> <p>This is not a drop-in and run problem, you really do have to be familiar with what exactly SQL injection is before you can prevent it. It is a sneaky problem, so it takes equally sneaky protections.</p> <p>These 2 links taught me far more then the basics on the subject to get started, and helped me better phrase my future lookups on specific questions that weren't answered.</p> <ul> <li><a href="http://en.wikipedia.org/wiki/SQL_injection" rel="nofollow noreferrer">SQL injection</a></li> <li><a href="http://www.unixwiz.net/techtips/sql-injection.html" rel="nofollow noreferrer">SQL Injection Attacks by Example</a></li> </ul> <p>And while this one isnt quite a 100% finder, it will "show you the light" on existing problem in your existing code, but like with webstandards, dont stop coding once you pass this test.</p> <ul> <li><a href="http://www.securitycompass.com/exploitme.shtml" rel="nofollow noreferrer">Exploit-Me</a></li> </ul>
<p>Interesting how this is being implemented years later by google and them removing the URL all together in order to prevent XSS attacks and other malicious acitivites</p>
2,367
<p>I'm attempting to use the following code to serialize an anonymous type to JSON:</p> <pre><code>var serializer = new DataContractJsonSerializer(thing.GetType()); var ms = new MemoryStream(); serializer.WriteObject(ms, thing); var json = Encoding.Default.GetString(ms.ToArray()); </code></pre> <p>However, I get the following exception when this is executed:</p> <blockquote> <p>Type '&lt;>f__AnonymousType1`3[System.Int32,System.Int32,System.Object[]]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. See the Microsoft .NET Framework documentation for other supported types.</p> </blockquote> <p>I can't apply attributes to an anonymous type (as far as I know). Is there another way to do this serialization or am I missing something? </p>
<p>Try the JavaScriptSerializer instead of the DataContractJsonSerializer</p> <pre><code>JavaScriptSerializer serializer = new JavaScriptSerializer(); var output = serializer.Serialize(your_anon_object); </code></pre>
<pre><code>public static class JsonSerializer { public static string Serialize&lt;T&gt;(this T data) { try { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); var stream = new MemoryStream(); serializer.WriteObject(stream, data); string jsonData = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length); stream.Close(); return jsonData; } catch { return ""; } } public static T Deserialize&lt;T&gt;(this string jsonData) { try { DataContractJsonSerializer slzr = new DataContractJsonSerializer(typeof(T)); var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonData)); T data = (T)slzr.ReadObject(stream); stream.Close(); return data; } catch { return default(T); } } } </code></pre>
43,008
<p>If I have a method such as:</p> <pre><code>public void MyMethod(int arg1, string arg2) </code></pre> <p>How would I go about getting the actual names of the arguments? I can't seem to find anything in the MethodInfo which will actually give me the name of the parameter.</p> <p>I would like to write a method which looks like this:</p> <pre><code>public static string GetParamName(MethodInfo method, int index) </code></pre> <p>So if I called this method with:</p> <pre><code>string name = GetParamName(MyMethod, 0) </code></pre> <p>it would return "arg1". Is this possible?</p>
<pre><code>public static string GetParamName(System.Reflection.MethodInfo method, int index) { string retVal = string.Empty; if (method != null &amp;&amp; method.GetParameters().Length &gt; index) retVal = method.GetParameters()[index].Name; return retVal; } </code></pre> <p>The above sample should do what you need.</p>
<p>without any kind of error checking:</p> <pre><code>public static string GetParameterName ( Delegate method , int index ) { return method.Method.GetParameters ( ) [ index ].Name ; } </code></pre> <p>You could use 'Func&lt;TResult&gt;' and derivatives to make this work for most situations</p>
26,319
<p>When the command prompt opens and then just closes really fast (because there isn't a pause line) is there a way to see what it just showed you? </p>
<p>You can pipe the output to a file.</p> <pre><code>something.exe &gt; c:\temp\output.txt </code></pre> <p>This works on the prompt and in the windows run dialog box.</p>
<p>Run the console application from the command line, that way the console window will not close after the execution.</p> <p>Open cmd prompt,</p> <p>type the program to run Ex.: </p> <pre><code>c:\&gt; ipconfig /all </code></pre> <p>I should get more coffee in my system before answering.</p>
43,394
<p>With really small sets of data, the policy where I work is generally to stick them into text files, but in my experience this can be a development headache. Data generally comes from the database and when it doesn't, the process involved in setting it/storing it is generally hidden in the code. With the database you can generally see all the data available to you and the ways with which it relates to other data.</p> <p>Sometimes for really small sets of data I just store them in an internal data structure in the code (like A Perl hash) but then when a change is needed, it's in the hands of a developer. </p> <p>So how do you handle small sets of infrequently changed data? Do you have set criteria of when to use a database table or a text file or..? </p> <p>I'm tempted to just use a database table for absolutely everything but I'm not sure if there are any implications to this.</p> <p><strong>Edit:</strong> For context:</p> <p>I've been asked to put a new contact form on the website for a handful of companies, with more to be added occasionally in the future. Except, companies don't have contact email addresses.. the users inside these companies do (as they post jobs through their own accounts). Now though, we want a "speculative application" type functionality and the form needs an email address to send these applications to. But we also don't want to put an email address as a property in the form or else spammers can just use it as an open email gateway. So clearly, we need an ID -> contact_email type relationship with companies. </p> <p>SO, I can either add a column to a table with millions of rows which will be used, literally, about 20 times OR create a new table that at most is going to hold about 20 rows. Typically how we handle this in the past is just to create a nasty text file and read it from there. But this creates maintenance nightmares and these text files are frequently looked over when data that they depend on changes. Perhaps this is a fault with the process, but I'm just interested in hearing views on this.</p>
<p>Put it in the database. If it changes infrequently, cache it in your middle tier.</p>
<p>I would add it to the database in the main table:</p> <ol> <li>Backup and recovery (you do want to recover this text file, right?)</li> <li>Adhoc querying (since you can do it will a SQL tool and join it to the other database data)</li> <li>If the database column is empty the store requirements for it should be minimal (nothing if it's a NULL column at the end of the table in Oracle)</li> <li>It will be easier if you want to have multiple application servers as you will not need to keep multiple copies of some extra config file around</li> <li>Putting it into a little child table only complicates the design without giving any real benefits</li> </ol> <p>You may well already be going to that same row in the database as part of your processing anyway, so performance is not likely to be a problem. If you are not, you could cache it in memory.</p>
16,152
<p>I'd like to capture the output of <a href="http://us3.php.net/manual/en/function.var-dump.php" rel="noreferrer"><code>var_dump</code></a> to a string.</p> <p>The PHP documentation says;</p> <blockquote> <p>As with anything that outputs its result directly to the browser, the <a href="http://us3.php.net/manual/en/ref.outcontrol.php" rel="noreferrer">output-control functions</a> can be used to capture the output of this function, and save it in a string (for example).</p> </blockquote> <p>What would be an example of how that might work?</p> <p><code>print_r()</code> isn't a valid possibility, because it's not going to give me the information that I need.</p>
<p>Use output buffering:</p> <pre><code>&lt;?php ob_start(); var_dump($someVar); $result = ob_get_clean(); ?&gt; </code></pre>
<p>From <a href="http://htmlexplorer.com/2015/01/assign-output-var_dump-print_r-php-variable.html" rel="nofollow">http://htmlexplorer.com/2015/01/assign-output-var_dump-print_r-php-variable.html</a>:</p> <blockquote> <p>var_dump and print_r functions can only output directly to browser. So the output of these functions can only retrieved by using output control functions of php. Below method may be useful to save the output.</p> <pre><code>function assignVarDumpValueToString($object) { ob_start(); var_dump($object); $result = ob_get_clean(); return $result; } </code></pre> </blockquote> <p>ob_get_clean() can only clear last data entered to internal buffer. So ob_get_contents method will be useful if you have multiple entries.</p> <p>From the same source as above:</p> <blockquote> <pre><code>function varDumpToErrorLog( $var=null ){ ob_start(); // start reading the internal buffer var_dump( $var); $grabbed_information = ob_get_contents(); // assigning the internal buffer contents to variable ob_end_clean(); // clearing the internal buffer. error_log( $grabbed_information); // saving the information to error_log } </code></pre> </blockquote>
16,870
<p>I was hoping someone could validate my assumptions before I recommend that my client upgrade from a 30/mo to a 80/mo hosting package. </p> <p><strong>Site:</strong> the site is a custom ASP.NET ecommerce site. the shopping carts are stored in the inproc session.</p> <p><strong>Problem</strong> during busy seasons like we are having now, users are frequently losing their shopping carts and their FormsAuthentication Login information. </p> <p><strong>Solution</strong> I wanted to migrate the site to use a SQL Server Session state. My assumptions are that the customers are losing their shopping carts because the InProc sessions are recycling more frequently then their 20 minute timeout, due to load. Will moving the Session to SQL Server or a Session State Server allow customer to store their Shopping Cart Session without the recycle, If so, can once their will I have any issues if I increase the Session timeout to say 40 or 60 minutes </p>
<p>Using the SQL Session state means that sessions should survive a recycle of IIS, (but not a recycle of SQL Server if you use the default script which creates the session database in the tempdb).</p> <p>There is a script available from the Microsoft website which creates a permanent session state db. I would recommend using that one instead (See <a href="http://www.dbazine.com/sql/sql-articles/cook9" rel="nofollow noreferrer">here</a>).</p> <p>So, to basically answer your question. Yes, the SQL Session state will help. You might want to consider also using the out-of-proc state server to test your theory.</p> <p>Also, as a co-worker has just reminded me, make sure anything you store in the session is marked as serializable before migrating, otherwise you will run into problems.</p>
<p>The assumptions sound reasonable to me. might also want to look at the settings on the AppPool and try to figure out why its recycling. Maybe all you need to do is change those (if you can).</p>
47,365
<p>I have three tables like that:</p> <p><strong>Articles</strong> IdArticle Title Content</p> <p><strong>Tags</strong> IdTag TagName</p> <p><strong>ContentTag</strong> IdContentTag Idtag IdContent</p> <p>When user in my site write an article with adding tags and submit, I want to save it to tables above. </p> <p>In traditional ways, I used to use transaction and I could do it. But How can I do it by using linq to sql?</p>
<p>Why do you need to call a function when the list is scrolled? </p> <p>If you are changing the items as it's scrolled i would recommend setting the listview to virtual.</p> <p>Or you could override the listview and do this:</p> <pre><code>public class TestListView : System.Windows.Forms.ListView { private const int WM_HSCROLL = 0x114; private const int WM_VSCROLL = 0x115; public event EventHandler Scroll; protected void OnScroll() { if (this.Scroll != null) this.Scroll(this, EventArgs.Empty); } protected override void WndProc(ref System.Windows.Forms.Message m) { base.WndProc(ref m); if (m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL) this.OnScroll(); } } </code></pre>
<p>it seems the best approach is the brian's solution. However, its only responds to events generated by scrollbars, but no to events from mouse midbuttton.</p> <p>if you change the conditional:</p> <pre><code> if (m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL) this.OnScroll(); </code></pre> <p>by:</p> <pre><code> if (m.Msg == 0x000c2c9) this.OnScroll(); </code></pre> <p>now it respods at all scrolling events in listview.</p>
48,628