instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully?</p> <p>Am I missing a best practice for tags?</p>
<p>Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly. </p> <pre><code>Table: Item Columns: ItemID, Title, Content Table: Tag Columns: TagID, Title Table: ItemTag Columns: ItemID, TagID </code></pre>
<p>I would suggest following design : Item Table: Itemid, taglist1, taglist2<br> this will be fast and make easy saving and retrieving the data at item level. </p> <p>In parallel build another table: Tags tag do not make tag unique identifier and if you run out of space in 2nd column which contains lets say 100 items create another row. </p> <p>Now while searching for items for a tag it will be super fast.</p>
4,123
<p>Is there a way to make a TSQL variable constant?</p>
<p>No, but you can create a function and hardcode it in there and use that.</p> <p>Here is an example:</p> <pre><code>CREATE FUNCTION fnConstant() RETURNS INT AS BEGIN RETURN 2 END GO SELECT dbo.fnConstant() </code></pre>
<p>The best answer is from SQLMenace according to the requirement if that is to create a temporary constant for use within scripts, i.e. across multiple GO statements/batches.</p> <p>Just create the procedure in the tempdb then you have no impact on the target database.</p> <p>One practical example of this is a database create script which writes a control value at the end of the script containing the logical schema version. At the top of the file are some comments with change history etc... But in practice most developers will forget to scroll down and update the schema version at the bottom of the file.</p> <p>Using the above code allows a visible schema version constant to be defined at the top before the database script (copied from the generate scripts feature of SSMS) creates the database but used at the end. This is right in the face of the developer next to the change history and other comments, so they are very likely to update it.</p> <p>For example:</p> <pre><code>use tempdb go create function dbo.MySchemaVersion() returns int as begin return 123 end go use master go -- Big long database create script with multiple batches... print 'Creating database schema version ' + CAST(tempdb.dbo.MySchemaVersion() as NVARCHAR) + '...' go -- ... go -- ... go use MyDatabase go -- Update schema version with constant at end (not normally possible as GO puts -- local @variables out of scope) insert MyConfigTable values ('SchemaVersion', tempdb.dbo.MySchemaVersion()) go -- Clean-up use tempdb drop function MySchemaVersion go </code></pre>
4,619
<p>I have a program that runs osql.exe from microsoft sql server tools directory and runs a script. </p> <p>The problem is that on computers that don't have an installation of sql server, this tool is missing. So my question is whether or not is possible to run it as a standalone( along with any dll that may be required ) meaning that run them from Process.Start from a local directory of the application.</p>
<p>Yes, you can. Just copy the binary and off you go.</p>
<p>Why are you spawning osql?</p> <p>I've written simple programs to execute scripts using SMO - mostly insired by <a href="http://weblogs.asp.net/jgalloway/archive/2006/11/07/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-_2D00_-the-easy-way.aspx" rel="nofollow noreferrer">this post</a>.</p> <p><strong>EDIT</strong></p> <p>The jist of the post is to use <a href="https://msdn.microsoft.com/en-gb/library/ms162169.aspx" rel="nofollow noreferrer">SQL Server Management Objects (SMO)</a>. <a href="http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.management.common.serverconnection.executenonquery.aspx" rel="nofollow noreferrer"><code>Server.ConnectionContext.ExecuteNonQuery</code></a> parses SQL with <code>GO</code> statements in it.</p>
33,781
<p>I'm serializing an object in a C# VS2003 / .Net 1.1 application. I need it serialized without the processing instruction, however. The XmlSerializer class puts out something like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-16" ?&gt; &lt;MyObject&gt; &lt;Property1&gt;Data&lt;/Property1&gt; &lt;Property2&gt;More Data&lt;/Property2&gt; &lt;/MyObject&gt; </code></pre> <p>Is there any way to get something like the following, without processing the resulting text to remove the tag?</p> <pre><code>&lt;MyObject&gt; &lt;Property1&gt;Data&lt;/Property1&gt; &lt;Property2&gt;More Data&lt;/Property2&gt; &lt;/MyObject&gt; </code></pre> <p>For those that are curious, my code looks like this...</p> <pre><code>XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); StringBuilder builder = new StringBuilder(); using ( TextWriter stringWriter = new StringWriter(builder) ) { serializer.Serialize(stringWriter, comments); return builder.ToString(); } </code></pre>
<p>In 2.0, you would use <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.omitxmldeclaration.aspx" rel="noreferrer">XmLWriterSettings.OmitXmlDeclaration</a>, and serialize to an XmlWriter - however I don't think this exists in 1.1; so not <em>entirely</em> useful - but just one more "consider upgrading" thing... and yes, I realise it isn't always possible.</p>
<p>If by "processing instruction" you mean the xml declaration, then you can avoid this by setting the OmitXmlDeclaration property of XmlWriterSettings. You'll need to serialize using an XmlWriter, to accomplish this.</p> <pre><code>XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); StringBuilder builder = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; using ( XmlWriter stringWriter = new StringWriter(builder, settings) ) { serializer.Serialize(stringWriter, comments); return builder.ToString(); } </code></pre> <p>But ah, this doesn't answer your question for 1.1. Well, for reference to others.</p>
19,894
<p>I am currently writing an open source wrapper for a COM object. I have just installed StyleCop and run it against some of my code, and as I expected it threw up a load of warnings (some of which I should have been doing already eg adding "this." to all local method calls and variables)</p> <p>How many of these warnings should I try and reduce? Which ones would be the best ones when writing an open source library?</p>
<p>The general idea with StyleCop is: All of them :)</p> <p>The more options you turn off the less value StyleCop has in enforcing a one-true code format. That being said, if you don't like some of the options then some options is better than none, include the StyleCop settings file with your code and others working on it can then use the same settings.</p> <p>Some of the settings may seem weird at first if you're not familiar with StyleCop, but having used it for two years now I leave all the options on and our team is quite happy with the results.</p> <p>I'd also say that if you're providing a library or framework that using <a href="http://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx" rel="nofollow noreferrer">FxCop</a> may be more important than using StyleCop.</p>
<p>Most large open source projects have their own style guidelines. For example, here's the <a href="http://httpd.apache.org/dev/styleguide.html" rel="nofollow noreferrer">Apache C Language Style Guide</a>.</p> <p>As a start, I suggest trawling the FAQ for the OS project you're interested in and take it from there.</p> <p>Anyway, I'm sure there'll be plenty of people who'll quickly let you know if you're breaking any existing style rules in a big way! ;-)</p> <p>Take heed of all the warnings, usually they are trying to tell you something useful. Don't finish up "programming by coincidence" (<a href="http://www.pragprog.com/the-pragmatic-programmer/extracts/coincidence" rel="nofollow noreferrer">book excerpt</a>) as the Pragmatic Programmers say!</p> <p>Edit: I didn't realise that this was your own, new, OS project. My bad. Anyway, I'd have a sniff around some similar already existing OS projects and see if they have any style guides. Definitely, check out Steve McConnell's book Code Complete (<a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="nofollow noreferrer" rel="nofollow noreferrer">Amazon link</a> - sanitised for the script kiddie link nazis that roam these halls).</p> <p>What I said about warnings and "programming by coincidence" still applies! (-:</p> <p>HTH.</p> <p>cheers,</p> <p>Rob</p>
43,303
<p>This is the trace of my app,when I updated my device to 2.2.</p> <p>any idea to get rid of this leak? because I think that's the culprit who keep crashing my application.<br> This is trace when I run my application in os2.2,see the image which show the part which might be generating leak,and if you can give me some hints to resolve it, will be greatly appreciated.</p> <p><a href="http://origindata.wapfly.com.au/extra/Picture%204.png" rel="nofollow noreferrer">alt text http://origindata.wapfly.com.au/extra/Picture%204.png</a></p> <p><a href="http://origindata.wapfly.com.au/extra/Picture%203.png" rel="nofollow noreferrer">alt text http://origindata.wapfly.com.au/extra/Picture%203.png</a> This is trace when I run my application in os2.1.it's very wired issue. <a href="http://origindata.wapfly.com.au/extra/Picture%205.png" rel="nofollow noreferrer">alt text http://origindata.wapfly.com.au/extra/Picture%205.png</a></p>
<p>That trace is rather meaningless without access to the code. My suggestion would be to download and install the Clang Static Analyzer and run your code against it to determine where the leak exists. It can be found at <a href="http://clang.llvm.org/StaticAnalysis.html" rel="nofollow noreferrer">http://clang.llvm.org/StaticAnalysis.html</a> - to use it, copy the contents of the .tar.gz file to /usr/bin then cd to your Xcode project and run <code>scan-build xcodebuild</code>. At which point you'll be given output that directs you to copy and pate a line that resembles <code>scan-view /tmp/logs/...</code> That should give you some indication.</p>
<p>You need to click the "View" button in the upper right of Instruments and choose "Extended Detail" then click the line item as you have selected above then click the details in the Extended Details right hand side column and it will open up to the line of code at fault in XCode </p>
44,578
<p>I'm looking for a way in .NET (2.0, C# in particular) for source code to trigger a debugging break as if a breakpoint was set at that point, without having to remember to set a specific breakpoint there in the debugger, and without interfering with production runtime.</p> <p>Our code needs to swallow exceptions in production so we don't disrupt a client application that links to us, but I'm trying to set it up so that such errors will pop up to be analyzed if it happens to be running in a debugger, and otherwise will be safely ignored.</p> <p>My attempt to use <code>Debug.Assert(false)</code> has been less than ideal, and I assume that <code>Debug.Fail()</code> would behave the same way. It should theoretically have no effect in production, and it does successfully stop when debugging, but by design there is (as far as I can tell) no way to continue execution if you want to ignore that error, like you could with an actual breakpoint, and like it would do in production where we swallow the error. It also apparently breaks evaluation of variable state because the debugger actually stops down in native system code and not in ours, so it's debugging help is limited. (Maybe I'm missing some way of getting back into things to look at the variables and so on where it happened. ???)</p> <p>I was hoping for something like <code>Debug.Break()</code>, but it doesn't seem to exist (unless maybe in a later version of .NET?), and no other <code>Debug</code> methods seem applicable, either.</p> <p><strong>Update:</strong> While ctacke's answer is the best match for what I was looking for, I have since also discovered a trick with Debug.Assert()--when running in the debugger--Pause the debugger, go to the code for the Debug.Assert call pending (highlighted in green because it is down in the framework code) and hit Step-Out (shift-F11), then hit Ignore in the assert dialog box. This will leave the debugger paused upon the return of the assert (and able to continue execution as if it hadn't occurred, because it was ignored). There may be other ways to do much the same thing (does hitting Retry do this more directly?), but this way was intuitive.</p>
<p>You probably are after something like this:</p> <pre><code>if(System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); </code></pre> <p>Of course that will still get compiled in a Release build. If you want it to behave more like the Debug object where the code simply doesn't exist in a Release build, then you could do something like this:</p> <pre><code> // Conditional("Debug") means that calls to DebugBreak will only be // compiled when Debug is defined. DebugBreak will still be compiled // even in release mode, but the #if eliminates the code within it. // DebuggerHidden is so that, when the break happens, the call stack // is at the caller rather than inside of DebugBreak. [DebuggerHidden] [Conditional("DEBUG")] void DebugBreak() { if(System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); } </code></pre> <p>Then add a call to it in your code.</p>
<p>In Visual Studio 2010, hitting <strong>Retry</strong> on a <code>Debug.Assert</code> dialog takes you to the failed debug assertion, just as if you had a breakpoint.</p>
47,172
<p>Does anyone know of a faster decimal implementation in python?</p> <p>As the example below demonstrates, the standard library's decimal module is ~100 times slower than <code>float</code>.</p> <pre class="lang-py prettyprint-override"><code>from timeit import Timer def run(val, the_class): test = the_class(1) for c in xrange(10000): d = the_class(val) d + test d - test d * test d / test d ** test str(d) abs(d) if __name__ == "__main__": a = Timer("run(123.345, float)", "from decimal_benchmark import run") print "FLOAT", a.timeit(1) a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal") print "DECIMAL", a.timeit(1) </code></pre> <p><em>Outputs:</em></p> <pre><code>FLOAT 0.040635041427 DECIMAL 3.39666790146 </code></pre>
<p>The <a href="http://gmplib.org" rel="noreferrer">GMP</a> library is one of the best arbitrary precision math libraries around, and there is a Python binding available at <a href="http://www.aleax.it/gmpy.html" rel="noreferrer">GMPY</a>. I would try that method.</p>
<p>python Decimal is very slow, one can use float or a faster implementation of Decimal cDecimal.</p>
23,703
<p>Is SQL case sensitive? I've used <a href="https://en.wikipedia.org/wiki/MySQL" rel="nofollow noreferrer">MySQL</a> and <a href="https://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL Server</a> which both seem to be case insensitive. Is this always the case? Does the standard define case-sensitivity?</p>
<p>The SQL keywords are case insensitive (<code>SELECT</code>, <code>FROM</code>, <code>WHERE</code>, etc), but they are often written in all caps. However, in some setups, table and column names are case sensitive.</p> <p>MySQL has a configuration option to enable/disable it. Usually case sensitive table and column names are the default on Linux <a href="https://en.wikipedia.org/wiki/MySQL" rel="nofollow noreferrer">MySQL</a> and case insensitive used to be the default on Windows, but now the installer asked about this during setup. For <a href="https://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL Server</a> it is a function of the database's collation setting.</p> <p>Here is the <a href="http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html" rel="nofollow noreferrer">MySQL page about name case-sensitivity</a></p> <p>Here is the <a href="http://msdn.microsoft.com/en-us/library/ms143503(SQL.90).aspx" rel="nofollow noreferrer">article in MSDN about collations for SQL Server</a></p>
<p><strong>Have the best of both worlds</strong></p> <p>These days you can just write all your SQL statements in lowercase and if you ever need to have it formatted then just install a plugin that will do it for you. This is only applicable if your code editor has those plug-ins available. <a href="https://en.wikipedia.org/wiki/Visual_Studio_Code" rel="nofollow noreferrer">Visual Studio Code</a> has many extensions that can do this.</p> <p>Here's a couple you can use: <a href="https://github.com/kufii/vscode-sql-formatter" rel="nofollow noreferrer">vscode-sql-formatter</a> and <a href="https://github.com/cymonbr/SqlFormatter-VSCode" rel="nofollow noreferrer">SqlFormatter-VSCode</a></p>
18,596
<p>When I click on a row in my GridView, I want to go to a other page with the ID I get from the database. </p> <p>In my RowCreated event I have the following line:</p> <pre><code>e.Row.Attributes.Add( "onClick", ClientScript.GetPostBackClientHyperlink( this.grdSearchResults, "Select$" + e.Row.RowIndex)); </code></pre> <p>To prevent error messages i have this code:</p> <pre><code>protected override void Render(HtmlTextWriter writer) { // .NET will refuse to accept "unknown" postbacks for security reasons. // Because of this we have to register all possible callbacks // This must be done in Render, hence the override for (int i = 0; i &lt; grdSearchResults.Rows.Count; i++) { Page.ClientScript.RegisterForEventValidation( new System.Web.UI.PostBackOptions( grdSearchResults, "Select$" + i.ToString())); } // Do the standard rendering stuff base.Render(writer); } </code></pre> <p>How can I give a row a unique ID (from the DB) and when I click the row, another page is opened (like clicking on a href) and that page can read the ID.</p>
<p>I have the solution.</p> <p>This is what i have done:</p> <pre><code>if(e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes["onClick"] = "location.href='view.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "id") + "'"; } </code></pre> <p>I have putted the preceding code in the RowDataBound event.</p>
<p>Can your ID be related to the data item displayed in the gridview?</p> <p>If so you can use e.Row.DataItem, and cast it to whatever type it is.</p>
42,904
<p>I'm looking for a script or application that tidies up and reformats SQL queries. I've found some good online SQL formatters (see <a href="http://www.wangz.net/gsqlparser/sqlpp/sqlformat.htm" rel="nofollow noreferrer">here</a>) , as well as some downloadable commercial applications. I'm cautious about using an online service as I don't want to risk copies of these queries being stored somewhere they might be compromised, if only in a web server's cache (and it is against my employer's policy). </p> <p>Does anyone know of any open-source applications, scripts, or downloadable freeware that might help me out with this?</p> <p>It probably bears mentioning that I'm working on a Windows platform at work, but I am open to suggestions for other operating systems.</p> <p>Cheers!</p> <p><strong>Update</strong></p> <p>I have used SQLInform as suggested by Vinko Vrsalovic to excellent effect. Thanks Vinko!</p> <p>Something that might also be worth watching is <a href="http://code.google.com/p/sqltidy/" rel="nofollow noreferrer">SQLTidy</a>, a young project on Google Code which could turn into something great in the long run.</p>
<p>Some things to try out (SQLinForm is free until 2009). It's weird how some niches totally lack good open source tools.</p> <p><a href="http://www.trialpay.com/checkout/?c=bb7014d&amp;tid=6rGUpGo" rel="nofollow noreferrer">http://www.trialpay.com/checkout/?c=bb7014d&amp;tid=6rGUpGo</a></p> <p><a href="http://www.sqlinform.com" rel="nofollow noreferrer">http://www.sqlinform.com</a></p> <p><a href="http://www.fileheap.com/software-universal-sql-editor-download-11096.html" rel="nofollow noreferrer">http://www.fileheap.com/software-universal-sql-editor-download-11096.html</a></p> <p>An Emacs macro:</p> <p><a href="http://www.emacswiki.org/emacs-en/tsql-indent.el" rel="nofollow noreferrer">http://www.emacswiki.org/emacs-en/tsql-indent.el</a></p>
<p>Red Gate SQL Refactor (trial) + a Virtual Machine</p>
27,160
<p>With text-recognition improving and CAPTCHA-breakers using Mechanical Turks to break otherwise unbreakable keys, what's the next technology to keep scripts from spam-botting a site that relies on user input?</p>
<p>I like the concept of an 'Invisible Captcha'. Phil Haack details one implementation <a href="http://haacked.com/archive/2006/09/26/Lightweight_Invisible_CAPTCHA_Validator_Control.aspx" rel="nofollow noreferrer">here</a>.</p> <p>This banks on the fact that bots, spiders, and crawlers don't implement javascript engines. This too could change in the near future.</p>
<p>The most fundamental tool to keep people from spambotting a user input site is the "nofollow" tag on links. Most comment-spammers are interested in Google juice rather than actually having their stuff seen, so nofollow removes the incentive. </p>
8,443
<p>is there any known pattern/algorithm on how to perform sorting or filtering a list of records (from database) in the correct way? My current attempt involves usage of a form that provides some filtering and sorting options, and then append these criteria and sorting algorithm to my existing SQL. However, I find it can be easily abused that users may get results that they are not suppose to see. </p> <p>The application that I am building is a scheduler where I store all the events in a database table. Then depending on user's level/role/privilege a different subset of data will be displayed. Therefore my query can be as complicated as </p> <pre><code>SELECT * FROM app_event._event_view WHERE ((class_id = (SELECT class_id FROM app_event._ical_class WHERE name = 'PUBLIC') AND class_id != (SELECT class_id FROM app_event._ical_class WHERE name = 'PRIVATE') AND class_id != (SELECT class_id FROM app_event._ical_class WHERE name = 'CONFIDENTIAL')) OR user_id = '1') AND calendar_id IN (SELECT calendar_id FROM app_event.calendar WHERE is_personal = 't') AND calendar_id = (SELECT calendar_id FROM app_event.calendar WHERE name = 'personal') AND state_id IN (1,2,3,4,5,6) AND EXTRACT(year FROM dtstart) = '2008' AND EXTRACT(month FROM dtstart) = '11' </code></pre> <p>As I am more concern about serving the correct subset of information, performance is not a major concern at the moment (as the sql mentioned was generated by the script, clause by clause). I am thinking of turning all these complicated SQL statements to views, so there will be less chances that the SQL generated is inappropriate.</p>
<p>First off, this query will look and perform better if you use joins:</p> <pre><code>SELECT * FROM app_event._event_view EV INNER JOIN app_event.calendar C ON EV.calendar_id = C.calendar.id INNER JOIN app_event._ical_class IC ON C.class_id = EV.class_id WHERE C.is_personal = 't' AND C.name = 'personal' AND state_id IN (1,2,3,4,5,6) AND EXTRACT(year FROM dtstart) = '2008' AND EXTRACT(month FROM dtstart) = '11' AND ( IC.name = 'PUBLIC' -- other two are redundant OR user_id = '1' ) </code></pre> <p>That's a good start for keeping complexity down. Then, if you want to add additional filters directly to the SQL, you can append more "AND ..." statements at the end. Since all the criteria are connected with AND (the OR is safely contained within parentheses), there's no possibility of someone adding a criterion after these that somehow undoes the ones above - that is, once you've restricted the results with one part of a clause, you can't "un-restrict" it with a later clause if it's strung together with ANDs. (Of course, if those additional clauses go anywhere near user text input, you have to sanitize them to prevent SQL injection attacks.)</p> <p>The database can filter faster than any other tier, in general, because using a WHERE clause on the database will often allow the database to avoid even reading the unnecessary records off the disk, which is several orders of magnitude slower than anything you can do with the CPU. Sorting is often faster on the DB as well, because the DB can often do the joins in such a way that records are already sorted in the order you want them. So, performance wise, if you can do it on the DB, all the better.</p> <p>You said performance isn't really the key here, though, so adding filters programatically in the business logic might be fine for you, and easier to read than messing with SQL strings.</p>
<p>It's hard to understand that query, because I have to scroll massively and since I don't know the database...</p> <p>But if the privilegues are "one dimensional", e.g. admins can see everything, power users can see less than admins, guests can see less than power users, etc.: you could probably implement the privilegues as an integer in both the event and the user, then </p> <pre><code>select from event where conditions AND event.privilegue &lt;= user.privilegue </code></pre> <p>If you set the privilegue values something like 10 000 (high/admin), 5000, 1(lowest/guest) you can later add more levels in between without changing all your code.</p>
37,692
<p>Is Structured Exception Handling bad? What is the right way to handle exceptions?</p> <p><strong>EDIT: Exception Handling in .NET using C#.</strong></p> <p>I usually have a set of specific exception classes (DivideByZeroException, ArrayTypeMismatchException) and don't have a generic "catch (Exception ex)".</p> <p>The thinking behind this is that I expect certain types of exceptions to occur and have specific actions defined when they occur and the unexpected exceptions would rise up the the interface (either windows or web). Is this a good practice? </p>
<p>I'm not sure what you mean by 'structured exception handling'. </p> <p>The worst thing that can be done in exception handling is to 'swallow' the exception or handle it silently.</p> <p>Do NOT do this:</p> <pre><code>try { ... } catch (Exception e) { //TODO: handle this later } </code></pre> <p>This is very often done out of laziness to get code to compile. If you do not know how to handle the exception at a particular level, have the method throw the exception and at least have a catch all handler at the top. Provide feedback somehow (via the GUI, a page / email to a support person, log file) so that the issue can eventually get fixed. Silently catching an exception almost always leads to a bigger issue happening later on and it being difficult to trace.</p>
<p>I'm not a Windows programmer, but it seems to me that using structured exception handling to treat hardware exceptions like software exceptions means that:</p> <ul> <li>Your code does something that in the C++ standard produces undefined or implementation-defined behaviour (such as dividing by zero).</li> <li>Windows defines that with SEH enabled it throws an exception in that case.</li> <li>You are using this fact to catch the exception and/or execute a termination handler.</li> </ul> <p>So the questions to ask, IMO, are:</p> <ul> <li>Is your programming task really of a nature that standard C++ cannot handle? (or can only handle in a way which is measurably inferior to what you get by allowing the hardware exception).</li> <li>Do you really need to take action when your code goes non-standard?</li> <li>Can you write your code so that it doesn't provoke hardware exceptions in the first place?</li> </ul> <p>If the answers are 'yes', 'yes', 'no', then structured exception handling is needed. Otherwise you may be able to avoid it, in which case you probably want to. Writing exception-safe code is tricky, so the stronger the exception guarantees you can offer the better. Code which maybe divides by zero with SEH isn't offering the nothrow guarantee, when perhaps with a bit of redesign so that callers don't give it duff data, it could do so. But if a function already has to throw exceptions for other reasons, then also possibly throwing them for hardware traps might make things no worse.</p> <p>One notable special case is memory allocation. Not sure if .NET does this, but on linux allocation only fails if there's insufficient virtual address space for the allocation. Physical memory is committed on first use, and causes a hardware exception if there isn't enough. Since memory allocation is <em>supposed</em> to throw std::bad_alloc on failure, and the implementation fails to implement this requirement of the standard, it <em>may</em> be that in some cases converting the hardware exception to software is the right thing to do. However, that hardware exception can occur in unexpected places, (including in routines you thought were nothrow), so may still be impossible to handle gracefully, which is why linux core dumps instead of throwing. In practice, anything that gets initialised fully will crash its constructor, which is often close enough to the allocation that a software exception instead would be useful.</p>
45,964
<p>I'm trying to animate Visio objects with a loop, such as:</p> <pre><code>For reposition = 2 To 6 xpos = reposition ypos = reposition sh1.SetCenter xpos, ypos Sleep 1000 Next reposition </code></pre> <p>While this DOES move the object from the starting position to the ending, the intermediate steps are not visible. After a delay only the final position is displayed.</p> <p>If I put a <code>MsgBox</code> in the loop then each intermediate position is visible but one must click a distracting, center-positioned box in order to see these.</p> <p>How can I make the flow visible without user interaction and covering of the screen by a modal window?</p>
<p>Try a <code>DoEvents</code> statement before your sleep</p>
<p>Make sure you have Application.Screenupdating set to true...I have a similar macro that animates a shape and I don't need to use DoEvents to update the screen...</p>
35,166
<p>When a getter returns a property, such as returning a <code>List</code> of other related objects, should that list and it's objects be immutable to prevent code outside of the class, changing the state of those objects, without the main parent object knowing?</p> <p>For example if a <code>Contact</code> object, has a <code>getDetails</code> getter, which returns a <code>List</code> of <code>ContactDetails</code> objects, then any code calling that getter:</p> <ol> <li>can remove <code>ContactDetail</code> objects from that list without the <code>Contact</code> object knowing of it.</li> <li>can change each <code>ContactDetail</code> object without the <code>Contact</code> object knowing of it.</li> </ol> <p>So what should we do here? Should we just trust the calling code and return easily mutable objects, or go the hard way and make a immutable class for each mutable class?</p>
<p>It's a matter of whether you should be "defensive" in your code. If you're the (sole) user of your class and you trust yourself then by all means no need for immutability. However, if this code needs to work no matter what, or you don't trust your user, then make everything that is externalized immutable.</p> <p>That said, most properties I create are mutable. An occasional user botches this up, but then again it's his/her fault, since it is clearly documented that mutation should not occur via mutable objects received via getters.</p>
<p>When I was starting out I was still heavily under the influence of HIDE YOUR DATA OO PRINCIPALS LOL. I would sit and ponder what would happen if somebody changed the state of one of the objects exposed by a property. Should I make them read only for external callers? Should I not expose them at all? </p> <p>Collections brought out these anxieties to the extreme. I mean, somebody could remove all the objects in the collection while I'm not looking! </p> <p>I eventually realized that if your objects' hold such tight dependencies on their externally visible properties and their types that, if somebody touches them in a bad place you go boom, your architecture is flawed.</p> <p>There are valid reasons to make your external properties readonly and their types immutable. But that is the corner case, not the typical one, imho.</p>
13,952
<p>Is there a way to distinguish if a script was invoked from the command line or by the web server? </p> <p>(<strong>See <a href="https://stackoverflow.com/questions/173851/what-is-the-canonical-way-to-determine-commandline-vs-http-execution-of-a-php-s">What is the canonical way to determine commandline vs. http execution of a PHP script?</a> for best answer</strong> and more detailed discussion - didn't find that one before posting)</p> <hr> <p>I have a (non-production) server with Apache 2.2.10 and PHP 5.2.6. On it, in a web-accessible directory is my PHP script, <code>maintenance_tasks.php</code>. I would like to invoke this script from the command line or through a HTTP request (by opening in a browser). Is there some variable that allows me to reliably determine how script is invoked?</p> <p>(I already tackled the issues of different views for each type of invocation and HTTP response timeout, just looking for a way of telling the two invocation types apart)</p> <p>I'll be trying different things and add my findings below.</p> <p><strong>Duplicate:</strong> <a href="https://stackoverflow.com/questions/173851/what-is-the-canonical-way-to-determine-commandline-vs-http-execution-of-a-php-s">What is the canonical way to determine commandline vs. http execution of a PHP script?</a></p>
<p><strike>If called from command line, the server variable HTTP_USER_AGENT is not set. I use this constant to define, whether the script is called from command line or not:</p> <pre><code>define("CLI", !isset($_SERVER['HTTP_USER_AGENT'])); </code></pre> <p></strike></p> <p><strong>UPDATE:</strong> Since this answer is still marked as the 'correct' one, I'd like to revise my statement - relying on the "User-Agent" header can be problematic, since it's a user-defined value.</p> <p>Please use <code>php_sapi_name() == 'cli'</code> or <code>PHP_SAPI == 'cli'</code>, as suggested by Eugene/cam8001 in the comments.</p> <p>Thanks for pointing this out!</p>
<p>I've compared the <code>$_SERVER</code> superglobal in both invocations. It seems that <code>$_SERVER['argc']</code> (i.e. number of arguments passed to the script) is only set when running from shell/command line:</p> <pre><code>&lt;?php if (isset($_SERVER['argc'])) { define('CLI', true); } else { define('CLI', false); } </code></pre> <p>That seems to work both on Linux and Windows hosts. (First I thought about checking for some of the environment variables, but those are different for every operating system. Also, all the <code>$_SERVER['HTTP_*']</code> headers are missing in the CLI version, but I'm not sure if that's reliable enough.)</p>
44,678
<p>I'm trying to read a Paradox 5 table into a dataset or simular data structure with the view to putting it into an SQL server 2005 table. I've trawled google and SO but with not much luck. I've tried ODBC:</p> <pre><code>public void ParadoxGet() { string ConnectionString = @"Driver={Microsoft Paradox Driver (*.db )};DriverID=538;Fil=Paradox 5.X;DefaultDir=C:\Data\;Dbq=C:\Data\;CollatingSequence=ASCII;"; DataSet ds = new DataSet(); ds = GetDataSetFromAdapter(ds, ConnectionString, "SELECT * FROM Growth"); foreach (String s in ds.Tables[0].Rows) { Console.WriteLine(s); } } public DataSet GetDataSetFromAdapter(DataSet dataSet, string connectionString, string queryString) { using (OdbcConnection connection = new OdbcConnection(connectionString)) { OdbcDataAdapter adapter = new OdbcDataAdapter(queryString, connection); connection.Open(); adapter.Fill(dataSet); connection.Close(); } return dataSet; } </code></pre> <p>This just return the error </p> <blockquote> <p>ERROR [HY000] [Microsoft][ODBC Paradox Driver] External table is not in the expected format.</p> </blockquote> <p>I've also tired OELDB (Jet 4.0) but get the same External table is not in the expected format error.</p> <p>I have the DB file and the PX (of the Growth table) in the Data folder... Any help would be much appriciated. </p>
<p>I've had the same error. It appeared when I started my C# project on Win2008 64 (previos OS was Win2003 32). Also I found out that it worked fine in console apps and gave different errors in winforms. It seems that problem comes from the specifics of 32 ODBC driver working on 64-bit systems. My solution was:</p> <pre><code>// Program.cs static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // it is important to open paradox connection before creating // the first form in the project if (!Data.OpenParadoxDatabase()) return; Application.Run(new MainForm()); } </code></pre> <p>The connectionstring is common:</p> <pre><code>string connStr = @"Driver={{Microsoft Paradox Driver (*.db )}};DriverID=538; Fil=Paradox 7.X;DefaultDir=C:\\DB;Dbq=C:\\DB; CollatingSequence=ASCII;"; </code></pre> <p>After opening connection you may close it in any place after creating first Form (if you need to keep DB closed most of time), for example:</p> <pre><code>private void MainForm_Load(object sender, EventArgs e) { Data.CloseParadoxDatabase(); } </code></pre> <p>After doing that you may open and close connection every time you want during execution of your application and you willn't get any exceptions.</p>
<p>This isn't an answer, but more of a question: any particular reason you're trying to use C# to do the data manipulation as opposed to using SQL Server tools to load the data directly? Something like DTS or SSIS would seem like a better tool for the job.</p>
39,217
<p>I have some problems on a site with the concurrent access to a list. This list keeps a cart of items, and multiple deletes are crashing the site. <strong>Which is the best method to sync them?</strong> Is a lock enough? The lock option seems to be ugly because the code is spread all over the place and is pretty messy.</p> <p>Update: This is a list implemented like this: public class MyList : List&lt; SomeCustomType> { }</p> <p>This is a legacy site so not so many modifications are allowed to it. How should I refactor this in order to safely lock when iterating over it ?</p> <p>any idea!</p>
<p>So is this in-memory list shared between requests? That sounds like a potential cause of problems even when you've got locking. Mutable shared collections should generally be avoided, IME.</p> <p>Note that if you <em>do</em> decide to synchronize, you'll need to do things like locking the list for the whole course of iterating over it and other compound operations. Just locking on each specific access isn't good enough.</p>
<p>@Samuel That's exactly the point: You can NOT correct a problem like this just by modifying the existing class. Nevermind that the <code>class extends List&lt;T&gt;</code>, which in keeping with MS ways mostly avoids virtual methods (only where MS intends us to override do they make it virtual, which mostly makes sense but can make life more difficult in situations where you kinda need a hack). Even if it embedded the <code>List&lt;T&gt;</code> and all access to it went through code you can change, you could not simply modify this code adding locks to solve the problem.</p> <p>Why? Well, iterators for one thing. A collection cannot merely not be modified between each access to the collection. It cannot be modified during the entire enumeration.</p> <p>In reality, synchronization is a complex matter and depends on what the list really is and what sorts of things need to be true at all times in a system. </p> <p>To illustrate, here's a hack abusing IDisposable. This <em>embeds</em> the list and redeclares whatever functionality of the list that is used somewhere, so that access to the list can be synchronized. In addition, it does <em>not</em> implement IEnumerable. Instead, the only way to get access to enumerate over the list is via a method that returns a disposable type. This type enters the monitor when created and exits it again when disposed. This ensures the list is not accessible during iteration. However, this still isn't really enough, as my example use will illustrate.</p> <p>First the hacked list:</p> <p><code> public class MyCollection { object syncRoot = new object(); List list = new List();</p> <pre><code>public void Add(T item) { lock (syncRoot) list.Add(item); } public int Count { get { lock (syncRoot) return list.Count; } } public IteratorWrapper GetIteratorWrapper() { return new IteratorWrapper(this); } public class IteratorWrapper : IDisposable, IEnumerable&lt;T&gt; { bool disposed; MyCollection&lt;T&gt; c; public IteratorWrapper(MyCollection&lt;T&gt; c) { this.c = c; Monitor.Enter(c.syncRoot); } public void Dispose() { if (!disposed) Monitor.Exit(c.syncRoot); disposed = true; } public IEnumerator&lt;T&gt; GetEnumerator() { return c.list.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } </code></pre> <p>} </code></p> <p>Then a console app using it:</p> <p><code> class Program { static MyCollection strings = new MyCollection();</p> <pre><code>static void Main(string[] args) { new Thread(adder).Start(); Thread.Sleep(15); dump(); Thread.Sleep(125); dump(); Console.WriteLine("Press any key."); Console.ReadKey(true); } static void dump() { Console.WriteLine(string.Format("Count={0}", strings.Count).PadLeft(40, '-')); using (var enumerable = strings.GetIteratorWrapper()) { foreach (var s in enumerable) Console.WriteLine(s); } Console.WriteLine("".PadLeft(40, '-')); } static void adder() { for (int i = 0; i &lt; 100; i++) { strings.Add(Guid.NewGuid().ToString("N")); Thread.Sleep(7); } } </code></pre> <p>} </code></p> <p>Note the "dump" method: It access Count, which is meaninglessly locking the list in an attempt to make it "thread safe", and then iterates through the items. But there is a race condition between the Count getter (which locks, gets the count, then releases) and the using statement. So it may not dump the number of items it things it does.</p> <p>Here, it may not matter. But what if the code instead did something like:</p> <pre><code>var a = new string[strings.Count]; for (int i=0; i &lt; strings.Count; i++) { ... } </code></pre> <p>Or even more likely to mess things up:</p> <pre><code>var n = strings.Count; var a = new string[n]; for (int i=0; i &lt; n; i++) { ... } </code></pre> <p>The former will blow up if items are concurrently added to the list. The latter is not going down well if items are removed from the list. And in both cases the <em>semantics</em> of the code may not be unaffected by changes to the list, even if the changes don't cause the code to crash. In the first case, perhaps items are removed from the list, causing the array not to be filled. Subsequently something far removed in code crashes because of null values in the array. </p> <p>The lesson to take from this is: Shared state can be very tricky. You need an <em>upfront</em> plan and you need to have a strategy for how you're going to ensure the meaning is right. </p> <p>In each of these cases, correct operation would be achieved only by making sure the lock spans all the related operations. There could be lots of other statements in between and the lock could span many method calls and/or involve many different objects. There is no magic bullet that allows these problems to be fixed merely by modifying the collection itself, because the <em>correct</em> synchronization depends on what the collection <em>means</em>. Something like a cache of readonly objects can probably be synchronized only with respect to <code>add/remove/lookup</code>, but if the collection itself is supposed to represent some meaningful/important concept, this will never be sufficient.</p>
22,573
<p>how can I check at runtime home many parameters a method or a function have in PHP.</p> <p>example</p> <pre> class foo { function bar ( arg1, arg2 ){ ..... } } </pre> <p>I will need to know if there is a way to run something like</p> <pre> get_func_arg_number ( "foo", "bar" ) </pre> <p>and the result to be</p> <pre> 2 </pre>
<p>You need to use <a href="http://php.net/oop5.reflection" rel="noreferrer">reflection</a> to do that.</p> <pre><code>$method = new ReflectionMethod('foo', 'bar'); $num = $method-&gt;getNumberOfParameters(); </code></pre>
<p>I believe you are looking for func_num_args()</p> <p><a href="http://us3.php.net/manual/en/function.func-num-args.php" rel="nofollow noreferrer">http://us3.php.net/manual/en/function.func-num-args.php</a></p>
45,120
<p>The standard way to load an image in a J2ME application is using the Image.createImage method and the recommended image format is PNG.</p> <p>Now, the J2ME specs dont lay down any restrictions on the implementation of this method or the in memory representation of an Image so, each vendor has a different implementation. </p> <p>Motorola in particular has this really crappy implementation where in the PNG is completely decoded into ARGB byte array at the time of image creation. This means that an 8K png with dimensions 176x208 takes up a peak memory of about 170K to load and the memory utilized by the Image object itself is about 145K! On other phones like Nokia, Sony Ericsson etc, the same image only takes about 16K to load and store in memory.I dont know what smart optimizations they use, but for some incomprehensible reason, Motorola's JVM does not.</p> <p>This is wreaking havoc in my J2ME app, making it almost impossible to run a decent version of it on Motorola phones. I tried various workarounds like using a gzip'd ARGB byte array of the image and deflating it during paint, but that causes the paint to slow down by a factor of 10! </p> <p>Anyone know of a workaround to this issue? An open source PNG image decoder for J2ME with the smarts that Motorola lacks? Or is there something that can be done to the PNG image to reduce its in memory footprint? (I currently used Indexed mode PNG) Any pointers at all would be welcome.. </p> <p>Gowri</p>
<p>One thing on Sony Ericsson. Don't give them so much credit. They take (image_width x image_height x bytes_per_pixel) of memory as well when loading images. </p> <p>From the SE J2ME developer doc, "<em>All images are stored in phone memory in a 16-bit per pixel RGB format, possibly with a 1-bit or 8-bit per pixel alpha channel.</em>" So, at least 2 bytes. The difference is that Sony Ericsson phones (I can't speak for Nokia) have a separate memory block for images that gets filled first before loading images in the heap (you can see this by wrapping the load with Runtime.getRuntime().freeMemory()...the heap size will increase by only a couple of bytes, which is the size of the new Object).</p> <p>This isn't defending Motorola's as I certain had my troubles porting from SE phones to Motorola's, but it's not because SE was able to figure out a way to store images in heap in a much more optimized way. Motorola just stores everything in the heap, and that's why you run out faster.</p> <p>The smaller images is a good idea, not only during the decoder part, but from a heap fragmentation point of view. It will allow the images to fit in smaller blocks of memory instead of a large continuous block. </p>
<p>PNG's tend to be bloaty.</p> <p>Why not use gif instead.</p> <p><a href="http://www.ddj.com/mobile/184406435;jsessionid=SBUQN2ECITM5OQSNDLOSKHSCJUNN2JVN?_requestid=76071" rel="nofollow noreferrer">http://www.ddj.com/mobile/184406435;jsessionid=SBUQN2ECITM5OQSNDLOSKHSCJUNN2JVN?_requestid=76071</a></p>
33,236
<p>Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?</p>
<pre><code>var qualityEncoder = Encoder.Quality; var quality = (long)&lt;desired quality&gt;; var ratio = new EncoderParameter(qualityEncoder, quality ); var codecParams = new EncoderParameters(1); codecParams.Param[0] = ratio; var jpegCodecInfo = &lt;one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = "image/jpeg"&gt;; bmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG </code></pre>
<p>You can try:</p> <pre><code>Bitmap.InterpolationMode = InterpolationMode.HighQualityBicubic; </code></pre> <p>and</p> <pre><code>Bitmap.CompositingQuality = CompositingQuality.HighQuality; </code></pre> <p>Which does keep the quality fairly high, but not the highest possible.</p>
6,303
<p>Here's an example:</p> <pre><code>&gt;git status # On branch master nothing to commit (working directory clean) &gt;git checkout -b test-branch &gt;vi test.c &gt;git add test.c &gt;git commit -m "modified test.c" &gt;vi README &gt;git add README &gt;git commit -m "modified README" </code></pre> <p>Now I want to do a '<code>git rebase -i</code>' that will let me rebase all commits for this branch. Is there something like '<code>git rebase -i HEAD~MASTER</code>' or similar. I figure I could do '<code>git rebase -i HEAD~2</code>', but I really don't want to have to count how many commits have been made. I could also do '<code>git rebase -i sha1</code>' but I don't want to comb through git log to find the first commit sha1. Any ideas?</p>
<p>Have you tried: <code>git rebase -i master</code>?</p>
<pre><code>git rebase -i --onto @{u}... @{u} </code></pre> <p>Interactive rebase starting from the single merge point of HEAD and its upstream including all commits in HEAD that are not in its upstream.</p> <p>In other words exactly what you want.</p>
47,507
<p>When compiling from source, I never know which configure flags to use to optimize the compilation for my environment. Assume the following hardware/OS:</p> <ul> <li>Single Core, 2 GHz Intel</li> <li>512MB Ram</li> <li>Debian 4</li> </ul> <p>I usually just go with </p> <p><code>./configure --prefix=/usr/local</code></p> <p>Should I be doing anything else?</p>
<p>I always use Debian packages. Compiling from sources can break your development environment during libraries conflicts and such problems are hard to detect.</p>
<p>You might want to check those few options out, which may be required by a Ruby On Rails environment, in which case they should be compiled. Just make sure the directory corresponds to your current settings.</p> <p>--with-openssl-dir=/usr --with-readline-dir=/usr --with-zlib-dir=/usr</p>
4,354
<p>In one of my projects I need to build an ASP.NET page and some of the controls need to be created dynamically. These controls are added to the page by the code-behind class and they have some event-handlers added to them. Upon the PostBacks these event-handlers have a lot to do with what controls are then shown on the page. To cut the story short, this doesn't work for me and I don't seem to be able to figure this out.</p> <p>So, as my project is quite involved, I decided to create a short example that doesn't work either but if you can tweak it so that it works, that would be great and I would then be able to apply your solution to my original problem.</p> <p>The following example should dynamically create three buttons on a panel. When one of the buttons is pressed all of the buttons should be dynamically re-created except for the button that was pressed. In other words, just hide the button that the user presses and show the other two.</p> <p>For your solution to be helpful you can't statically create the buttons and then use the Visible property (or drastically change the example in other ways) - you have to re-create all the button controls dynamically upon every PostBack (not necessarily in the event-handler though). This is not a trick-question - I really don't know how to do this. Thank you very much for your effort. Here is my short example:</p> <h2>From the Default.aspx file:</h2> <pre><code>&lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:Panel ID="ButtonsPanel" runat="server"&gt;&lt;/asp:Panel&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <h2>From the Default.aspx.cs code-behind file:</h2> <pre><code>using System; using System.Web.UI; using System.Web.UI.WebControls; namespace DynamicControls { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { AddButtons(); } protected void AddButtons() { var lastClick = (string) Session["ClickedButton"] ?? ""; ButtonsPanel.Controls.Clear(); if (!lastClick.Equals("1")) AddButtonControl("1"); if (!lastClick.Equals("2")) AddButtonControl("2"); if (!lastClick.Equals("3")) AddButtonControl("3"); } protected void AddButtonControl(String id) { var button = new Button {Text = id}; button.Click += button_Click; ButtonsPanel.Controls.Add(button); } private void button_Click(object sender, EventArgs e) { Session["ClickedButton"] = ((Button) sender).Text; AddButtons(); } } } </code></pre> <p>My example shows the three buttons and when I click one of the buttons, the pressed button gets hidden. Seems to work; but after this first click, I have to click each button <strong>TWICE</strong> for it to get hidden. !?</p>
<p>I think that you have to provide the same ID for your buttons every time you add them like this for example (in first line of <code>AddButtonControl</code> method):</p> <pre><code>var button = new Button { Text = id , ID = id }; </code></pre> <hr> <p><strong>EDIT</strong> - My solution without using session:</p> <pre><code>public partial class _Default : Page { protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); AddButtons(); } protected void AddButtons() { AddButtonControl("btn1", "1"); AddButtonControl("btn2", "2"); AddButtonControl("btn3", "3"); } protected void AddButtonControl(string id, string text) { var button = new Button { Text = text, ID = id }; button.Click += button_Click; ButtonsPanel.Controls.Add(button); } private void button_Click(object sender, EventArgs e) { foreach (Control control in ButtonsPanel.Controls) control.Visible = !control.Equals(sender); } } </code></pre>
<p>AFAIK, creating of controls should not be placed in Page_Load but in Page_PreInit (ViewState and SessionState is loaded before Page_Load but after Page_PreInit).</p> <p>With your problem, I would suggest to debug the AddButtons function to find out what exactly (and when) is stored in Session["ClickedButton"]. Then, you should be able to figure out the problem.</p>
31,816
<p>Let's say we have</p> <pre><code>public interface ITimestampProvider { DateTime GetTimestamp(); } </code></pre> <p>and a class which consumes it</p> <pre><code>public class Timestamped { private ITimestampProvider _timestampProvider public Timestamped(ITimestampProvider timestampProvider) { // arg null check _timestampProvider = timestampProvider; } public DateTime Timestamp { get; private set; } public void Stamp() { this.Timestamp = _timestampProvider.GetTimestamp(); } } </code></pre> <p>and a default implementation of:</p> <pre><code>public sealed class SystemTimestampProvider : ITimestampProvider { public DateTime GetTimestamp() { return DateTime.Now; } } </code></pre> <p>Is it helpful or harfmful to introduce this constructor?</p> <pre><code>public Timestamped() : this(new SystemTimestampProvider()) {} </code></pre> <p>This is a general question, i.e. timestamping is not the interesting part.</p>
<p>I think it depends on the scenario, and is basically a function of who the consumer the code is (library vs. application) and whether you're using an IoC container or not.</p> <ul> <li><p>If you're using an IoC container, and this is not part of a public API, then let the container do the heavy lifting, and just have the single constructor. Adding the no-args constructor just makes things confusing, since you'll never use it.</p></li> <li><p>If this is part of a public API, then keep both. If you're using IoC, just make sure your IoC finds the "greediest" constructor (the one with the most arguments). Folks not using IoC, but using your API will appreciate not having to construct an entire dependency graph in order to use your object.</p></li> <li><p>If you're not using an IoC container, but just want to to unit test with a mock, keep the no-args constructor, and make the greedy constructor internal. Add InternalsVisibleTo for your unit test assembly so that it can use the greedy constructor. If you're just unit testing, then you don't need the extra public API surface.</p></li> </ul>
<p>I try to avoid this - there are a few places where I've found it to be a useful design but more often than not I've found it just leads to me making mistakes that can be a little puzzling to work out.</p> <p>The need for the default injected objects is greatly reduced by using a dependency injection container (I use StructureMap) to manage all this wiring - the DI container makes sure that you always get a concrete instance you can use.</p> <p>The only place where I'm still tempted to use the constructor you suggest is in my unit tests but recently I've been getting far greater value out of using fake or mocked objects.</p> <p>There are places where having the default dependant objects is the correct and useful design, but in general I'd say that you are just introducing tight coupling that doesn't add a lot of value.</p>
38,485
<p>We disassembled everything in order to unclog the filament from the tube, but now I can't seem to get the nozzle to screw back in to the hotbed with the PTFE tube in place. Is there some kind of trick? I feel like if the tube were slightly smaller in diameter it would work. I'm using the same tube, just without the filament that had clogged it. Am I just not using enough force?</p> <p><a href="https://i.stack.imgur.com/a8iq4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a8iq4.jpg" alt="enter image description here"></a></p>
<p>I was able to fix my problem so thought I'd post how I solved it for anyone else that is looking for a possible answer:</p> <p>I believe the actual problem was that there was filament hardened inside the nozzle which I couldn't see, so that prevented me from being able to push the PTFE tube into the nozzle deep enough. I reassembled the extruder and heated it up, then using needle nose pliers so I wouldn't burn myself, I held the nozzle to the end to block to heat it up, (I didn't actually screw it in) and the stuck filament melted so I could scrape it out. I also learned from Tang, the Amazon flashforge tech guy, that the tube should be 23mm above the block, so that was helpful to use as a guide. As I read in other places, I then inserted the tube into the block to heat it up, which I think made it slightly more pliable and easier to insert into the nozzle.</p>
<p>I got the same issue before. When you tried to push out the material from the tube, one end of the tube was being pressed. The tube was so soft that the diameter at that end was slightly increased. Hence it was difficult to put the tube back. When you tried to tighten the screw, more force applied and the tube end was pinched more. I got some spare tubes from the supplier. I simply replaced the tube. The PTFE tube could be pulled off from the nozzle.</p>
1,529
<p>Specifically, I am looking to use CA on properties of types other than </p> <ul> <li>integers and doubles</li> <li>CGRect, CGPoint, CGSize, and CGAffineTransform structures</li> <li>CATransform3D data structures</li> <li>CGColor and CGImage references</li> </ul> <p>and in objects other than CALayers or NSViews</p>
<p>If you can do the changes yourself and the class you use is custom, you might want to add a setProgress:(float) f method to your class and use CA to animate it, then modify the desired properties as needed as a function of f.</p> <p>Just do a</p> <pre><code>[[someObject animator] setValue:[NSNumber numberWithFloat:1.0] forKeyPath:@"someCustomProperty.progress"]; </code></pre> <p>or if the object doesn't have an animator, create the correct CAAnimation yourself.</p>
<p>Well, it seems I cannot do that. What I should be doing is [subclassing NSAnimation](<a href="https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/AnimationGuide/Articles/TimingAnimations.html" rel="nofollow noreferrer">https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/AnimationGuide/Articles/TimingAnimations.html</a> subclassing NSAnimation). This will work on a MacOS 10.4+ app, but not on Cocoa Touch, in which I cannot find any alternatives apart from using a NSTimer.</p>
6,986
<p>I received a WSDL file for a web service interface that our system should call somewhere in the future. </p> <p>Until then, I'd like to setup a dummy/mockup web service that does nothing else than to log the web service invocations and return dummy data.</p> <p>What I've done so far is to generate Java objects from the WSDL file.</p> <p>What's the fastest way to setup such a mockup web service when you already have an application server (here: JBoss) running? </p>
<p>We just faced this same problem, and found <a href="http://www.soapui.org/" rel="noreferrer">SoapUI</a> to be the perfect tool. Given a WSDL it'll create a service on your machine you can call, and it allows you to edit the response as you need.</p>
<p>You can use <a href="http://ws.apache.org/axis/java/user-guide.html#WSDL2JavaBuildingStubsSkeletonsAndDataTypesFromWSDL" rel="nofollow noreferrer">Apache Axis's wsdl2java</a> to generate skeleton classes from the WSDL:</p> <blockquote> <p>Just as a stub is the client side of a Web Service represented in Java, a skeleton is a Java framework for the server side. To make skeleton classes, you just specify the &quot;--server-side --skeletonDeploy true&quot; options to WSDL2Java.</p> <p>...</p> <p>The skeleton class is the class that sits between the Axis engine and the actual service implementation.</p> </blockquote> <p>You would effectively be creating your own version of the server-side implementation of the web service. You can then implement the skeleton to return some stub/dummy data, deploy that to your application server, and then make web service calls to your skeleton just as you would to the live web service.</p>
26,053
<p>I've just written a small XBox 360 Wireless Controller managed interface that basically wraps around the low-lever <a href="http://slimdx.mdxinfo.com/wiki/index.php?title=Main_Page" rel="nofollow noreferrer">SlimDX</a> wrapper library and provides a easy, managed API for the XBOX 360 controller.</p> <p>Internally, the class polls the gamepad every N ms, and shoots events as it detects changes in the underlying state of the controller.</p> <p>I'm experiencing some what dead end with timers that is basiclly forcing to choose between the lesser of two evils:</p> <ul> <li><p>Either make my XBox360GamePad class UI framework specific (i.e. support WPF/WinForms will be hard-coded in the class, and the class has to reference these frameworks...)</p></li> <li><p>Make the class completely framework agnostic, but force the users to sprinkle their code with Dispatcher.Invoke / Invoke() calls to be able to update UI according to the events generated.</p></li> </ul> <p>If I choose the latter option (of making the code UI agnostic), then I basically use the "generic" System.Timers.Timer or any timer that has no UI dependency. In that case I end up having events generated/called from a thread that is incapable of directly updating the UI, i.e. in WPF, I would have to issue every update originated form the 360 controller class through the (ugly) use of Dispatcher.Invoke.</p> <p>On the other hand, If I use DispatcherTimer inside the XBox 360 Controller class I have a working component that can update the UI directly with no fuss, but now my whole controller class is coupled to WPF, and it can't be used without being dependent on WPF (i.e. in a pure console app)</p> <p>What I'm kind of looking is a some sort solution that would allow me to be both framework agnostic and also update UI without having to resort to all kinds of Dispatcher.Invoke() techniques... If for example there was a shared base class for all timers, I could somehow inject the timer as a dependency according to the relevant scenario.. Has anyone ever dealt successfully with this sort of problem?</p>
<p>Is a polling architecture the only option?</p> <p>In any case, personally I would restructure the system so that outside world can subscribe to events that is fired from the controller class.</p> <p>If you want the controller to fire the events on the right thread context, then I would add a property for a ISynchronizeInvoke interface, and if this property is non-null inside the controller, use the interface, otherwise just invoke the events directly, on the thread the controller runs on.</p> <p>This would for instance allow you make the entire polling thing into a thread that wakes up every N milliseconds to do its job, or even use event objects to just wait for events (if the 360 controller architecture has something like this).</p>
<p>The 360 controller can only report it's current state. There is no other means to get the state without polling. Using System.Threading.Timer or opening up a new Thread that does Thread.Sleep() is really the same in my view, both of them fulfill the functionality of a UI-less timer class.</p> <p>Thanks for mentioning ISynchronizeInvoke, I've googled some more and found someone that shares my pain and might even have a solution: <a href="https://web.archive.org/web/20210125200028/http://geekswithblogs.net/robp/archive/2008/03/28/why-doesnt-dispatcher-implement-isynchronizeinvoke.aspx" rel="nofollow noreferrer">http://geekswithblogs.net/robp/archive/2008/03/28/why-doesnt-dispatcher-implement-isynchronizeinvoke.aspx</a></p> <p>I'll try his code and keep this thread posted... Thanks for the tip!</p>
37,541
<p>I'm on .NET 2.0, running under Medium Trust (so <a href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx" rel="nofollow noreferrer">TimeZoneInfo</a> and the Registry are not allowed options). I'm asking the user for two dates and a time zone, and would really love to be able to automatically determine whether I need to adjust the time zone for DST. </p> <p>This probably isn't even a valid scenario unless I have some <em>very</em> robust support, a la <a href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx" rel="nofollow noreferrer">TimeZoneInfo</a>, to differentiate between all of the different varieties of Time Zones in the first place.</p>
<p>In .NET 2.0 you have to code this yourself. It involves researching daylight savings time laws in various regions and building that into your own data structures. The problem is somewhat simplified if you only care about a subset of time zones, for example just in the USA, but if you need all global time zones, you have a lot of work to do, and then the code has to be updated every few years when the laws change. Even the new time zone objects in the latest version of .NET will require windows updates to keep them correct as laws change.</p> <p>Look <a href="http://aa.usno.navy.mil/faq/docs/daylight_time.php" rel="nofollow noreferrer">here</a>, <a href="http://en.wikipedia.org/wiki/Daylight_saving_time" rel="nofollow noreferrer">here</a>, and <a href="http://www.timeanddate.com/time/aboutdst.html" rel="nofollow noreferrer">here</a> for more info.</p>
<p>Well, since <code>TimeZoneInfo</code> is excluded, you're probably not going to find a solution in the framework itself (but don't quote me on that).</p> <p>In which case, have you considered reflectoring the <code>TimeZoneInfo</code> class and using what you find there?</p>
6,657
<p>I have a string</p> <pre><code>var s:String = "This is a line \n This is another line."; this.txtHolder.text = s; //.text has \n, not a new line </code></pre> <p>and i want to put it into a text area, but the new line character is ignored. How can i ensure that the text breaks where i want it to when its assigned?</p>
<p>On flex, while coding <code>\n</code> is working well on <code>mxml</code> or any <code>xml</code> to define a line just use <code>&amp;amp;#13;</code> line entity.</p> <p>I mean:</p> <pre><code>lazy&amp;amp;#13;fox </code></pre> <p>gives us</p> <pre><code>lazy&lt;br /&gt; fox </code></pre>
<p>It should work or at the very least <strong>&lt; br \></strong> (without the spaces before the "br") should work if you are using htmlText.</p> <p>I was using XML to fill in the TextArea and since I'm not entirely sure how to use HTML inside of XML (they mention that I should wrap it with CDATA tags) but I just did a simple </p> <pre><code>txt.replace("\\n", "&lt;br/&gt;"); </code></pre> <p>Perhaps there's a better way to go about it but this works out nicely.</p> <p>EDIT: I had a space after the "br"</p>
40,644
<p>If you were to self-fund a software project which tools, frameworks, components would you employ to ensure maximum productivity for the dev team and that the "real" problem is being worked on.</p> <p>What I'm looking for are low friction tools which get the job done with a minimum of fuss. Tools I'd characterize as such are SVN/TortioseSVN, ReSharper, VS itself. I'm looking for frameworks which solve the problems inherient in all software projects like ORM, logging, UI frameworks/components. An example on the UI side would be ASP.NET MVC vs WebForms vs MonoRail.</p>
<ul> <li><strong>Versioning.</strong> <em>Subversion</em> is the popular choice. If you can afford it, <em>Team Foundation Server</em> offers some benefits. If you want to be super-modern, consider a distributed versioning system, such as <em>git</em>, <em>bazaar</em> or <em>Mercurial</em>. Whatever you do, don't use SourceSafe or other lock-based tools, but rather merge-baseed ones. Consider installing both a Windows Explorer client (such as <em>TortoiseSVN</em>) as well as a Visual Studio add-in (such as <em>AnkhSVN</em> or <em>VisualSVN</em>).</li> <li><strong>Issue tracking.</strong> Given that Joel Spolsky is on this site's staff, <em>FogBugz</em> deserves a mention. <em>Trac</em>, <em>Mantis</em> and <em>BugZilla</em> are widespread open-source choices.</li> <li><strong>Continuous integration.</strong> <em>CruiseControl.NET</em> is a popular and open-source choice. There's also <em>Draco.NET</em>.</li> <li><strong>Unit testing.</strong> <em>NUnit</em> is the popular open-source choice. Does the job. Consider installing the <em>TestDriven.NET</em> Visual Studio add-in.</li> </ul> <p>That said, you want to look at the answers to <a href="https://stackoverflow.com/questions/2187/essential-programming-tools">Essential Programming Tools</a> and <a href="https://stackoverflow.com/questions/23490/what-is-your-best-list-of-must-have-development-tools">What is your best list of ‘must have’ development tools?</a>; while not .NET-specific, they should apply anyway.</p>
<p>I'd definitely recommend Coderush+Refactor or Resharper (Coderush being my personal favourite), these tools dramatically reduce the time to go from code in your head to code on the page.</p> <p>For quick development the UI component sets from the likes of Telerik/DevExpress/Infragistics can be good, but in my experience can cause pain further out in the project when you want to refine things more precisely.</p> <p>Regarding frameworks etc I think you'd need to be a bit more specific about the project itself to get any meaningful suggestions.</p>
8,633
<p>In a detailsview, how can I prepopulate one of the textboxes on the insertcommand (When the user clicks insert and the view is insert).</p> <p>I think this would work for codebehind:</p> <p>Dim txtBox As TextBox = FormView1.FindControl("txtbox")</p> <p>txtbox.Text = "Whatever I want"</p> <p>Is this right? What do I need in the aspx (not as sure)? Also, I'm assuming the server-side code will go in the itemcommand or insertcreating event.</p> <p>I have typed this in VB.NET but I am using C# (I can do both so on a language agnostic forum I might type the problem in another language). I am also using a SqlDataSource, with my parameters and insert/delete/edit commands all created.</p> <p>I am trying to generate a random GUID (using the GUID object), which will be prepopulated in the textbox.</p> <p>Also, is the postbackurl property of a button not another way of preserving form state?</p> <p>Thanks</p>
<p>I would update the field in the DetailsView to a TemplateField: </p> <pre><code>&lt;asp:TemplateField&gt; &lt;InsertItemTemplate&gt; &lt;asp:TextBox ID="txtField" runat="server" Text='&lt;%# Bind("GUID") %&gt;'/&gt; &lt;/InsertItemTemplate&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="lblField" runat="server" Text='&lt;%# Bind("GUID") %&gt;'/&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre> <p>Then you have two options: </p> <ul> <li>generate your GUID and insert into your datasource. This may have to be done with SQL since you mentioned using SqlDataSource</li> <li><p>remove the binding and access the controls from code in the DataBound event of your DetailsView </p> <pre><code>Private Sub dv_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles dv.DataBound dim txt as Textbox = dv.FindControl("txtField") txt.Text = GenerateGUID() End Sub </code></pre></li> </ul>
<p>I'm guessing you need to use one of detailsview events. Hook up to ItemCommand, ModeChanging or ModeChanged events and fill your value there.</p>
34,182
<p>When I download my program from my website to my windows 2003 machine, it has a block on it and you have to right click on the exe, then properties, then select the button "Unblock".</p> <p>I would like to add detection in my installer for when the file is blocked and hence doesn't have enough permissions. </p> <p>But I can't eaisly reproduce getting my exe in this state where it needs to be unblocked.</p> <p>How can I get the unblock to appear on my exe so I can test this functionality?</p>
<p>This is done using NTFS File Streams. There is a stream named "Zone.Identifier" added to downloaded files. When IE7 downloads certain types of file that stream contains:</p> <pre><code>[ZoneTransfer] ZoneId=3 </code></pre> <p>The simplest way to set it is to create a text file with those contents in it, and use more to add it to the alternate stream.</p> <p>Zone.Identifier.txt:</p> <pre><code>[ZoneTransfer] ZoneId=3 </code></pre> <p>Command:</p> <pre><code>more Zone.Identifier.txt &gt; file.exe:Zone.Identifier </code></pre> <p>Then, the way for you to check it would be to try to open the Zone.Identifier stream and look for ZoneId=3, or simply assume that if the stream exists at all that your user will receive that warning.</p> <p>It's also important to note that this has nothing to do with permissions. Administrators see the same warning; it's to do entirely with the source and type of file. The entire stream goes away when users uncheck the "Always ask before opening this file" box and then click Run.</p>
<p>Thanks for this it helped me a lot.</p> <p>You can make the process even easier if you create a batch file with the contents.</p> <pre><code>echo [ZoneTransfer] &gt; Zone.Identifier echo ZoneId=3 &gt;&gt; Zone.Identifier more Zone.Identifier &gt; %1:Zone.Identifier </code></pre> <p>This will generate the Zone.Identifier for you and mark the file accordingly.</p> <p>To run it just supply the file name e.g. if the file is called mark.bat</p> <pre><code>mark.bat myfile.txt </code></pre>
16,420
<p>How does googlebot treat iframes? Does it follow the src attribute like a link? Is the iframe content analyzed as if it was part of the page where it is included?</p>
<blockquote> <p>IFrames are sometimes used to display content on web pages. <strong>Content displayed via iFrames may not be indexed</strong> and available to appear in Google's search results. We recommend that you avoid the use of iFrames to display content. If you do include iFrames, make sure to <strong>provide additional text-based links to the content they display, so that Googlebot can crawl and index this content.</strong></p> </blockquote> <p>From the <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=72746&amp;query=iframe&amp;topic=&amp;type=" rel="noreferrer">Google Webmaster Guidelines</a></p> <p>The iframe content isn't included in the original page. If you want the content indexed, try providing a text link to the src page. If you don't want it indexed, use the meta robots tag or robots.txt to restrict the file.</p>
<p>Anecdotal evidence suggests it treats it like a link (so you can end up with a page designed to be viewed inside the frame being loaded on its own via a link from a search engine).</p>
17,674
<p>I've never used the Global Temporary Tables however I have some questions how they will work in a php environment.</p> <p>How is data shared: Assuming persistent connections to oracle through php using oci8. Is the data tied to a database id? is it done based on the Apache httpd demons? Or is each individual request unique?</p> <p>When is the data for the session cleared from the global temporary table? I'm assuming (or rather hoping) that its done when the php script exits. Alternatively if not I'm assuming I'll need to remove it before script exit.</p>
<p>The global temporary table is simply the logical definition of a table structure (Name, column names, column data types etc). When a session references it by inserting data, a data segment is created in a temporary tablespace to hold only that session's data. Different sessions can therefore reference the same logical table definition because they each have their own dedicated data segment which can be purged easily on commit or when the session disconnects without affecting other sessions.</p> <p>The purging of the data in the GTT can either be on commit or when the session ends, depending on the option with which it was created. In either case you do not have to attend to the purging yourself before disconnecting.</p> <p>A useful alternative to the GTT is the subquery factoring clause ("WITH"), in which you can create multiple relations that can reference those previously declared in that SQL statement. These can be materialised as a data segment in a temporary tablespace either automatically by Oracle when they exceed a certain memory usage, or manually by using the MATERIALIZE optimizer hint.</p>
<p>If I remember correct, the data in global temporary tables is available only from one active session and only for this active session (I mean session = connection). So you can see only data which was inserted before in active session. Therefore I belive, this data is cleared after closing session. No matter which language are you using.</p> <p>At least I think so. :D</p> <p>As is it written here: <a href="http://www.oracle-base.com/articles/8i/TemporaryTables.php" rel="nofollow noreferrer">http://www.oracle-base.com/articles/8i/TemporaryTables.php</a></p> <p>The data in a global temporary table is private, such that data inserted by a session can only be accessed by that session.</p> <p>Data in temporary tables is automatically delete at the end of the database session, even if it ends abnormally.</p> <p>Sorry for my bad english.</p>
14,974
<p>I'm having a problem running a VS 2005 app on some machines and not others. I looked up the error message on google and found a post by someone who had the same error and fixed it by uninstalling and reinstalling the .NET framework. When I try to do that, Windows won't let me because it is in use.</p> <p>Am I expected to uninstall everything that is using the framework first, then uninstall the framework, then reinstall, etc.? Does anyone know of an easier way?</p>
<p>Check out Aaron Stebner's <a href="https://web.archive.org/web/20160301085724/http://blogs.msdn.com:80/b/astebner/archive/2008/08/28/8904493.aspx" rel="nofollow noreferrer">.NET Framework Cleanup Tool</a>. Works quite nicely.</p>
<p>Boot into safe mode and uninstall the framework from add/remove programs.</p>
19,950
<p>We have a custom section in my app.config file related to our IoC container class. How can I get intellisense when editing the config file for this section, as well as getting rid of the compiler messages informing me of the missing schema.</p> <p>I found this question here: <a href="https://stackoverflow.com/questions/229155/appconfig-configsections-custom-settings-can-not-find-schema-information">app.config configSections custom settings can not find schema information</a>, but I don't understand if it applies to my problem or not, and how to use the answer there if it does.</p> <p>I also found this page <a href="http://www.radsoftware.com.au/articles/intellisensewebconfig.aspx" rel="nofollow noreferrer">How to get Intellisense for Web.config and App.config in Visual Studio .NET</a>, but it says to remove the xmlns attribute before running the application. Is that really the only/best way?</p> <p>Here is an example of a simple file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;section name="ServiceContainers" type="LVK.IoC.RegistrationsSectionHandler, LVK"/&gt; &lt;/configSections&gt; &lt;ServiceContainers&gt; &lt;Registration type="DatabaseConnection" class="DatabaseConnection"&gt; &lt;Parameter name="connectionString" type="System.String" value="TYPE=MSSQL2000;SERVER=localhost;DATABASE=db"/&gt; &lt;/Registration&gt; &lt;/ServiceContainers&gt; &lt;/configuration&gt; </code></pre> <p>Basically I would like to be able to type <code>&lt;R</code> inside the <code>&lt;ServiceContainers&gt;</code> node, and get Registration suggested to me in the intellisense dropdown, as well as the appropriate attributes for it.</p>
<p>XML Intellisense will not automatically work for a custom configuration section. </p> <p>Visual Studio may report warnings on compilation complaining that the attributes of the custom configuration section are not defined. These warnings may be ignored. </p> <p>If you want XML IntelliSense support for a custom configuration section (or if you just want the 'schema not found' warnings to disappear), add the following line to your DotNetConfig.xsd file immediately after the first &lt;xs:schema ...&gt; line (which is typically the second line in the DotNetConfig.xsd file). </p> <pre><code>&lt;xs:include schemaLocation="YOUR_DIRECTORY\namespace.assemblyname.xsd"/&gt; </code></pre> <p>The DotNetConfig.xsd file can be found in your Visual Studio 8 (or 9) installation directory in the Xml\Schemas subdirectory. </p>
<p>If you don't want to modify your DotNetConfig.xsd you could add the xsd configuration "inline".</p> <p>In your case add the following attributes to the custom section</p> <pre><code>&lt;ServiceContainers xmlns="your_xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="your_xmlns location_of_your_schema"&gt; &lt;Registration .... &lt;/ServiceContainers&gt; </code></pre> <p>This is useful while testing an xsd locally because <em>location_of_your_schema</em> could be a local path and when you are ready to production change <em>location_of_your_schema</em> to the public url of the xsd file.</p> <p>Note that the <em>xsi:schemaLocation</em> attribute must contain pairs of strings separated by spaces where the first string in each pair is a namespace URI and the second string is the location of a schema. </p>
49,519
<p>In Windows for ASP, you can get it perfmon, but...</p> <p>How to get <strong>"requests per second"</strong> for Apache in Linux?</p>
<p>In realtime, or can you use <a href="http://www.cyberciti.biz/faq/apache-server-status/" rel="noreferrer">mod_status</a>?</p> <p>And apparently, there is a version of <a href="http://www.linuxhaxor.net/2008/01/15/real-time-display-of-apache-usage/" rel="noreferrer">top for apache</a>...</p>
<p>mod_status is the one! if you call it with:</p> <p>http://{ip}/server-status?refresh=1&amp;auto-refresh=true</p> <p>Then it auto refreshes every 2 seconds so you can see a constant realtime view :-)</p>
44,962
<p>I'm trying to read a value from a file and use it in a subsequent command.</p> <p>I have a file called <code>AppServer.pid</code> which contains the process id of my app server (just the number, it's not a properties file or anything like that).</p> <p>The app server is hanging, so I want to take this value and pass it to the kill command. So my script will be something like</p> <pre><code>SET VALUE_FROM_FILE=AppServer.pid # or something taskkill /pid %VALUE_FROM_FILE% /f </code></pre> <p>Is there a convenient way to do this in Windows scripting?</p>
<p>This works:</p> <pre><code>SET /P VALUE_FROM_FILE= &lt; AppServer.pid taskkill /pid %VALUE_FROM_FILE% /f </code></pre> <p>The /P parameter used with SET allows you to set the value of a parameter using input from the user (or in this case, input from a file)</p>
<pre><code>for /f %%G in (appid.txt) do (SET PID=%%G) echo %PID% taskkill etc here... </code></pre> <p>This might help !</p>
38,179
<p>I would like to sort an array in ascending order using <code>C/C++</code>. The outcome is an array containing element indexes. Each index is corespondent to the element location in the sorted array.</p> <p><strong>Example</strong></p> <pre><code>Input: 1, 3, 4, 9, 6 Output: 1, 2, 3, 5, 4 </code></pre> <p><strong>Edit:</strong> I am using shell sort procedure. The duplicate value indexes are arbitrarily chosen based on which duplicate values are first in the original array.</p> <h3>Update:</h3> <p>Despite my best efforts, I haven't been able to implement a sorting algorithm for an array of pointers. The current example won't compile.</p> <p>Could someone please tell me what's wrong?</p> <p>I'd very much appreciate some help!</p> <pre><code>void SortArray(int ** pArray, int ArrayLength) { int i, j, flag = 1; // set flag to 1 to begin initial pass int * temp; // holding variable orig with no * for (i = 1; (i &lt;= ArrayLength) &amp;&amp; flag; i++) { flag = 0; for (j = 0; j &lt; (ArrayLength - 1); j++) { if (*pArray[j + 1] &gt; *pArray[j]) // ascending order simply changes to &lt; { &amp;temp = &amp;pArray[j]; // swap elements &amp;pArray[j] = &amp;pArray[j + 1]; //the problem lies somewhere in here &amp;pArray[j + 1] = &amp;temp; flag = 1; // indicates that a swap occurred. } } } }; </code></pre>
<p>Since you're using C++, I would do it something like this. The <code>SortIntPointers</code> function can be any sort algorithm, the important part is that it sorts the array of pointers based on the <code>int</code> that they are pointing to. Once that is done, you can go through the array of pointers and assign their sorted index which will end up in the original position in the original array.</p> <pre><code>int* intArray; // set somewhere else int arrayLen; // set somewhere else int** pintArray = new int*[arrayLen]; for(int i = 0; i &lt; arrayLen; ++i) { pintArray[i] = &amp;intArray[i]; } // This function sorts the pointers according to the values they // point to. In effect, it sorts intArray without losing the positional // information. SortIntPointers(pintArray, arrayLen); // Dereference the pointers and assign their sorted position. for(int i = 0; i &lt; arrayLen; ++i) { *pintArray[i] = i; } </code></pre> <p>Hopefully that's clear enough.</p>
<p>Well, there's a trival n^2 solution.</p> <p>In python:</p> <pre><code>newArray = sorted(oldArray) blankArray = [0] * len(oldArray) for i in xrange(len(newArray)): dex = oldArray.index(newArray[i]) blankArray[dex] = i </code></pre> <p>Depending on how large your list is, this may work. If your list is very long, you'll need to do some strange parallel array sorting, which doesn't look like much fun and is a quick way to introduce extra bugs in your code.</p> <p>Also note that the above code assumes unique values in oldArray. If that's not the case, you'll need to do some post processing to solve tied values.</p>
3,441
<p>Does anyone know how to move the "Solution Explorer" tab in Visual Studio 2005? It's on the left, and I can't move it to the right.</p> <p>Thanks,</p> <p>Alan</p>
<p>Click on the title bar, and drag it to the right portion of the screen. Eventually you'll see a compas like structure popup. Make sure you hover over the right area and let go of the mouse button. That will bind it to the right side.</p>
<p>Go to View-> Appearance -> Move Side Bar Left</p>
41,666
<p>I've seen a lot of example c++ code that wraps function calls in a FAILED() function/method/macro. Could someone explain to me how this works? And if possible does anyone know a c# equivalent?</p>
<p>It generally checks COM function errors. But checking any function that returns a <code>HRESULT</code> is what it's meant for, specifically. <code>FAILED</code> returns a true value if the <code>HRESULT</code> value is negative, which means that the function failed ("error" or "warning" severity). Both <code>S_OK</code> and <code>S_FALSE</code> are >= 0 and so they are not used to convey an error. With "negative" I mean that the high bit is set for <code>HRESULT</code> error codes, <em>i.e.</em>, their hexadecimal representation, which can be found in, <em>e.g.</em>, winerror.h, begins with an 8, as in 0x8000FFFF.</p>
<blockquote> <p>And if possible does anyone know a c# equivalent?</p> </blockquote> <p>You won't actually need that in C#, unless you're using COM objects. Most .NET functions either already return a (more or less) meaningful value (i.e. null, false) or throw an exception when they fail.</p> <p>If you're directly accessing a COM object, you can define a simple Failed function that does what the macro in unwind's post does. Define that locally (protected/private), since the messy COM details shouldn't be visible in your app anyway.</p> <p>In case you didn't know, there's also a SUCCEEDED macro in COM. No need to test for failure :)</p>
49,410
<p>In OS X, in order to quickly get at menu items from the keyboard, I want to be able to type a key combination, have it run a script, and have the script focus the Search field in the Help menu. It should work just like the key combination for Spotlight, so if I run it again, it should dismiss the menu. I can run the script with Quicksilver, but how can I write the script?</p>
<p>Here is the script I came up with.</p> <pre><code>tell application "System Events" tell (first process whose frontmost is true) click menu "Help" of menu bar 1 end tell end tell </code></pre>
<p>Here is the script I came up with.</p> <pre><code>tell application "System Events" tell (first process whose frontmost is true) click menu "Help" of menu bar 1 end tell end tell </code></pre>
9,477
<p>I have a bunch of objects in my application (Organisations, Individuals, Orders, etC) and I need a nice clean way to decide which users can and can't view/edit these objects. User have a range of permissions such as 'Can edit own contacts' and 'Can view team's contacts' and can also be members of groups such as 'Account Manager' so various things need to be checked (Is this user an account manager? Is this contact managed by this users team? Can this user edit his teams contacts?) before it can be decided if they have access to the object.</p> <p>Previously most of the logic was inline but as it becomes more complex I've decided that it's best to move it out to new classes such as OrganisationSecurity, OrderSecurity, etc and creating methods such as CanEdit on them.</p> <p>Is this the correct way to go? Any gotchas I should be careful of? How do you handle this?</p> <p>Thanks</p>
<p>Check out <a href="http://www.securitypatterns.org/patterns.html" rel="nofollow noreferrer">Security Patterns</a>, especially in the areas about authentication and authorization. </p>
<p>Google for the term entitlements management and XACML. This will get you pointed in a better direction.</p>
38,755
<p>s it possible to do the following in subsonic.</p> <p>SELECT * FROM TABLE1</p> <p>WHERE Column1 > Column2 or Column1 &lt; Colum3</p> <p>All examples that I've seen assume you now a value to pass to the where clause. I'm trying to do this without creating a view.</p> <p>Thanks</p>
<p>If it's in our stack I can't find it :). It would be a good thing to add though :). You can, for now, use an Inline query to simply execute the statement you wrote (it takes straight SQL). I know it's fugly but...</p> <p>Rick - if you did get that to work I'd be interested in how. "Col2" will try and be parsed to a type and your query will fail.</p>
<p>Yes it is.</p> <pre><code>Dim TableList As Generic.List(Of Database.Table1) = _ New SubSonic.Select().From("Table1"). _ Where("Col1").IsGreaterThan("Col2"). _ Or("Col1").IsLessThan("Col3").ExecuteTypedList(Of Database.Table1)() </code></pre>
30,292
<p>I have a WordPress site (2.6.2) in which I have set the Home page to a static page instead of the normal posts page. The ID of this page is 2, so in the WordPress template I have changed the <code>wp_list_pages</code> to look like this:</p> <pre><code>&lt;?php wp_list_pages('exclude=2&amp;title_li=&amp;depth=1' ); ?&gt; </code></pre> <p>this works fine, but now the Home page doesn't get "lit up" when it's selected (because in fact it's page_id 2 that is selected, and it doesn't show in the menu). Is there any easy way around this?</p> <p>If not, in broad outlines, what's the hard way around this? Make my own version of the <code>wp_list_pages</code> function?</p> <p>Thanks!</p>
<p>Setting a static page as the front page doens't highlight the menu link, which is at the heart of the question.</p> <p>So, you could server-side customize (hack) the wp_list_pages function, but here's a client-side option if you so choose:</p> <p>Use the jQuery library (conveniently it comes with WP 2.2+), call:</p> <pre><code>wp_enqueue_script('jquery'); </code></pre> <p>or load your own version:</p> <pre><code>wp_enqueue_script( 'jquery', '/path/to/your/jquery.js', false, '1.2.1'); </code></pre> <hr> <p>Now add a bit of javascript in your template, something like:</p> <pre><code>if(window.location.href == 'http://www.example.com/'){ //checks for root path - "home" ('http://www.example.com/?p=7' or 'http://www.example.com/2008-10/7' will not match) jQuery('#nav &gt; ul &gt; li &gt; a:first').addClass('current_page_item'); } </code></pre> <p>The <em>a:first</em> portion assumes the first link in your menu is the home/frontpage link. If it's not, select via href value or position. Here's by postion:</p> <p>~~~~~~~~~~~~~~~</p> <pre><code>jQuery(jQuery('#nav &gt; ul &gt; li &gt; a')[3]).addClass('current_page_item'); //add 'current_page_item' css class so menu item highlighting occurs </code></pre> <p>Example:</p> <blockquote> <p>&lt;div id="nav" &gt;</p> <p>&lt;ul &gt;<br> &lt;li &gt; &lt;a &gt;Link 0 &lt;/a &gt; &lt;/li &gt;<br> &lt;li &gt; &lt;a &gt;Link 1 &lt;/a &gt; &lt;/li &gt;<br> &lt;li &gt; &lt;a &gt;Link 2 &lt;/a &gt; &lt;/li &gt;<br> <strong>&lt;li &gt; &lt;a &gt;Link 3 &lt;/a &gt; &lt;/li &gt;</strong><br> &lt;li &gt; &lt;a &gt;Link 4 &lt;/a &gt; &lt;/li &gt;<br> &lt;li &gt; &lt;a &gt;Link 5 &lt;/a &gt; &lt;/li &gt;<br> &lt;/ul &gt; </p> <p>&lt;/div &gt;</p> </blockquote> <hr> <p>Caveats: </p> <ol> <li>Check for the actual name of your menu div id (<em>#nav</em> shown here)</li> <li>A nested ul/li menu structure (so more than one level) will require additional code to properly selection the correct <em>a</em> element.</li> <li>If menu links are going to change, don't use a positional selection technique, use another hook, like the href value of the link to the home/front page.</li> <li>The <em>if(window.location.href == '<a href="http://www.example.com/" rel="nofollow noreferrer">http://www.example.com/</a>')</em> portion may need to be a regex if more variation is involved (https, multiple subdomains, etc).</li> </ol>
<p>You can set a static page as the front page in the Administration > Settings > Reading panel after logging in as the administrator.</p> <p>The Wordpress manual entry on this subject can be found <a href="http://codex.wordpress.org/Creating_a_Static_Front_Page" rel="nofollow noreferrer">here</a>.</p>
27,066
<pre><code>select Table1.colID, Table1.colName, (select * from Table2 where Table2.colID = Table1.colID) as NestedRows from Table1 </code></pre> <p>The above query gives you this error: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, &lt;, &lt;= , >, >= or when the subquery is used..... </p> <p>Can anybody explain why this limitation exist? </p> <p>I had this idea that this kind of multidimentional queries would be nice for building OO objects directly from the database with 1 query</p> <p>EDIT:</p> <p>This question is pretty theoretical. To solve this practical I would use a join or simply done 2 queries, but I wondered if there was anything stopping you from returning a column as a table type (In sql server 2008 you can create table types).</p> <p>Say you have corrensponding classes in code, think Linq2Sql</p> <pre><code>public class Table1 { public int colID, public string colName, public List&lt;Table2&gt; table2s; } </code></pre> <p>I would like to be able to fill instances of this class directly with 1 query</p>
<p>Because the subquery in a select clause must be "inserted" into a column value in every row of the result set from the outer query. You cannot put a set of values into a single cell (a single column of a single row) of the result set. </p> <p>You need to use an inner join. the multiple rows returned by joined table will be output as multiple rows in the final result set. </p>
<p>You would be better off using an INNER JOIN between the two tables and simply selecting the rows you want from each table.</p> <pre><code>SELECT tab1.colID, tab1.colName, tab2.Column1, tab2.column2 FROM dbo.Table1 AS tab1 INNER JOIN dbo.Table2 AS tab2 ON tab1.colID = tab2.colID </code></pre> <p>However, remember that the data from table1 will be repeated for each matching record in table2. Although I believe the query I posted will get the data in the form you are looking for, I don't think it's the best method for querying the database. I would either execute separate queries, or put the separate queries into a stored procedure and return multiple result sets.</p>
48,557
<p>For my programming class I have to write a linked list class. One of the functions we have to include is next(). This function would return the memory address of the next element in the list.</p> <pre><code>#include &lt;iostream&gt; using namespace std; class Set { private: int num; Set *nextval; bool empty; public: Set(); &lt;some return type&gt; next(); }; &lt;some return type&gt; Set::next() { Set *current; current = this; return current-&gt;next; } int main() { Set a, *b, *c; for (int i=50;i&gt;=0;i=i-2) a.insert(i); // I've ommited since it does not pertain to my question // Test the next_element() iterator b = a.next(); c = b-&gt;next(); cout &lt;&lt; "Third element of b = " &lt;&lt; c-&gt;value() &lt;&lt; endl; return 0; } </code></pre> <p>As you can see, I need to set the pointer <code>*b</code> and <code>*c</code> to the memory address that holds the next element in the list. My question is what kind of return type would I use? I've tried putting Set and Set* in place of but get compiler errors. Any help is greatly appreciated.</p>
<p><code>Set*</code> is correct. You are suffering from a rather silly bug in this function:</p> <pre><code>Set* Set::next() { Set *current; current = this; return current-&gt;next; } </code></pre> <p>The last line should be <code>return current-&gt;nextval</code>. Otherwise you are trying to return a pointer to the <code>next</code> function... probably not what you want, ever. :-)</p>
<p>luqui is correct, although your <strong>next</strong> function is overly complex, there's no reason to copy the <em>this</em> pointer, that's just silly. Use this instead:</p> <pre><code>Set* Set::next() { return nextval; } </code></pre>
40,247
<p>I have the following C# which simply replaces parts of the input string that look like EQUIP:19d005 into URLs, like this:</p> <pre><code>input = Regex.Replace(input, @"(EQUIP:)(\S+)", @"&lt;a title=""View equipment item $2"" href=""/EquipmentDisplay.asp?eqnum=$2""&gt;$1$2&lt;/a&gt;", RegexOptions.IgnoreCase); </code></pre> <p>The HTML ends up looking like this.</p> <pre><code>&lt;a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19d005"&gt;EQUIP:19d005&lt;/a&gt; </code></pre> <p>The only trouble is that the destination page expects the eqnum querystring to be all UPPERCASE so it returns the correct equipment when eqnum=19D005 but fails if it receives eqnum=19d005.</p> <p>I guess I can modify and correct EquipmentDisplay.asp's errant requirement of uppercase values however, if possible I'd like to make the C# code comply with the existing classic ASP page by uppercasing the $2 in the Regex.Replace statement above.</p> <p>Ideally, I'd like the HTML returned to look like this:</p> <pre><code>&lt;a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19D005"&gt;EQUIP:19d005&lt;/a&gt; </code></pre> <p><em>Notice although the original string was EQUIP:19d005 (lowercase), only the eqnum= value is uppercased.</em></p> <p>Can it be done and if so, what's the tidiest way to do it?</p>
<p>OK, 2 solutions, one inline:</p> <pre><code>input = Regex.Replace(input, @"(EQUIP:)(\S+)", m =&gt; string.Format(@"&lt;a title=""View equipment item {1}"" href=""/EquipmentDisplay.asp?eqnum={2}""&gt;{0}{1}&lt;/a&gt;", m.Groups[1].Value, m.Groups[2].Value, m.Groups[2].Value.ToUpper()), RegexOptions.IgnoreCase); </code></pre> <p>The other using a separate function:</p> <pre><code>var input = Regex.Replace(input, @"(EQUIP:)(\S+)", Evaluator, RegexOptions.IgnoreCase); private static string Evaluator(Match match) { return string.Format(@"&lt;a title=""View equipment item {1}"" href=""/EquipmentDisplay.asp?eqnum={2}""&gt;{0}{1}&lt;/a&gt;", match.Groups[1].Value, match.Groups[2].Value, match.Groups[2].Value.ToUpper()); } </code></pre>
<p>Assuming that input is a string:</p> <p><code>input = Regex.Replace(input.ToUpper, @"(EQUIP:)(\S+)", @"&lt;a title=""View equipment item $2"" href=""/EquipmentDisplay.asp?eqnum=$2""&gt;$1$2&lt;/a&gt;", RegexOptions.IgnoreCase);</code></p> <p>Changing the case of a string isn't something regex does.</p>
25,163
<p>how do I bind a <code>std::ostream</code> to either <code>std::cout</code> or to an <code>std::ofstream</code> object, depending on a certain program condition? Although this invalid for many reasons, I would like to achieve something that is semantically equivalent to the following:</p> <pre><code>std::ostream out = condition ? &amp;std::cout : std::ofstream(filename); </code></pre> <p>I've seen some examples that are not exception-safe, such as one from <a href="http://www2.roguewave.com/support/docs/sourcepro/edition9/html/stdlibug/34-2.html" rel="noreferrer">http://www2.roguewave.com/support/docs/sourcepro/edition9/html/stdlibug/34-2.html</a>:</p> <pre><code>int main(int argc, char *argv[]) { std::ostream* fp; //1 if (argc &gt; 1) fp = new std::ofstream(argv[1]); //2 else fp = &amp;std::cout //3 *fp &lt;&lt; "Hello world!" &lt;&lt; std::endl; //4 if (fp!=&amp;std::cout) delete fp; } </code></pre> <p>Does anyone know a better, exception-safe solution?</p>
<pre><code>std::streambuf * buf; std::ofstream of; if(!condition) { of.open("file.txt"); buf = of.rdbuf(); } else { buf = std::cout.rdbuf(); } std::ostream out(buf); </code></pre> <p>That associates the underlying streambuf of either cout or the output file stream to out. After that you can write to "out" and it will end up in the right destination. If you just want that everything going to <code>std::cout</code> goes into a file, you can aswell do</p> <pre><code>std::ofstream file("file.txt"); std::streambuf * old = std::cout.rdbuf(file.rdbuf()); // do here output to std::cout std::cout.rdbuf(old); // restore </code></pre> <p>This second method has the drawback that it's not exception safe. You possibly want to write a class that does this using RAII:</p> <pre><code>struct opiped { opiped(std::streambuf * buf, std::ostream &amp; os) :os(os), old_buf(os.rdbuf(buf)) { } ~opiped() { os.rdbuf(old_buf); } std::ostream&amp; os; std::streambuf * old_buf; }; int main() { // or: std::filebuf of; // of.open("file.txt", std::ios_base::out); std::ofstream of("file.txt"); { // or: opiped raii(&amp;of, std::cout); opiped raii(of.rdbuf(), std::cout); std::cout &lt;&lt; "going into file" &lt;&lt; std::endl; } std::cout &lt;&lt; "going on screen" &lt;&lt; std::endl; } </code></pre> <p>Now, whatever happens, std::cout is in clean state. </p>
<p>Being a novice to C++, I don't know if this is exception-safe, but here's how I usually do it:</p> <pre><code>std::ostream&amp; output = (condition)?*(new std::ofstream(filename)):std::cout; </code></pre>
47,897
<p>When sending data over HTTPS, I know the content is encrypted, however I hear mixed answers about whether the headers are encrypted, or how much of the header is encrypted.</p> <p>How much of HTTPS headers <em>are</em> encrypted?</p> <p>Including GET/POST request URLs, Cookies, etc.</p>
<p>All the HTTP headers are encrypted<sup>†</sup>. That's why SSL on vhosts doesn't work too well - you need a dedicated IP address because the Host header is encrypted.</p> <p><sup>†</sup>The Server Name Identification (SNI) standard means that the hostname may not be encrypted if you're using TLS. Also, whether you're using SNI or not, the TCP and IP headers are never encrypted. (If they were, your packets would not be routable.)</p>
<p>To understand, what is encrypted and what not, you need to know that SSL/TLS is the layer between the transport-layer and the application-layer.</p> <p>in the case of HTTPS, HTTP is the application-layer, and TCP the transport-layer. That means, all Headers below the SSL-Level are unencrypted. Also, SSL itself may expose data. The exposed data includes(for each layer's Header):</p> <p>NOTE: Additional Data might be exposed too, but this data is pretty sure to be exposed.</p> <p>MAC:</p> <ol> <li>Source MAC address(Current Hop)</li> <li>Destination MAC address(Next Hop)</li> </ol> <p>IP(assuming IPv4):</p> <ol> <li>Destination IP address</li> <li>Source IP address</li> <li>IP Options(if set)</li> <li>Type-Of-Service(TOS)</li> <li>The number of hops the current packet passed, if TTL is set to 64</li> </ol> <p>TCP:</p> <ol> <li>Source Port</li> <li>Destination Port</li> <li>TCP-Options</li> </ol> <p>Theoretically, you can encrypt the TCP-Headers, but that is hard to implement.</p> <p>SSL:</p> <ol> <li>Hostname(if SNI is being used)</li> </ol> <p>Usually, a browser won't just connect to the destination host by IP immediantely using HTTPS, there are some earlier requests, that might expose the following information(if your client is not a browser, it might behave differently, but the DNS request is pretty common):</p> <p>DNS: This request is being sent to get the correct IP address of a server. It will include the hostname, and its result will include all IP addresses belonging to the server.</p> <p>HTTP: the first request to your server. A browser will only use SSL/TLS if instructed to, unencrypted HTTP is used first. Usually, this will result in a redirect to the seucre site. However, some headers might be included here already:</p> <ol> <li>User-Agent(Specification of the client)</li> <li>Host (Hostname)</li> <li>Accept-Language (User-Language)</li> </ol>
22,739
<p>I wonder what are the main challenges to porting those emulator engines. </p> <p>Could there been any sucess without having to rewrite all the code? Any conversion tools available that can help? </p>
<p>Some people have tried but it seems they <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1011253&amp;SiteID=1" rel="nofollow noreferrer">gave up</a>:</p> <p><a href="http://sourceforge.net/projects/scummvmxna/" rel="nofollow noreferrer">scummvmxna</a></p> <p>Other route could be the approach taken by <a href="http://spel.bth.se/index.php/Cibyl" rel="nofollow noreferrer">Cibyl</a>.</p>
<p>There is some people over at XDA developers that is making a DLL wrapper for C#.Net/XNA/Silverlight... The DllImport Project: <a href="http://forum.xda-developers.com/showthread.php?t=1006331" rel="nofollow">http://forum.xda-developers.com/showthread.php?t=1006331</a></p> <p>As I understand it this is for wrapping DLLs to use them on Windows Phone 7 systems</p> <p>But I don't know if it will be possible to use it for ScummVM. It seems like you can't do p/invoke. And as I understand ScummVM is heavily dependent on p/invoke. <a href="http://forums.scummvm.org/viewtopic.php?t=9350&amp;sid=d324c805f27e3c62713f02db3763c021" rel="nofollow">http://forums.scummvm.org/viewtopic.php?t=9350&amp;sid=d324c805f27e3c62713f02db3763c021</a></p> <p>NOTE: I haven't been reading up on this much at all... I was just browsing around, searching for the possibility if ScummVM will ever be released for WP7 units, and found this question and thought I ought to answer what I've found out. I can have misunderstood some of the things I been reading. So just check it out for yourself if you are interested in trying to port or wrap the ScummVM libraries to C#.Net/XNA/Silverlight code.</p> <p>God I'm tired... I should really go to sleep now...</p>
37,457
<p>At my current job I've been working on making web apps with Java, Tapestry, Hibernate, MSSQL, and Tomcat.</p> <p>I've got an idea for a little web game I'd like to write. I'd like to know what the SO community would use for something like this.</p> <p>Should I stick to what I know? I was thinking it would be very beneficial for me to learn different languages and frameworks. Any suggestions?</p>
<p>If its a personal project then take this as an opportunity to learn something new.</p>
<p>If your thinking about an online game like a RPG or card game I might be selfish and suggest you have a look at <a href="http://www.projectdarkstar.org" rel="nofollow noreferrer">Project Darkstar</a> and let us know how you got on. I've been trying to get started with it and cannot get it up running in my environment.</p>
49,704
<p>I am thinking about providing a version of say, the database schema and the <code>dlls</code> for business logic in the footer of my web application.</p> <p>Is this advised?</p> <p>Are there any pitfalls, or pointers of how to do this best?</p> <p>Usability concerns?</p> <p><strong>I already have a version scheme, for both schema and dlls, used in my CI solution.</strong></p>
<p>I quite like what is done e.g. <a href="http://episteme.arstechnica.com/" rel="noreferrer">here</a>. If you look towards the bottom of the page, there's a piece of text "powered by eve community". If you click that text you get a small chunk of technical information.</p> <p>To me, this is a nice tradeoff between having the (useful) information readily available (for bug reports, etc.) and having to have (unpleasant) technical jargon visible to users of the site.</p>
<p>IMO, the only reasons to show version numbers are:</p> <ul> <li>To show progress is being made</li> <li>To help bug reports be localized to the version they were discovered in</li> </ul> <p>So if these things are important for your bug reports, then expose them. If not, then don't.</p>
4,439
<p>I'm trying to load a page that is basically an edit form inside a dialog (ui.dialog). I can load this page fine from an external (I'm using asp.net) page.</p> <p>The problem is that inside of my "popup" form, I need to <code>$(function() {my function here});</code> syntax to do some stuff when the page loads, along with registering some <code>.fn</code> extensions for some dynamic dropdowns using ajax calls.</p> <p>I have created my <code>&lt;script type="text/javascript" src="jquery.js"&gt;</code> but I don't think these are being included, and also my <code>$(function)</code> is not being called.</p> <p>Is this possible to do or do I need to find another way of accomplishing what I need to do? </p>
<p>If you really need to load that form via AJAX you could to do all the Javascript stuff in $.ajax callback itself. So, you load the popup form like this:</p> <pre><code>$.ajax({ //... success: function(text) { // insert text into container // the code from $(function() {}); } }); </code></pre>
<p>The script isn't getting run because the document's ready event has already been fired. Remove your code from within the </p> <pre><code>$() </code></pre>
8,988
<p>Of all the forms of CAPTCHA available, which one is the "least crackable" while remaining fairly human readable?</p>
<p>I agree with Thomas. Captcha is on its way out. But if you must use it, <a href="http://www.recaptcha.net" rel="noreferrer">reCAPTCHA</a> is a pretty good provider with a simple API.</p>
<p>As far as I know, the Google's one is the best that there is. It hasn't been broken by computer programs yet. What I know that the crackers have been doing is to copy the image and then send it to many phishing websites where humans solve them to enter those websites.</p>
8,421
<p>I'm inserting something in the cache when the user does a login. </p> <p>Now I want to delete that from the cache when the user's session expires. HttpContext is null .. so I don't know for which user the session expired. How can I go about finding this ?</p> <p><strong>EDIT:</strong> unfortunately SessionID doesn't offer me much. What i'm doing in this particular case is using an HttpModule that handles AuthorizeRequest to insert the current userName in Cache to ensure that another user from another machine can't login. But the Session is null in the HttpModule. So I can't use that. Any other suggestions ?</p>
<p>Instead of creating Excel or HTML files on Oracle server, you can fetch Oracle data to existing Excel document via ODBC or OLEDB. The shortcoming is, that you should be careful with user permissions.</p> <p><a href="https://www.youtube.com/watch?v=Adz0zZFePf8" rel="nofollow noreferrer">https://www.youtube.com/watch?v=Adz0zZFePf8</a></p>
<p>You could save a (small) Excel sheet as html in Excel, and then reproduce that format.</p>
38,239
<p>I have an MFC application that uses several MFC extension DLL's. I want this app (and several other similar apps) to be able to access some parts of the .net framework. I wrote a C# library to do the .net work I want and was hoping to be able to write an MFC dll to hide all the C++/CLI code from my apps. The apps would stay as pure MFC apps and the only C++/CLI code would be in my new MFX extension DLL. However when I did this the apps crashed when accessing the new MFC C++/CLI dll. If I put the C++/CLI code in the apps it works ok and I can debug my way all the way in to the C#.</p> <p>Does anyone understand why the dll idea doesn't work?</p> <p>Thanks</p>
<p>You can't reference managed assemblies from pure native code. You have to either flip the /clr switch on the consumer (either project-wide or in certain files,) or do some interop.</p> <p>One interop option that will allow your consumer to say pure native is calling into the managed assembly via <a href="http://msdn.microsoft.com/en-us/library/f07c8z1c.aspx" rel="nofollow noreferrer">COM Callable Wrapper</a>.</p>
<p>The MFC dll project references the C# library and has one file compiled with /clr that handles the interface into my C# library. I have actually seen this work sometimes at run time but have never been able to debug into the MFC dll or into the C# code. However it doesn't seem to be at all stable and crashes in the majority of cases.</p>
27,396
<p>I have the following code:</p> <pre><code>MemoryStream foo(){ MemoryStream ms = new MemoryStream(); // write stuff to ms return ms; } void bar(){ MemoryStream ms2 = foo(); // do stuff with ms2 return; } </code></pre> <p>Is there any chance that the MemoryStream that I've allocated will somehow fail to be disposed of later? </p> <p>I've got a peer review insisting that I manually close this, and I can't find the information to tell if he has a valid point or not.</p>
<p>You won't leak anything - at least in the current implementation.</p> <p>Calling Dispose won't clean up the memory used by MemoryStream any faster. It <em>will</em> stop your stream from being viable for Read/Write calls after the call, which may or may not be useful to you.</p> <p>If you're absolutely sure that you <em>never</em> want to move from a MemoryStream to another kind of stream, it's not going to do you any harm to not call Dispose. However, it's generally good practice partly because if you ever <em>do</em> change to use a different Stream, you don't want to get bitten by a hard-to-find bug because you chose the easy way out early on. (On the other hand, there's the YAGNI argument...)</p> <p>The other reason to do it anyway is that a new implementation <em>may</em> introduce resources which would be freed on Dispose.</p>
<p>I'm no .net expert, but perhaps the problem here is resources, namely the file handle, and not memory. I guess the garbage collector will eventually free the stream, and close the handle, but I think it would always be best practice to close it explicitly, to make sure you flush out the contents to disk.</p>
28,971
<p>I need to 3D print several composites. The constituent materials are photopolymer resins. The composites are very similar to a Rubik's cube. Considering it that way, each voxel (every small piece of the Rubik's cube) is either entirely printed by material A or B.</p> <p>I have the binary files ready for the parts. More specifically speaking, I have 3D binary tensors corresponding to each composite topology. In my tensors, each of the elements represents a voxel, and their values (binary) indicate the material that should be assigned to that specific voxel. For instance, a 1 or 0 value located at the I, J, K position of the binary tensor simply means that in that composite, the voxel located at that I, J, K position should be printed with material A or B entirely.</p> <p>I believe for 3D printing these composites, the <a href="https://www.stratasys.com/3d-printers/objet-350-500-connex3" rel="nofollow noreferrer">Stratasys Objet500 Connex3 printer</a> would be a good choice. However, I have no idea how to prepare my files for 3D printing the structures. If it was a CAD file, I could use slicer software, but I do not know how I can print the structures using these binary tensors. I would appreciate any help regarding this matter.</p>
<p>It appears that your question is directed to solving the problem of converting your file of parameters to a 3D printable form. I'm far from an OpenSCAD wizard, but I suspect that your parameters file could be read into a properly coded OpenSCAD document to create the necessary STL to be printed.</p> <p>Your reference of I, J, K is better considered as X, Y, Z and requires an additional value to determine material A, B or nul. If your voxels are uniform size as I expect, the coding is likely not to be particularly complex (for more skilled individuals).</p> <p>pseudocode:</p> <pre><code>read entry translate by x, y, z check for print material a create voxel repeat to EOF export STL </code></pre> <p>repeat for material b</p> <p>It's important to note that a typical STL file requires the object to be a fully manifold creation. If the STL appears, for example, as a QR code, some of the voxels will be floating and may not produce. This is also dependent on the printer selected, as an SLS printer would be able to produce such a design, which would fall apart once removed from the print chamber. These are aspects not covered in the question.</p>
<p>Stratasys industrial machines generally use proprietary software to prepare the print files for printing and don't use common slicers like Ultimaker Cura or Prusa-slicer.</p> <p>The software that is suggested by the manufacturer for both arranging and preparing prints on their machines of the Objet type is <a href="https://grabcad.com/print" rel="nofollow noreferrer">GrabCAD</a>, a free software. The project is owned by Stratasys, so it is pretty much on point to all of Stratasys' machine's capabilities.</p>
2,087
<p>A class I am taking currently requires us to do all of our coding in smalltalk (it's a Design class). On one of our projects, I am looking to do some things, and am having a tough time finding how to do them. It seems that what most people do is modify their own version of smalltalk to do what they need it to do. I am not at liberty to do this, as this would cause an error on my prof's computer when he doesn't have the same built-in methods I do.</p> <p>Here's what I'm looking to do:</p> <p>Random Numbers. I need to create a random number between 1 and 1000. Right now I'm faking it by doing </p> <pre><code>rand := Random new. rand := (rand nextValue) * 1000. rand := rand asInteger. </code></pre> <p>This gives me a number between 0 and 1000. Is there a way to do this in one command? similar to </p> <pre><code>Random between: 0 and: 1000 </code></pre> <p>And/Or statements. This one bugs the living daylights out of me. I have tried several different configurations of </p> <pre><code>(statement) and: (statement) ifTrue... (statement) and (statement) ifTrue... </code></pre> <p>So I'm faking it with nested ifTrue statements:</p> <pre><code>(statement) ifTrue:[ (statement) ifTrue:[... </code></pre> <p>What is the correct way to do and/or and Random in smalltalk?</p>
<p>The problem is that</p> <pre><code> (expr) and: (expr) ifTrue: aBlock </code></pre> <p>is parsed as the method <code>and:ifTrue:</code> If you look at the Boolean class (and either True or False in particular), you notice that ifTrue: is just a regular method, and that no method and:ifTrue: exists - however, plain and: does. So to make it clear that these are two messages, write</p> <pre><code>((expr) and: (expr)) ifTrue: aBlock </code></pre> <p>For longer boolean combinations, notice that there are also methods and:and: and and:and:and: implemented.</p>
<p><strong>To create several random integers between 1 and 1000</strong><br> First create a random number series. Do this just once.</p> <p>Then create a new random number by taking the next number from the series. Repeat as necessary.</p> <pre><code>aRandomSeries := Random new . "Seed a new series of random numbers" aRandomInt := aRandomSeries newInt: 1000 . "generate a random integer between 0 and 1000" anotherRandomInt := aRandomSeries newInt: 1000 . "generate another random integer between 0 and 1000" </code></pre> <p><strong>Logical operations</strong></p> <p><code>aBoolean</code> will respond to <code>and:</code> and <code>or:</code>. They both take <em>block arguments</em>.</p> <p>Here is how they work.</p> <p><code>and: alternativeBlock</code><br> If the receiver is true, answer the value of alternativeBlock; otherwise answer false without evaluating alternativeBlock.</p> <p><code>or: alternativeBlock</code><br> If the receiver is false, answer the value of alternativeBlock; otherwise answer true without evaluating alternativeBlock.</p> <p>e.g.<br> <code>( 3 &gt; 2 ) or: [ 3 &lt; 4 ] ifTrue: [ ]</code><br> <code>aBoolean and: [ anotherBoolean ] ifFalse: [ ]</code></p> <p>However, Squeak and Pharo Smalltalks will both accept an argument in parentheses <code>( )</code><br> Dolphin Smalltalk will not, and strictly requires the standard Smalltalk syntax of a block argument.</p> <p><strong>Other related methods:</strong><br> <code>&amp;</code> an <em>AND</em> that does not require a square bracketted (i.e. block) argument<br> <code>|</code> an <em>OR</em> that does not require a square bracketted (i.e. block) argument<br> <code>&amp;</code> and <code>|</code> work in Amber, Cuis, Gnu, Pharo, Squeak, VisualAge and VisualWorks Smalltalks. </p> <p>Squeak Smalltalk also provides:<br> <code>and:and: }</code><br> <code>and:and:and: }</code> These take multiple block arguments<br> <code>and:and:and:and }</code></p> <p><code>or:or: }</code><br> <code>or:or:or: }</code> These take multiple block arguments<br> <code>or:or:or:or: }</code></p>
34,130
<p>I have a website setup in IIS 6, let's say it's called <strong><a href="http://www.this.com" rel="nofollow noreferrer">http://www.this.com</a></strong>.</p> <p>I have setup a redirection for this website to <strong><a href="http://www.that.com" rel="nofollow noreferrer">http://www.that.com</a></strong> which maintains the directory structure and query parameters as follows:</p> <p><strong><a href="http://www.that.com" rel="nofollow noreferrer">http://www.that.com</a>$S$Q - using the option "The exact URL entered above"</strong></p> <p>This works great, whenever someone requests, for example:</p> <p><strong><a href="http://www.this.com/subfolder/page.aspx?Id=1" rel="nofollow noreferrer">http://www.this.com/subfolder/page.aspx?Id=1</a></strong></p> <p>then they end up at:</p> <p><strong><a href="http://www.that.com/subfolder/page.aspx?Id=1" rel="nofollow noreferrer">http://www.that.com/subfolder/page.aspx?Id=1</a></strong></p> <p>Now, I have one page, actually a handler, <strong><a href="http://www.this.com/image.axd" rel="nofollow noreferrer">http://www.this.com/image.axd</a></strong>, which I do not want to redirect.</p> <p>What is the syntax for that? I've read the <strong>Redirection Using Wildcards</strong> section <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/41c238b2-1188-488f-bf2d-464383b1bb08.mspx?mfr=true" rel="nofollow noreferrer">here</a>, but I can't work out how to do what seems to be something straight forward.</p> <p>Note that <strong>image.axd</strong> is a handler so I can't just "right click" on it and set the redirection properties as it doesn't physically exist.</p> <p>I also have a couple of other pages in subfolders which I do not want to redirect, for example:</p> <p><strong><a href="http://www.this.com/subfolder/donotredirectthispage.aspx" rel="nofollow noreferrer">http://www.this.com/subfolder/donotredirectthispage.aspx</a></strong></p> <p>Any help would be appreciated.</p> <p><strong>Edit:</strong> A couple of people have mentioned using ISAPI_Rewrite, for which I'm grateful, but I really don't want to introduce another complexity into the website configuration. IIS seems to imply I can acheive what I want using the ! and 0 through 9 variables. </p> <p>Is it really not possible to do this using IIS?</p> <p>My current workaround is to set the redirection properties on ALL folders and pages that I want to redirect except those I do not, but this is a management nightmare.</p>
<p>You could implement a custom error page for the <code>page not found</code> error (404) that does the redirection for you. You'd turn off the redirection in IIS. Build the logic for the redirection in your custom error page. Then configure your web site so that 404 errors redirect to your error page.</p>
<p>If you can install software on your IIS server, I'd recommend using a tool to rewrite your request URLs.</p> <p>For IIS 6.0 I've used <a href="http://www.isapirewrite.com/" rel="nofollow noreferrer">ISAPI_Rewrite</a> and it works really well. It's lightweight and very configurable. There's a "Lite" version available for free and will support your requirements.</p> <p>You configure the program using a text file containing rules that match HTTP requests and then write actions to perform once a rule is matched. Your instance would probably require a general redirect rule (similar to the one in IIS) and rules for your exceptions.</p>
46,394
<p>I have a c# winforms program and it opens up a serial port. The problem happens when the end user unplugs the usb cable and then the device disappears. After this the program will crash and want to report the error to microsoft. </p> <p>Is there a way to capture this event and shut down gracefully? </p>
<p>You can use WMI (Windows Management Instrumentation) to receive notification on USB events. I did exactly that two years ago, monitoring for plugging and unplugging of a specific usb device.<br> Unfortunately, the code stays with my former employer, but I found one example at <a href="http://bytes.com/topic/net/answers/102489-how-detect-usb-device-being-plugged-unplugged" rel="nofollow">bytes.com</a>:</p> <pre><code>using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Management; class UsbWatcher { public static void Main() { WMIEvent wEvent = new WMIEvent(); ManagementEventWatcher watcher = null; WqlEventQuery query; ManagementOperationObserver observer = new ManagementOperationObserver(); ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; try { query = new WqlEventQuery(); query.EventClassName = "__InstanceCreationEvent"; query.WithinInterval = new TimeSpan(0,0,10); query.Condition = @"TargetInstance ISA 'Win32_USBControllerDevice' "; watcher = new ManagementEventWatcher(scope, query); watcher.EventArrived += new EventArrivedEventHandler(wEvent.UsbEventArrived); watcher.Start(); } catch (Exception e) { //handle exception } } </code></pre> <p>I don't remember if I modified the query to receive events only for e specific device, or if I filtered out events from other devices in my event handler. For further information you may want to have a look at the <a href="http://msdn.microsoft.com/en-us/library/ms257338.aspx" rel="nofollow">MSDN WMI .NET Code Directory</a>.</p> <p><strong>EDIT</strong> I found some more info on the event handler, it looks roughly like this:</p> <pre><code>protected virtual void OnUsbConnected(object Sender, EventArrivedEventArgs Arguments) { PropertyData TargetInstanceData = Arguments.NewEvent.Properties["TargetInstance"]; if (TargetInstanceData != null) { ManagementBaseObject TargetInstanceObject = (ManagementBaseObject)TargetInstanceData.Value; if (TargetInstanceObject != null) { string dependent = TargetInstanceObject.Properties["Dependent"].Value.ToString(); string deviceId = dependent.Substring(dependent.IndexOf("DeviceID=") + 10); // device id string taken from windows device manager if (deviceId = "USB\\\\VID_0403&amp;PID_6001\\\\12345678\"") { // Device is connected } } } } </code></pre> <p>You may want to add some exception handling, though.</p>
<p>If your try statement isn't catching the exception then let's hope Microsoft will inspect the dumps.</p> <p>There are some SetupDi APIs (I think ... it's been a while) that permit you to be advised of device arrivals and removals, but it won't help if you already crashed because the removed device was in the middle of your read or write operation.</p>
36,361
<p>What steps I need to perform in order to convert asp.net 2 application from IIS7 classic to integrated mode?</p>
<p>Here is a process: <a href="http://www.west-wind.com/WebLog/posts/6075.aspx" rel="noreferrer">Rick Strahl's blog</a></p>
<p>Nothing really. ASP.NET 2.0 applications will run just as they have in IIS 6.0. If you want to take advantage of any of the new features then you just need to update your code. But unless you are changing the structure of the header of the response or intercepting requests for other applications you probably will not need to do anything.</p>
3,193
<p>What is the best way to store instances of a class to file/database?</p> <p>We have a base class called Command and loads of derived classes. Users create instances of these classes by adding commands to a graphical designer where they can configure them. (Set the properties).</p> <p>We then need a way to store these "commands" to a file without losing any information.</p> <p>One idea was to use db4o, but the GPL license is not acceptable for this project.</p> <p>Any suggestions or code samples?</p> <p>Update:</p> <p>(In order to "de-blurryfie" my question :p)</p> <p>The generated code might look something like:</p> <pre><code> command[i++] = new DelayInSecondsCommand(2); command[i++] = new DaliRequestCommand(1, false, 254); command[i++] = new DaliRequestCommand(2, false, 254); command[i++] = new DaliRequestCommand(3, false, 254); command[i++] = new WaitInSecondsCommand(2); command[i++] = new DaliRequestCommand(1, false, 0); command[i++] = new DaliRequestCommand(2, false, 0); command[i++] = new DaliRequestCommand(3, false, 0); command[i++] = new JumpCommand(0); </code></pre> <p>But then with loads of different commands.</p> <p>I know it's possible with .NET serialization, altough I've never used it before, but I was wondering if there are better alternatives, like I said db4o seems nice but the license doesn't fit the project.</p> <p>Update 2:</p> <p>Thank you for the replies. I'll probably go with the serialization solution now, but I'll look into the other options as well. F.Y.I. data is stored in a SQL Compact database.</p>
<p>serialization does the trick! Serialization is nothing more than converting an object or a connected graph of objects into a stream of bytes (in order to persist the current state of the object). This can be a binary stream, XML or whatever. You don't have to do this conversion by your own since .Net has great support for serialization. Once you serialized an object, you are free to store this data to a file or database. Likewise, a stream of bytes representing a serialized object can be deserialized into an object which will have the same state as the original one.</p> <p>Btw: Once you have a serialized stream of bytes, you can apply some more functions on it, e.g. compression or encryption.</p>
<p>Pretty blurry question, why don't you just use .NET's built-in serialization possibilities (e.g. XmlSerializer).</p>
46,367
<p>We have a PHP project that we would like to version control. Right now there are three of us working on a development version of the project which resides in an external folder to which all of our Eclipse IDEs are linked, and thus no version control.</p> <p>What is the right way and the best way to version control this?</p> <p>We have an SVN set up, but we just need to find a good way to check in and out that allows us to test on the development server. Any ideas?</p>
<p>We were in a similar situation, and here's what we ended up doing:</p> <ul> <li>Set up two branches -- the release and development branch.</li> <li>For the development branch, include a post-commit hook that deploys the repository to the dev server, so you can test.</li> <li>Once you're ready, you merge your changes into the release branch. I'd also suggest putting in a post-commit hook for deployment there.</li> </ul> <p>You can also set up individual development servers for each of the team members, on their workstations. I find that it speeds things up a bit, although you do have some more setup time.</p> <p>We had to use a single development server, because we were using a proprietary CMS and ran into licensing issues. So our post-commit hook was a simple FTP bot.</p>
<p>Each of you could run it locally, or on your own dev server (or even the same one with a different port...).</p>
2,694
<p>I am evaluating VintaSoft .net control and Atalasoft DotTwain Image Capture. And I am very but very lost with the most of the definitions and keywords.</p> <p>So I am asking this because I think I am in Lala land. Is it possible to listen or have the scanner tell my app that there is a scanned image and I can process it?</p> <p>The idea is to have a winservice that is waiting for the scanner to scan something and when that happens process the image.</p>
<p>I have only worked with the native interfaces to TWAIN and WIA, so I can't vouch for these other layers on top of them. However, with regards to TWAIN, some mechanisms do exist that allow an application to be notified to capture data. I believe this is handled with STI.dll, an older library that is available on Windows 2000+. Look up StiCreateInstance for more info.</p> <p>If you choose to go the WIA route, it is much simpler. You can register to recieve events, such as a 'scan' button or 'image created' event. Then all you need to do is handle those events to get the image. The toughest part of that is finding hardware that implements the features you want.</p> <p>Microsoft has a WIA automation library that makes many of these tasks much simpler. It can be used by scripting languages.</p>
<p>It is possible to have the scanner tell your app that there is a scanned image. I am not familiar with VintaSoft .net control and Atalasoft DotTwain Image Capture, but with some twain sdks, there is OnPostTransfer/OnPostAllTransfer event which is triggered after each scanning so that you can "notify" your winservice</p>
33,006
<p>I have a folder full of files i need to post to a webservice using cURL but i'm not sure on the whole variables and iterations in batch files thing.</p> <p>I know the syntax for curl should be </p> <pre><code>c:\curl\bin\curl -X POST -F File=@[filename] -F "title=[title]" -F "notes=[notes]" "http://xxx/AddScannedImage?debtref=[filename]" </code></pre> <p>but the % symbols from the variables seem to get gobbled up in the URL encoding</p> <p>Any ideas?</p> <p>TIA</p>
<p>You should try with the <code>-g</code> aka <code>--globoff</code> cURL option.</p> <p>The default behavior is to :</p> <blockquote> <p>You can specify multiple URLs or parts of URLs by writing part sets within braces as in:</p> <pre><code>http://site.{one,two,three}.com </code></pre> <p>or you can get sequences of alphanumeric series by using [] as in:</p> <pre><code>ftp://ftp.numericals.com/file[1-100].txt ftp://ftp.numericals.com/file[001-100].txt (with leading zeros) ftp://ftp.letters.com/file[a-z].txt </code></pre> <p>No nesting of the sequences is supported at the moment, but you can use several ones next to each other:</p> <pre><code>http://any.org/archive[1996-1999]/vol[1-4]/part{a,b,c}.html </code></pre> <p>You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.</p> <p>Since curl 7.15.1 you can also specify step counter for the ranges, so that you can get every Nth number or letter:</p> <pre><code>http://www.numericals.com/file[1-100:10].txt http://www.letters.com/file[a-z:2].txt </code></pre> </blockquote> <p>You can even do :</p> <pre><code> curl -T "img[1-1000].png" ftp://ftp.picturemania.com/upload/ </code></pre> <p>But in your case, you really don't want that, so you should use the <code>-g</code> flag to tell it not to do globbing at all.</p>
<p>You should try with the <code>-g</code> aka <code>--globoff</code> cURL option.</p> <p>The default behavior is to :</p> <blockquote> <p>You can specify multiple URLs or parts of URLs by writing part sets within braces as in:</p> <pre><code>http://site.{one,two,three}.com </code></pre> <p>or you can get sequences of alphanumeric series by using [] as in:</p> <pre><code>ftp://ftp.numericals.com/file[1-100].txt ftp://ftp.numericals.com/file[001-100].txt (with leading zeros) ftp://ftp.letters.com/file[a-z].txt </code></pre> <p>No nesting of the sequences is supported at the moment, but you can use several ones next to each other:</p> <pre><code>http://any.org/archive[1996-1999]/vol[1-4]/part{a,b,c}.html </code></pre> <p>You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.</p> <p>Since curl 7.15.1 you can also specify step counter for the ranges, so that you can get every Nth number or letter:</p> <pre><code>http://www.numericals.com/file[1-100:10].txt http://www.letters.com/file[a-z:2].txt </code></pre> </blockquote> <p>You can even do :</p> <pre><code> curl -T "img[1-1000].png" ftp://ftp.picturemania.com/upload/ </code></pre> <p>But in your case, you really don't want that, so you should use the <code>-g</code> flag to tell it not to do globbing at all.</p>
48,979
<p>I've recently purchased an Ender 3 and have had great success with some Cura settings found on a YouTube Tutorial at 0.2 mm resolution.</p> <p>So then I noticed that there were default settings in Cura for the Ender 3. Except printing at 0.2 mm it selects a 20 % infill, and when choosing 0.1 mm it changed the infill to 10 %.</p> <p>I changed infill to 20 % and attempted to print this but there were gaps in the bottom layer and it won't stick to the bed. Is there anything else I need to change in the process?</p> <p>The shape is essentially a cube with a circular hole in the middle, sliced in half.</p>
<p>The more infill, the more material. The more material, the more stress is inside the part while it cools down from printing temperature to ambient temperature. Parts with higher infill density tend to warp more (the edges curl up).</p> <p>But 20 % should be fine, you shouldn't have any issue at that percentage (unless you're printing with ABS/ASA).</p> <p>I think it's a first layer issue, the 0.2 mm first layer gets more 'squished' onto the bed, thats why you get better adhesion. I'm using PrusaSlicer, every default print profile in PrusaSlicer uses a 0.2 mm first layer, maybe there is something like that in Cura too?</p> <p>For example the 0.1 mm PrusaSlicer profile will squish a 0.2 mm first layer onto the bed and changes to 0.1 mm layers for the rest of the print.</p>
<p>Basically you have 2 issues, first, an adhesion in combination with layer thickness problem, second, an infill problem.</p> <p>Starting with the infill issue, when you lower the layer height, without increasing the amount of layers for the &quot;Top/Bottom Thickness&quot;, you get a very thin shell (unless the top bottom thickness is expressed in mm). A lower layer height should, because of the lesser amount of filament being extruded over the infill, should be accompanied with a higher infill value, but that is necessary for the top layers, your issue is with the bottom layer and adhesion. As said, a lower layer height also implies lower filament flow, for the first layer this lower flow causes an inconsistent flow to adhere the filament to the bed (probably caused by the gap between the nozzle and bed from leveling with a piece of paper). Most slicers will add some extra features to increase the change to get the filament to stick to the bed; one of those is an increased first layer height (e.g. in Ultimaker Cura, the first default layer height for Ultimaker 3 printers is laarger than the rest of the layers), others include modifying the flow by e.g. over-extruding for the first layer.</p> <p>You could try to increase your first layer height to the value you create successful prints with, specify the thickness of the bottom and top (or increase the amount of layers for printing these) and increase the infill percentage.</p>
1,110
<p>Basically, we have a rule setup to run a script when a code word is detected in the body of an incoming message. The script will append the current subject header with a word in front. For example, Before: "Test Message", After: "Dept - Test Message". Any ideas?</p>
<p>Or if you need an entire script:</p> <p>Do the Run a script with the MailItem as the parameter.</p> <pre><code>Sub RewriteSubject(MyMail As MailItem) Dim mailId As String Dim outlookNS As Outlook.NameSpace Dim myMailItem As Outlook.MailItem mailId = MyMail.EntryID Set outlookNS = Application.GetNamespace("MAPI") Set myMailItem = outlookNS.GetItemFromID(mailId) ' Do any detection here With myMailItem .Subject = "Dept - " &amp; mailItem.Subject .Save End With Set myMailItem = Nothing Set outlookNS = Nothing End Sub </code></pre>
<p>Not tested:</p> <pre><code>mailItem.Subject = "Dept - " &amp; mailItem.Subject mailItem.Save </code></pre>
12,116
<p>How do you manage deploying InfoPath forms to different sharepoint servers? Is there a better way to deal all the data connections being site-specific without opening the forms, editing the data connections and republishing for each environment?</p>
<p>If I understand your scenario correctly:</p> <p>You have an InfoPath form, with data connections that submit your data. You wish to deploy this form on multiple SharePoint Servers and have those data connections submit data to the currently deployed server.</p> <p>You can't really get around needing to do work on every SharePoint server that you would want to deploy the form to. However, you can get around needing to modify the InfoPath Form Template.</p> <p>If you use the SharePoint Data Connection Library (DCL), and create a UDC file from your data connection, on every SharePoint Server that you would want to use...then your InfoPath Template can just talk to the UDC file.</p> <p>Here's a link to an article about integrating InfoPath with SharePoint's DCL:</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb267335.aspx" rel="nofollow noreferrer" title="Integrating InfoPath 2007 with the Data Connection Library">http://msdn.microsoft.com/en-us/library/bb267335.aspx</a></p>
<p>By site-specific, do you mean that the data connections in your forms refer to the server the form is deployed to? If that's the case perhaps you could tweak your connections to use localhost instead of the server name for the hostname part of the data connection URLs.</p>
4,076
<p>I am writing an application with a hand-crafted domain model (classes) and a hand-crafted data model (tables/relationships), and letting NHibernate take care of the mapping.</p> <p>Is it best to tell the database to perform cascading updates or deletes or to tell NHibernate to do it (cascade="all-delete-orphan")? Can they both be set up to do it at the same time?</p>
<p>I prefer to let NHibernate do this for me. It's easier to setup and it works well.</p> <p>cascade: all-delete-orphan is something that you wouldn't be able to do in SQL without a trigger, so there's another reason</p>
<blockquote> <p>Can they both be set up to do it at the same time?</p> </blockquote> <p>I think if you try, you might get NHibernate complaining, as most of it's operations check the row count to ensure that the expect number of rows were inserted/updated/deleted.</p> <p>As Ben says, get NHibernate to do it. </p> <p>Ultimately, NHibernate (and ORMs in general) let you think of the database as a storage and retrieval mechanism. You still want to create constraints, primary keys, foreign keys, and indexes, but the ORM should obey these rules anyway. As with any data-access scenerio, if you find yourself creating complex constraints in the database, then remember that these rules will have to be duplicated in your application.</p>
20,134
<p>I just came across the proposed <a href="http://web.archive.org/web/20171008232044/http://dancinghacker.com:80/code/dataflow/dataflow/introduction/dataflow.html" rel="nofollow noreferrer">Boost::Dataflow</a> library. It seems like an interesting approach and I was wondering if there are other such alternative frameworks for C++, and if there are any related design patterns. I have not ruled out Boost::Dataflow, I am just looking into any available alternatives so I can understand the domain and my options better (or roll my own if necessary).</p>
<p><strong>Wikipedia</strong></p> <p>There are a couple of good articles in the Wikipedia about the theory of the dataflow programming:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Dataflow" rel="nofollow noreferrer">Dataflow</a></li> <li><a href="http://en.wikipedia.org/wiki/Dataflow_programming" rel="nofollow noreferrer">Dataflow programming</a></li> <li><a href="http://en.wikipedia.org/wiki/Flow-based_programming" rel="nofollow noreferrer">Flow based programming</a></li> <li><a href="http://en.wikipedia.org/wiki/Actor_model" rel="nofollow noreferrer">Actor model</a></li> <li><a href="http://en.wikipedia.org/wiki/Visual_programming" rel="nofollow noreferrer">Visual programming</a></li> </ul> <p>These articles are written by various authors, so there are some overlaps, and some important stuff are missing, but it is a very good start point.</p> <p><strong>TinyOS</strong></p> <p>This is an open source operating system based on the dataflow principle. I have bad feelings about that: they don't even mention the term "dataflow". Altough, it is that, and maybe it's <a href="http://www.tinyos.net/" rel="nofollow noreferrer">worth studying it</a>.</p>
<p>If your area is sound generation/processing, use <a href="http://www.synthedit.com/" rel="nofollow noreferrer">http://www.synthedit.com/</a> </p> <p>It looks promising, I've found a good answers for a deep problem in the SDK docs (polyphony). Funny, but they don't mention the word <em>dataflow</em>.</p>
9,753
<p>Can someone post a simple example of starting two (Object Oriented) threads in C++. </p> <p>I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.</p> <p>I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.</p>
<p>Create a function that you want the thread to execute, for example:</p> <pre><code>void task1(std::string msg) { std::cout &lt;&lt; &quot;task1 says: &quot; &lt;&lt; msg; } </code></pre> <p>Now create the <code>thread</code> object that will ultimately invoke the function above like so:</p> <pre><code>std::thread t1(task1, &quot;Hello&quot;); </code></pre> <p>(You need to <code>#include &lt;thread&gt;</code> to access the <code>std::thread</code> class.)</p> <p>The constructor's first argument is the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.</p> <p>If later on you want to wait for the thread to be done executing the function, call:</p> <pre><code>t1.join(); </code></pre> <p>(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution.)</p> <hr /> <h2>The Code</h2> <pre><code>#include &lt;string&gt; #include &lt;iostream&gt; #include &lt;thread&gt; using namespace std; // The function we want to execute on the new thread. void task1(string msg) { cout &lt;&lt; &quot;task1 says: &quot; &lt;&lt; msg; } int main() { // Constructs the new thread and runs it. Does not block execution. thread t1(task1, &quot;Hello&quot;); // Do other things... // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution. t1.join(); } </code></pre> <p><a href="http://en.cppreference.com/w/cpp/thread/thread" rel="noreferrer">More information about std::thread here</a></p> <ul> <li><em>On GCC, compile with <code>-std=c++0x -pthread</code>.</em></li> <li><em>This should work for any operating-system, granted your compiler supports this (<a href="https://en.wikipedia.org/wiki/C%2B%2B11" rel="noreferrer">C++11</a>) feature.</em></li> </ul>
<p>It largely depends on the library you decide to use. For instance, if you use the <a href="https://en.wikipedia.org/wiki/WxWidgets" rel="nofollow noreferrer">wxWidgets</a> library, the creation of a thread would look like this:</p> <pre><code>class RThread : public wxThread { public: RThread() : wxThread(wxTHREAD_JOINABLE){ } private: RThread(const RThread &amp;copy); public: void *Entry(void){ //Do... return 0; } }; wxThread *CreateThread() { //Create thread wxThread *_hThread = new RThread(); //Start thread _hThread-&gt;Create(); _hThread-&gt;Run(); return _hThread; } </code></pre> <p>If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your &quot;Entry&quot; method. You'll have to keep a reference to the thread in most cases to join or stop it.</p> <p>More information is in the <a href="http://docs.wxwidgets.org/stable/wx_wxthread.html#wxthread" rel="nofollow noreferrer">wxThread documentation</a>.</p>
33,371
<p>I have a lot of classes in the App_Code directory could this be a problem? Would it build faster if it was in a separate library?</p> <p>Any other tips?</p>
<p>There's a decent article <a href="http://weblogs.asp.net/bradleyb/archive/2005/12/06/432441.aspx" rel="nofollow noreferrer">here</a>. Items listed there are:</p> <ul> <li>Do not disable batch compilation</li> <li>Leverage Server-side Compilation</li> <li>Move App_Code files into a separate class library project</li> <li>Check for conflicting dependencies</li> <li>Turn off AutoToolboxPopulate in the Windows Forms Designer options.</li> <li>Disable validation for HTML editing</li> </ul>
<p>I would recommend a second project, let's say "MyLibrary", instead of having a bloated App_Code folder.</p>
21,429
<p>How can I match (PCRE) everything inbetween two tags?</p> <p>I tried something like this:</p> <blockquote> <p>&lt;!--\s&#42;LoginStart\s&#42;--&gt;(.*)&lt;!--\s&#42;LoginEnd\s&#42;--&gt;</p> </blockquote> <p>But it didn't work out too well for me..</p> <p>I'm kind of new to regular expressions, so I was hoping if someone would be kind enough to explain to me how I would accomplish this, if its even possible with regular expressions.</p> <p>Thanks</p>
<pre><code>$string = '&lt;!-- LoginStart --&gt;&lt;div id="stuff"&gt;text&lt;/div&gt;&lt;!-- LoginEnds --&gt;'; $regex = '#&lt;!--\s*LoginStart\s*--&gt;(.*?)&lt;!--\s*LoginEnds\s*--&gt;#s'; preg_match($regex, $string, $matches); print_r($matches); // $matches[1] = &lt;div id="stuff"&gt;text&lt;/div&gt; </code></pre> <p>explanations:</p> <pre><code>(.*?) = non greedy match (match the first &lt;!-- LoginEnds --&gt; it finds s = modifier in $regex (end of the variable) allows multiline matches such as '&lt;!-- LoginStart --&gt;stuff more stuff &lt;!-- LoginEnds --&gt;' </code></pre>
<p>i have tried Owen's answer but its fails for the conditions like</p> <p><code>&lt;!-- LoginStart --&gt;&lt;div id="stuff"&gt;text&lt;/div&gt;&lt;!-- LoginEnds --&gt;<b>"DONT MIND THIS"</b>&lt;!-- LoginStart --&gt;&lt;div id="stuff"&gt;text&lt;/div&gt;&lt;!-- LoginEnds --&gt;</code></p> <p>This includes the line "DONT MIND THIS" also, that is it covers all the contents within first &lt;!-- LoginStart --&gt; and last &lt;!-- LoginEnds --&gt; tag</p>
36,644
<p>For data types such as std::set and std::map where lookup occurs in logarithmic time, is the implementation required to maintain the begin and end iterators? Does accessing begin and end imply a lookup that could occur in logarithmic time?</p> <p>I have always assumed that begin and end always occur in constant time, however I can't find any confirmation of this in Josuttis. Now that I'm working on something where I need to be anal about performance, I want to make sure to cover my bases.</p> <p>Thanks</p>
<p>They happen in constant time. I'm looking at page 466 of the ISO/IEC 14882:2003 standard:</p> <p><strong>Table 65 - Container Requiments</strong></p> <p>a.begin(); <em>(constant complexity)</em></p> <p>a.end(); <em>(constant complexity)</em></p> <p><strong>Table 66 - Reversible Container Requirements</strong></p> <p>a.rbegin(); <em>(constant complexity)</em></p> <p>a.rend(); <em>(constant complexity)</em></p>
<p>For std::set</p> <p>begin: constant, end: constant, rbegin: constant, rend: constant, </p> <p>For std::map</p> <p>they are also constant (all of them)</p> <p>if you have any doubt, just check <a href="http://www.cplusplus.com" rel="nofollow noreferrer">www.cplusplus.com</a></p>
10,920
<p>I'm looking for a free templating engine to generate simple reports. I want some basic features such as :</p> <ul> <li>Ability to Write Loops (with any IEnumerable)</li> <li>Passing Variables</li> <li>Passing Templates Files (main template, footer, header)</li> </ul> <p>I'll use this to generate reports in HTML and XML. I'm not looking for a ASP.NET Template Engine.</p> <p>This is for a WinForms applications.</p> <p>I've seen this question <a href="https://stackoverflow.com/questions/340095/can-you-recommend-a-net-template-engine">Can you recommend a .net template engine?</a>, however all of those template engines are total overkill for me and focused for ASP.NET.</p> <p>Please only recommend free libraries.</p> <p>// I'm still looking an NVelocity but it doesn't look any promising for .NET, overly complicated, when you download it's bunch of files not clear what to do, no tutorial, startup document etc.</p>
<p>I second not recommending nVelocity. It is a horrible port.</p> <p>.NET actually has built in templating abilities by using CodeDOM.</p> <p>Here is a pretty good walkthrough of how to do it:</p> <p><a href="http://www.codeproject.com/KB/cs/smarttemplateengine.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/smarttemplateengine.aspx</a></p> <p>With some minor coding, you'll be able to create templates that have inline C#:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;My Report&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;% foreach (ReportRow r in ReportData) { %&gt; &lt;!-- Markup and Code for Report --&gt; &lt;% } %&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>Thanks for the help, CodeDOM specifically showed me a nice way, now I'm working with this : <a href="http://www.stefansarstedt.com/templatemaschine.html" rel="nofollow noreferrer">http://www.stefansarstedt.com/templatemaschine.html</a></p> <p>It's not the best and a bit dirty but doing the trick for me. It's LGPL which fits me, and short. </p> <p>I've looked at the other suggestions but didn't like them, too complicated for what I want (and quite messy -tons of DLLs, dependencies etc.-)</p>
45,080
<p>Currently I have this (edited after reading advice):</p> <pre><code>struct Pair&lt;T, K&gt; : IEqualityComparer&lt;Pair&lt;T, K&gt;&gt; { readonly private T _first; readonly private K _second; public Pair(T first, K second) { _first = first; _second = second; } public T First { get { return _first; } } public K Second { get { return _second; } } #region IEqualityComparer&lt;Pair&lt;T,K&gt;&gt; Members public bool Equals(Pair&lt;T, K&gt; x, Pair&lt;T, K&gt; y) { return x.GetHashCode(x) == y.GetHashCode(y); } public int GetHashCode(Pair&lt;T, K&gt; obj) { int hashCode = obj.First == null ? 0 : obj._first.GetHashCode(); hashCode ^= obj.Second == null ? 0 : obj._second.GetHashCode(); return hashCode; } #endregion public override int GetHashCode() { return this.GetHashCode(this); } public override bool Equals(object obj) { return (obj != null) &amp;&amp; (obj is Pair&lt;T, K&gt;) &amp;&amp; this.Equals(this, (Pair&lt;T, K&gt;) obj); } } </code></pre> <p>The problem is that First and Second may not be reference types (VS actually warns me about this), but the code still compiles. Should I cast them (First and Second) to objects before I compare them, or is there a better way to do this?</p> <p>Edit: Note that I <em>want</em> this struct to support value and reference types (in other words, constraining by class is not a valid solution)</p> <p>Edit 2: As to what I'm trying to achieve, I want this to work in a Dictionary. Secondly, SRP isn't important to me right now because that isn't really the essence of this problem - it can always be refactored later. Thirdly, comparing to default(T) will not work in lieu of comparing to null - try it.</p>
<p>It looks like you need IEquatable instead:</p> <pre><code>internal struct Pair&lt;T, K&gt; : IEquatable&lt;Pair&lt;T, K&gt;&gt; { private readonly T _first; private readonly K _second; public Pair(T first, K second) { _first = first; _second = second; } public T First { get { return _first; } } public K Second { get { return _second; } } public bool Equals(Pair&lt;T, K&gt; obj) { return Equals(obj._first, _first) &amp;&amp; Equals(obj._second, _second); } public override bool Equals(object obj) { return obj is Pair&lt;T, K&gt; &amp;&amp; Equals((Pair&lt;T, K&gt;) obj); } public override int GetHashCode() { unchecked { return (_first != null ? _first.GetHashCode() * 397 : 0) ^ (_second != null ? _second.GetHashCode() : 0); } } } </code></pre>
<p>Regarding the warning, you can use default(T) and default(K) instead of null.</p> <p>I can't see what you're trying to achieve, but you shouldn't be using the hashcode to compare for equality - there is no guarantee that two different objects won't have the same hashcode. Also even though your struct is immutable, the members _first and _second aren't.</p>
14,688
<p>Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container?</p> <p>For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarchy of files and configuration locations to see which if any are available to determine which implementation class to instantiate - for example, </p> <ol> <li>a properties file in the classpath,</li> <li>a web.xml parameter, </li> <li>a system property, or </li> <li>some default logic if nothing else is available. </li> </ol> <p>I'd like to be able to do this without injecting any reference to <code>ServletConfig</code> or anything similiar to my Factory - the code should be able to run ok outside of a Servlet Container.</p> <p>This might sound a little bit uncommon, but I'd like for this component I'm working on to be able to be packaged with one of our webapps, and also be versatile enough to be packaged with some of our command-line tools without requiring a new properties file just for my component - so I was hoping to piggyback on top of other configuration files such as web.xml.</p> <p>If I recall correctly, .NET has something like <code>Request.GetCurrentRequest()</code> to get a reference to the currently executing <code>Request</code> - but since this is a Java app I'm looking for something simliar that could be used to gain access to <code>ServletConfig</code>.</p>
<p>One way you could do this is:</p> <pre><code>public class FactoryInitialisingServletContextListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent event) { } public void contextInitialized(ServletContextEvent event) { Properties properties = new Properties(); ServletContext servletContext = event.getServletContext(); Enumeration&lt;?&gt; keys = servletContext.getInitParameterNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = servletContext.getInitParameter(key); properties.setProperty(key, value); } Factory.setServletContextProperties(properties); } } public class Factory { static Properties _servletContextProperties = new Properties(); public static void setServletContextProperties(Properties servletContextProperties) { _servletContextProperties = servletContextProperties; } } </code></pre> <p>And then have the following in your web.xml</p> <pre><code>&lt;listener&gt; &lt;listener-class&gt;com.acme.FactoryInitialisingServletContextListener&lt;listener-class&gt; &lt;/listener&gt; </code></pre> <p>If your application is running in a web container, then the listener will be invoked by the container once the context has been created. In which case, the _servletContextProperties will be replaced with any context-params specified in the web.xml.</p> <p>If your application is running outside a web container, then _servletContextProperties will be empty.</p>
<p>I think that you will have to add an associated bootstrap class which takes a reference to a ServletConfig (or ServletContext) and transcribes those values to the Factory class. At least this way you can package it separately.</p> <p>@toolkit : Excellent, most humbled - This is something that I have been trying to do for a while</p>
6,302
<p>I'm having an issue setting up one of my projects in TeamCity (v4.0), specifically when it comes to using Object Initializers.</p> <p>The project builds fine normally, however it would seem that TeamCity transforms the build file into something it likes (some MSBuild mutation) and when it comes to compiling the code for a part of the solution it balks when it sees an Object Initializer.</p> <p>Specifically the errors are:</p> <pre><code>[11:16:21]: ErrorView.xaml.cs(22, 187): error CS1026: ) expected [11:16:21]: ErrorView.xaml.cs(22, 208): error CS0116: A namespace does not directly contain members such as fields or methods [11:16:21]: ErrorView.xaml.cs(27, 16): error CS1518: Expected class, delegate, enum, interface, or struct [11:16:21]: ErrorView.xaml.cs(35, 16): error CS1518: Expected class, delegate, enum, interface, or struct [11:16:21]: ErrorView.xaml.cs(46, 91): error CS1031: Type expected [11:16:21]: ErrorView.xaml.cs(46, 119): error CS0116: A namespace does not directly contain members such as fields or methods [11:16:21]: ErrorView.xaml.cs(48, 17): error CS1022: Type or namespace definition, or end-of-file expected </code></pre> <p>When I look into this further it would seem the problem ties back to the transformation of the build file to TeamCity format using CSC from the v2.0 framework directory.</p> <p>Is it possible to compile code using object initializers (a .NET 3.0 feature) with the .NET 2.0 compiler (I would assume not, though I may be missing something), and if not, does anyone know a way to force it to use the 3.0 compiler (if one exists) or the 3.5 compiler?</p> <p>For those interested, the CSC command being executed is:</p> <pre><code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /reference:..\..\..\build\blah.Logging.dll /reference:..\..\..\build\blah.Presentation.Interfaces.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.VisualBasic.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationCore.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationFramework.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationFramework.Luna.dll" /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationProvider.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll" /debug+ /debug:full /filealign:512 /keyfile:..\..\..\resources\blah.snk /optimize- /out:obj\Debug\blah.dll /resource:obj\Debug\blah.UserInterface.Properties.Resources.resources /resource:obj\Debug\blah.UserInterface.blah.exe.license /target:library /win32icon:blah.ico SignalStrengthIndicator.xaml.cs TrayNotifier.xaml.cs ConnectedView.xaml.cs ConnectionProgressView.xaml.cs NetworkPasswordView.xaml.cs TrayProgress.xaml.cs NetworkConnectionView.xaml.cs ClassFiles\NetworkTypeConverter.cs ClassFiles\SecurityImageConverter.cs ClassFiles\SecurityTooltipConverter.cs ClassFiles\SignalStrengthTooltipConverter.cs ClassFiles\SignalVisibilityConverter.cs ClassFiles\SynchronizedObservableCollection.cs ConnectionOption.xaml.cs DisconnectionProgressView.xaml.cs ErrorView.xaml.cs ..\..\..\config\assemblyversion.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs </code></pre> <p>Thanks!</p> <p>Update: I have partially (read: I'm not happy with it) fixed the problem by changing the build runner from Nant to command runner - this just executed the Nant build file as it was intended without any manipulation, though the feedback level is different. Any other suggestions would be appreciated.</p>
<p>Are you using the sln2005 build runner? That will use the 2.0 csc. Check your build configuration and change it to the sln2008 runner ( see <a href="http://www.jetbrains.net/confluence/display/TCD4/3.Build+Runners" rel="nofollow noreferrer">http://www.jetbrains.net/confluence/display/TCD4/3.Build+Runners</a> ). That should use the 3.5 compiler.</p> <p>If you are using the MSBuild runner <a href="http://www.jetbrains.net/confluence/display/TCD4/MSBuild" rel="nofollow noreferrer">http://www.jetbrains.net/confluence/display/TCD4/MSBuild</a> check that you have set the version number to 3.5 on the configuration page.</p> <p>Edit: after checking up on NAnt See <a href="http://www.jetbrains.net/confluence/display/TCD4/NAnt_" rel="nofollow noreferrer">http://www.jetbrains.net/confluence/display/TCD4/NAnt_</a></p> <p>where it says: "By default, NAnt msbuild task uses MSBuild 2.0 (from Microsoft .NET Framework 2.0), however you can use MSBuild 3.5 (from Microsoft .NET Framework 3.5) if you add the teamcity_dotnet_use_msbuild_v35 property with the value of true to your msbuild task in NAnt script. For example:"</p> <pre><code>&lt;msbuild project="SimpleEcho.v35.proj"&gt; &lt;!-- this property enables MSBuild 3.5 --&gt; &lt;property name="teamcity_dotnet_use_msbuild_v35" value="true"/&gt; ... &lt;/msbuild&gt; </code></pre>
<p>For NAnt script one may simply define system property teamcity_dotnet_use_msbuild_v35 in the build configuration settings ( <a href="http://www.jetbrains.net/confluence/display/TCD4/6.Properties+and+environment+variables" rel="nofollow noreferrer">http://www.jetbrains.net/confluence/display/TCD4/6.Properties+and+environment+variables</a>) to make it run msbuild 3.5.</p> <p>On the other hand, if NAnt target framework is set to net-3.5 (only for NAnt 0.86 beta 1) msbuild should be taken from .NET 3.5 folder.</p>
48,832
<p>In WPF, how would I apply multiple styles to a <code>FrameworkElement</code>? For instance, I have a control which already has a style. I also have a separate style which I would like to add to it without blowing away the first one. The styles have different TargetTypes, so I can't just extend one with the other.</p>
<p><strong>I think the simple answer is that you can't do (at least in this version of WPF) what you are trying to do.</strong></p> <p><em>That is, for any particular element only one Style can be applied.</em></p> <p>However, as others have stated above, maybe you can use <code>BasedOn</code> to help you out. Check out the following piece of loose xaml. In it you will see that I have a base style that is setting a property that exists on the base class of the element that I want to apply two styles to. And, in the second style which is based on the base style, I set another property.</p> <p><strong>So, the idea here ... is if you can somehow separate the properties that you want to set ... according the inheritance hierarchy of the element you want to set multiple styles on ... you might have a workaround.</strong></p> <pre><code>&lt;Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Page.Resources&gt; &lt;Style x:Key="baseStyle" TargetType="FrameworkElement"&gt; &lt;Setter Property="HorizontalAlignment" Value="Left"/&gt; &lt;/Style&gt; &lt;Style TargetType="Button" BasedOn="{StaticResource baseStyle}"&gt; &lt;Setter Property="Content" Value="Hello World"/&gt; &lt;/Style&gt; &lt;/Page.Resources&gt; &lt;Grid&gt; &lt;Button Width="200" Height="50"/&gt; &lt;/Grid&gt; &lt;/Page&gt; </code></pre> <p><br> Hope this helps.</p> <p><strong>Note:</strong></p> <p>One thing in particular to note. If you change the <code>TargetType</code> in the second style (in first set of xaml above) to <code>ButtonBase</code>, the two Styles do not get applied. However, check out the following xaml below to get around that restriction. Basically, it means you need to give the Style a key and reference it with that key.</p> <pre><code>&lt;Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Page.Resources&gt; &lt;Style x:Key="baseStyle" TargetType="FrameworkElement"&gt; &lt;Setter Property="HorizontalAlignment" Value="Left"/&gt; &lt;/Style&gt; &lt;Style x:Key="derivedStyle" TargetType="ButtonBase" BasedOn="{StaticResource baseStyle}"&gt; &lt;Setter Property="Content" Value="Hello World"/&gt; &lt;/Style&gt; &lt;/Page.Resources&gt; &lt;Grid&gt; &lt;Button Width="200" Height="50" Style="{StaticResource derivedStyle}"/&gt; &lt;/Grid&gt; &lt;/Page&gt; </code></pre>
<p><strong>If you are trying to apply a unique style to just one single element</strong> as an addition to a base style, there is a completely different way to do this that is IMHO much better for readable and maintainable code.</p> <p>It's extremely common to need to tweak parameters per individual element. Defining dictionary styles just for use on one-element is extremely cumbersome to maintain or make sense of. To avoid creating styles just for one-off element tweaks, read my answer to my own question here here:</p> <p><a href="https://stackoverflow.com/a/54497665/1402498">https://stackoverflow.com/a/54497665/1402498</a></p>
3,680
<p>Virtualizing the mobile is way different from virtualizing the server or the desktop, where in the the hardware components are almost standardized [like the keyboard, mouse , usb, LAN etc] so the hardware could be easily abstracted for any of the OS.</p> <p>While on a mobile there is a multitude of hardware [like the iphone touch screen, stylus ... other add ons ] and there is a very less interoperability among all the types of phones or there is very less feature set common to all the mobile hardware. One cannot use iphone gestures on a nokia phone that doesnot have a touch surface. </p> <p>What drives one to virtualize the mobile ? </p>
<p>Not everyone can afford to supply their testers/developers with full-blown mobiles. That's when virtualization comes into game as nearly everyone today has a computer capable of running some kind of VM.</p>
<p>There's also the twin drives of:</p> <ul> <li>It's useful for cases like S60 and Windows mobile where there isn't the gulf between hardware (or perhaps virtualise your android mobile so you can use WM until android stops being shaky and having huge root exploits :))</li> <li>Because they can</li> </ul> <p>I'm interested in this from the developer side though, as I have to develop for symbian all the time, and it could reduce the number of phone variants I have to developer test on :)</p>
38,132
<p>To add a svg graphics in html page, it is common to use object tag to wrap it like this:</p> <pre><code>&lt;object id="svgid" data="mysvg.svg" type="image/svg+xml" wmode="transparent" width="100" height="100"&gt; this browser is not able to show SVG: &lt;a linkindex="3" href="http://getfirefox.com"&gt;http://getfirefox.com&lt;/a&gt; is free and does it! If you use Internet Explorer, you can also get a plugin: &lt;a linkindex="4" href="http://www.adobe.com/svg/viewer/install/main.html"&gt; http://www.adobe.com/svg/viewer/install/main.html&lt;/a&gt; &lt;/object&gt; </code></pre> <p>If you do not use width and height attributes in the object tag, the svg will be displayed in full size. Normally I get svg files from Open Graphics Library for testing. Is there any way to get svg's size by using JavaScript? Or maybe I should just look at the svg xml file to find out the size from the top svg tag?</p>
<p><strong>> Is there any way to get svg's size by using JavaScript?</strong></p> <p>No and yes.</p> <p><strong>No:</strong></p> <p>JavaScript won't be able to access the SVG file contents that are sitting in the browser.</p> <p>So it wouldn't be possible to have a page containing an arbitrary SVG image and then have JavaScript determine anything from the SVG file itself.</p> <p>The only data JS can access it that contained within the page's DOM: the original markup plus any JS-related modifications to the DOM. You could access the <code>object</code> element's attributes and descendant nodes, but that won't give you visibility of anything more than what you can see if you look at the page markup yourself.</p> <p><strong>Yes:</strong></p> <p>JS (in modern browsers) can parse any XML string into a DOM and then access the content using DOM-based methods.</p> <p>You could get the SVG file contents by issuing an xmlHttpRequest-style request (i.e. JS performs an HTTP GET on the SVG file's URL). JS would then have the SVG file's full XML string and you can then access anything you like.</p> <p><strong>> Or maybe I should just look at the svg xml file to find out the size from the top svg tag?</strong></p> <p>This would be more feasible by far.</p> <p>The only JS-based solution would require JS to perform a GET request on the SVG file's URL (as above), which is unlikely to be feasible - each page load might result in double-downloading each SVG file, and the parsing of the SVG's XML into a DOM by JS might be too resource intensive.</p> <p>Having JS retrieve the SVG's XML content and parse it into a DOM to retrieve only the image dimensions is a bit overkill. It's perfectly possible, but generally not practical.</p> <p>Querying the SVG's XML content server-side, determining a suitable width and height and then dynamically adding the <code>width</code> and <code>height</code> attributes prior to returning markup to the browser would be your best bet.</p>
<blockquote> <p>Is there any way to get svg's size by using JavaScript?</p> </blockquote> <p><strong>YES</strong></p> <pre><code>var filesize = function(url, requestHandler) { var requestObj = new XMLHttpRequest(); requestObj.open('head', address, true); requestObj.onreadystatechange = callback; requestObj.send(null); }; </code></pre> <p>Now a handling function:</p> <pre><code>var requestHandler = function(result) { if (this.readyState === 1) { this.abort(); } return this.getResponseHeader("Content-length"); }; var size = fileSize("http://whatever.org/someSVGFile.svg", requestHandler); alert(size); </code></pre> <p>That should return the filesize of your svg or any other file without a hitch. Server configuration is the only thing that might interfere.</p>
28,677
<p>Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this? Thanks!</p> <pre><code>def unique_filename(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while os.path.isfile(file_name): file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 return file_name </code></pre> <p>I really <em>do</em> require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.</p>
<p>One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program running with a higher privilege could) Attacks like these are why things like os.tempnam() are deprecated.</p> <p>To get around it, the best approach is to actually try create the file in such a way that you'll get an exception if it fails, and on success, return the actually opened file object. This can be done with the lower level os.open functions, by passing both the os.O_CREAT and os.O_EXCL flags. Once opened, return the actual file (and optionally filename) you create. Eg, here's your code modified to use this approach (returning a (file, filename) tuple):</p> <pre><code>def unique_file(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while 1: try: fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW) return os.fdopen(fd), file_name except OSError: pass file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 </code></pre> <p><strong>[Edit]</strong> Actually, a better way, which will handle the above issues for you, is probably to use the tempfile module, though you may lose some control over the naming. Here's an example of using it (keeping a similar interface):</p> <pre><code>def unique_file(file_name): dirname, filename = os.path.split(file_name) prefix, suffix = os.path.splitext(filename) fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname) return os.fdopen(fd), filename &gt;&gt;&gt; f, filename=unique_file('/home/some_dir/foo.txt') &gt;&gt;&gt; print filename /home/some_dir/foo_z8f_2Z.txt </code></pre> <p>The only downside with this approach is that you will always get a filename with some random characters in it, as there's no attempt to create an unmodified file (/home/some_dir/foo.txt) first. You may also want to look at tempfile.TemporaryFile and NamedTemporaryFile, which will do the above and also automatically delete from disk when closed.</p>
<p>How about </p> <pre><code>def ensure_unique_filename(orig_file_path): from time import time import os if os.path.lexists(orig_file_path): name, ext = os.path.splitext(orig_file_path) orig_file_path = name + str(time()).replace('.', '') + ext return orig_file_path </code></pre> <p>time() returns current time in milliseconds. combined with original filename, it's fairly unique even in complex multithreaded cases.</p>
22,184
<pre><code>rsync -auve ssh --backup --suffix='2008-10-03-1514539' --backup-dir='/tmp/' module.pm root@web1:/path/to/module.pm </code></pre> <p>I run this command without the --backup-dir option and when it copies the file over, it creates a backup with a current timestamp. When I include the --backup-dir option, it makes the backup into the /tmp/ directory but never attaches my suffix. </p> <p>There is nothing in the <a href="http://samba.anu.edu.au/ftp/rsync/rsync.html" rel="nofollow noreferrer">manual</a> to suggest that you can't use both these options together. I've played around with the order also and nothing seems to fix it.</p> <p>Does anyone have a solution to this?</p>
<p>the manual says:</p> <blockquote> <p>--backup make backups (see --suffix &amp; --backup-dir)</p> <p>--backup-dir=DIR make backups into hierarchy based in DIR</p> <p>--suffix=SUFFIX backup suffix (default ~ w/o --backup-dir)</p> </blockquote> <p>so it seems that you can use one or the other, not both (as I guess you want a way to determine what's a backup you use a suffix or a directory).</p> <p>As a way to fix this, why don't you keep the suffix and modify the destination to include the backup directory.</p>
<p>You could also use something like this </p> <pre><code># Backup mkdir -p /tmp/`date +\%Y-\%m-\%d`-`date +\%A`/ rsync -avz /tmp/`date --date=yesterday +\%Y-\%m-\%d`-`date --date=yesterday +\%A`/ /tmp/`date +\%Y-\%m-\%d`-`date +\%A`/ rsync -avz -e ssh root@web1:/path/to/module.pm /tmp/`date +\%Y-\%m-\%d`-`date +\%A`/ </code></pre>
20,196
<p>Is there <strong>any</strong> way (maybe directly editing resource files) to configure a Tab Control (add/remove tabs and their captions and contents) at <strong>design time</strong> with Visual Studio 2008 without SP1 (I heard that SP1 has such feature)? P.S.: I use c++ with wtl</p>
<p>There are various schemas which are effective, each with their own performance implications for the common queries you'll need as the number of tagged items grows:</p> <ul> <li><a href="http://howto.philippkeller.com/2005/04/24/Tags-Database-schemas/" rel="noreferrer">http://howto.philippkeller.com/2005/04/24/Tags-Database-schemas/</a></li> <li><a href="http://howto.philippkeller.com/2005/06/19/Tagsystems-performance-tests/" rel="noreferrer">http://howto.philippkeller.com/2005/06/19/Tagsystems-performance-tests/</a></li> </ul> <p>Personally, I like having a tag table and a link table which associates tags with items, as it's denormalized (no duplication of tag names) and I can store additional information in the link table (such as when the item was tagged) when necessary.</p> <p>You can also add some denormalised data if you're feeling frisky and want simple selects at the cost of the additional data maintenance required by storing usage counts in the tag table, or storing tag names which were used in the item table itself to avoid hitting the link table and tag table for each item, which is useful for displaying multiple items with all their tags and for simple tag versioning... if you're into that sort of thing ;)</p>
<p>In my app BugTracker.NET, I make an assumption that there won't be TOO many bugs. Maybe tens of thousands, but not tens of millions. That assumption allows me to cache the tags and the ids of the items they reference.</p> <p>In the database, the tags are stored as they are entered, with the bugs, in a comma delimited text field.</p> <p>When a tag field is added or changed, that kicks off a background thread that selects all bugids and their tags, parses the text, building a map where the key is the tag and the value is a list of all the ids that have that tag. I then cache that map in the Asp.Net Application object.</p> <p>Below is the code I've just described.</p> <p>The code could be optimized so that instead of going through all the bugs it just incrementally modified the cached map, but even unoptimized, it works fine.</p> <p>When somebody does a search using a tag, I look up the value in the map, get the list of ids, and then fetch those bugs using SQL with "where id in (1, 2, 3...)" clause. </p> <pre><code> public static void threadproc_tags(object obj) { System.Web.HttpApplicationState app = (System.Web.HttpApplicationState)obj; SortedDictionary&lt;string,List&lt;int&gt;&gt; tags = new SortedDictionary&lt;string,List&lt;int&gt;&gt;(); // update the cache DbUtil dbutil = new DbUtil(); DataSet ds = dbutil.get_dataset("select bg_id, bg_tags from bugs where isnull(bg_tags,'') &lt;&gt; ''"); foreach (DataRow dr in ds.Tables[0].Rows) { string[] labels = btnet.Util.split_string_using_commas((string) dr[1]); // for each tag label, build a list of bugids that have that label for (int i = 0; i &lt; labels.Length; i++) { string label = normalize_tag(labels[i]); if (label != "") { if (!tags.ContainsKey(label)) { tags[label] = new List&lt;int&gt;(); } tags[label].Add((int)dr[0]); } } } app["tags"] = tags; } </code></pre>
20,802
<p>I am using a Visual Studio project with custom build script/batch file (ala make, ant, etc.).</p> <p>When the build is run from the command line we have placed colored highlighting on various output lines.</p> <p>However, when built via Visual Studio (2005 in my case) the output window does not show the color anymore.</p> <p>Is this possible? I am quite happy to put specific code into the build script if required.</p>
<p>If you don't want to go with the pro version of the VSCommands plug-in, there is a free one called VSColorOutput, which does just that. I've worked with it a bit, does what it says.</p> <p>See <a href="http://coolthingoftheday.blogspot.com/2011/12/vscoloroutput-visual-studio-output.html" rel="noreferrer">http://coolthingoftheday.blogspot.com/2011/12/vscoloroutput-visual-studio-output.html</a> or look it up in the extension gallery.</p>
<p>The problem isn't with your build scripts, but with Visual Studio not supporting <a href="http://en.wikipedia.org/wiki/ANSI_escape_code" rel="noreferrer">ANSI control codes</a> to change the color.</p>
7,245
<p>Generally, what's the best way to tackle a layout bug in IE6? What are the most common bugs or problems that one should look for when trying to figure out why your page suddenly looks like a monkey coded it?</p>
<h2>First Things First</h2> <p>Get yourself the <a href="http://www.microsoft.com/en-us/download/details.aspx?id=18359" rel="nofollow noreferrer">Internet Explorer Developer Toolbar</a>. It's a life saver and works great with IE6 and/or IE7. It's no replacement for Web Developer Toolbar or Firebug for Firefox, but it's better than nothing.</p> <h2>Know Thy Enemy</h2> <p>Read up on the quirks of IE &mdash; particularly <a href="http://www.satzansatz.de/cssd/onhavinglayout.html" rel="nofollow noreferrer">hasLayout</a> and <a href="http://www.positioniseverything.net/explorer/expandingboxbug.html" rel="nofollow noreferrer">overflow</a> and the like. There are also many CSS niceties that you'll have to either <a href="http://wordpress.com/tag/max-width-not-working-in-ie6/" rel="nofollow noreferrer">do without</a> or find <a href="http://www.seopher.com/articles/ie6_min_max_width_hack" rel="nofollow noreferrer">alternatives</a>. Look into how many of the popular JavaScript <a href="http://dojotoolkit.org/" rel="nofollow noreferrer">toolkits</a>/<a href="http://mootools.net/" rel="nofollow noreferrer">frameworks</a>/<a href="http://jquery.com/" rel="nofollow noreferrer">libraries</a> get around different <a href="http://xlib.wordpress.com/2006/04/12/bug-fix-select-box-displayed-through-dynamic-div-in-internet-explorer/" rel="nofollow noreferrer">issues</a>.</p> <h2>Rome Wasn't Built in a Day</h2> <p>The more you have to work with it, the more you'll remember off hand and won't have to lookup as often. There's just no replacement for experience in this. As several have pointed out, though, there are great resources out there on the net. <a href="http://www.positioniseverything.net/" rel="nofollow noreferrer">Position Is Everything</a> is certainly up there.</p>
<p>We had a floating div issue that was only evident in a particular version of IE6. It was fixed by downloading the latest service pack.</p>
10,925
<p>Do you generate your data dictionary? If so, how?</p> <p>I use extended procedures in SQL Server 2005 to hold onto table and field information. I have some queries that create a dictionary out of them, but it's ... meh. Do you have a particular query or tool you use? Do you generate it off of your database diagrams?</p> <p>Googling for "data dictionary sql server" comes up with many queries, but they're all about equally as attractive. Which is to say, good starting off points, but not production ready.</p>
<p><a href="http://schemaspy.sourceforge.net/" rel="nofollow noreferrer">SchemaSpy</a> is a really nice tool that can reverse engineer a description of a database. This includes:</p> <ul> <li>ERD</li> <li>List of tables, columns, and constraints</li> <li>Set of warnings about DB anomalied (e.g. tables without indexes)</li> </ul>
<p>We generate the database's dictionnary on the developper's side of the application. We have a nice procedure using an ADODB connection + ADOX objects and collections. This procedure will browse all tables in the database. The following main data is collected:</p> <ol> <li>TableName </li> <li>ColumnName</li> <li>ColumnType</li> <li>ColumnSize</li> <li>bool_ColumnIsThePrimaryKey</li> <li>bool_ColumnHasReferentialIntegrityConstraint</li> </ol> <p>You can also follow up field default values, etc.</p> <p>It is then possible for example to :</p> <ul> <li>check in how many tables my field <code>currency_id</code> (primary key of the <code>Tbl_currency</code> table)is referenced, and if referential integrity is each time properly implemented (we very often create the field without implementing the corresponding rules ...).</li> <li>Make sure that fields of similar logical type (like "<code>description</code>" fields) are of similar data type/size. Nothing is so frustrating that having a <code>item_Description nvarchar(50)</code> field in a table, and a <code>document_Description ntext</code> in another table!</li> <li>etc.</li> </ul> <p>All the data extracted through the procedure is inserted in a local table (could be an XML file or whatever) and saved for further use. </p> <p>A column dictionnary/report can be generated from this data through </p> <pre><code>SELECT DISTINT columnName FROM Tbl_Column </code></pre>
35,696
<p>I'm trying to write a regular expression that validates a date. The regex needs to match the following</p> <ul> <li>M/D/YYYY</li> <li>MM/DD/YYYY</li> <li>Single digit months can start with a leading zero (eg: 03/12/2008)</li> <li>Single digit days can start with a leading zero (eg: 3/02/2008)</li> <li>CANNOT include February 30 or February 31 (eg: 2/31/2008)</li> </ul> <p>So far I have </p> <pre><code>^(([1-9]|1[012])[-/.]([1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d)|((1[012]|0[1-9])(3[01]|2\d|1\d|0[1-9])(19|20)\d\d)|((1[012]|0[1-9])[-/.](3[01]|2\d|1\d|0[1-9])[-/.](19|20)\d\d)$ </code></pre> <p>This matches properly EXCEPT it still includes 2/30/2008 &amp; 2/31/2008.</p> <p>Does anyone have a better suggestion?</p> <p><strong>Edit:</strong> I found <a href="http://regexlib.com/REDetails.aspx?regexp_id=112" rel="noreferrer">the answer</a> on RegExLib</p> <pre><code>^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$ </code></pre> <p>It matches all valid months that follow the MM/DD/YYYY format.</p> <p>Thanks everyone for the help.</p>
<p>This is not an appropriate use of regular expressions. You'd be better off using</p> <pre><code>[0-9]{2}/[0-9]{2}/[0-9]{4} </code></pre> <p>and then checking ranges in a higher-level language.</p>
<p>A slightly different approach that may or may not be useful for you.</p> <p>I'm in php.</p> <p>The project this relates to will never have a date prior to the 1st of January 2008. So, I take the 'date' inputed and use strtotime(). If the answer is >= 1199167200 then I have a date that is useful to me. If something that doesn't look like a date is entered -1 is returned. If null is entered it does return today's date number so you do need a check for a non-null entry first.</p> <p>Works for my situation, perhaps yours too? </p>
7,422
<p>I have</p> <pre><code>class Foo &lt; ActiveRecord::Base named_scope :a, lambda { |a| :conditions =&gt; { :a =&gt; a } } named_scope :b, lambda { |b| :conditions =&gt; { :b =&gt; b } } end </code></pre> <p>I'd like</p> <pre><code>class Foo &lt; ActiveRecord::Base named_scope :ab, lambda { |a,b| :conditions =&gt; { :a =&gt; a, :b =&gt; b } } end </code></pre> <p>but I'd prefer to do it in a DRY fashion. I can get the same effect by using</p> <pre><code> Foo.a(something).b(something_else) </code></pre> <p>but it's not particularly lovely.</p>
<p>At least since 3.2 there is a clever solution :</p> <pre><code>scope :optional, -&gt;() {where(option: true)} scope :accepted, -&gt;() {where(accepted: true)} scope :optional_and_accepted, -&gt;() { self.optional.merge(self.accepted) } </code></pre>
<p>@<a href="https://stackoverflow.com/questions/29011/is-there-a-way-to-combine-named-scopes-into-a-new-named-scope#30719">PJ</a>: you know, I had considered that, but dismissed it because I thought I wouldn't be able to later chain on a <em>third</em> named scope, like so:</p> <pre><code>Foo.ab(x, y).c(z) </code></pre> <p>But since <code>ab(x, y)</code> returns whatever <code>b(y)</code> would return, I think the chain would work. Way to make me rethink the obvious!</p>
4,868
<p>What is a good setup for .hgignore file when working with Visual Studio 2008?</p> <p>I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it.</p> <p>I'm thinking about obj folders, .suo, .sln, .user files etc.. Can they just be included or are there file I shouldn't include?</p> <p>Thanks!</p> <p>p.s.: at the moment I do the following : ignore all .pdb files and all obj folders.</p> <pre><code># regexp syntax. syntax: glob *.pdb syntax: regexp /obj/ </code></pre>
<p>Here's my standard .hgignore file for use with VS2008 that was originally modified from a Git ignore file:</p> <pre><code># Ignore file for Visual Studio 2008 # use glob syntax syntax: glob # Ignore Visual Studio 2008 files *.obj *.exe *.pdb *.user *.aps *.pch *.vspscc *_i.c *_p.c *.ncb *.suo *.tlb *.tlh *.bak *.cache *.ilk *.log *.lib *.sbr *.scc [Bb]in [Dd]ebug*/ obj/ [Rr]elease*/ _ReSharper*/ [Tt]est[Rr]esult* [Bb]uild[Ll]og.* *.[Pp]ublish.xml </code></pre>
<p>some others I use:</p> <pre><code>output PrecompiledWeb _UpgradeReport_Files #Guidance Automation Toolkit *.gpState #patches *.patch </code></pre>
5,514
<p>I'm using jQuery to handle all my ajax needs for an ASP.NET site coded in VB. When I use the built in $.ajax function to POST to a code-behind function and there is an exception, it simply exits the function, and shows an error on the client side.</p> <p>Besides making debugging difficult when coding, the bigger issue is that the Application_Error function in Global.asax isn't firing when those exceptions occur. This is making it almost impossible to track production errors.</p> <p>Why would it not bubble up to Application_Error? Is the answer to wrap the code-behind function in a Catch statement?</p> <p>jQuery ajax function:</p> <pre><code>$.ajax({ type: "POST", url: "page.aspx/GetData", data: "{'param':'" + param_value + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { processData(msg); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error: " + textStatus + " - " + errorThrown); } }); </code></pre> <p>VB.NET function:</p> <pre><code>&lt;Script.Services.ScriptMethod()&gt; _ &lt;WebMethod()&gt; _ Public Shared Function GetData(ByVal param As Integer) As String 'Parse some data Return data End Function </code></pre>
<p>I figured out a work around. Although I did not find a way to directly get the error to fire the Application_Error event, I discovered a property on the jQuery XMLHttpRequest object that contains the actual exception text.</p> <p>Here is an example that will show the error in an alert:</p> <pre><code>error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error: " + XMLHttpRequest.responseText); } </code></pre> <p>Another idea is to submit the error via AJAX to a web method that will handle all the error event logic.</p>
<p>With .Net 3.5 you can pull in the <a href="http://www.asp.net/Ajax/Documentation/Live/overview/ScriptManagerOverview.aspx" rel="nofollow noreferrer">ScriptManager object</a> and register your javascript with it, this allows .Net to manage the scripts (it's not jsut for MS Ajax, it works with third party libraries), this could be a solution.</p>
33,267
<p>Is there a way to get the tests inside of a <code>TestCase</code> to run in a certain order? For example, I want to separate the life cycle of an object from creation to use to destruction but I need to make sure that the object is set up first before I run the other tests.</p>
<p>Maybe there is a design problem in your tests.</p> <p>Usually each test must not depend on any other tests, so they can run in any order.</p> <p>Each test needs to instantiate and destroy everything it needs to run, that would be the perfect approach, you should never share objects and states between tests.</p> <p>Can you be more specific about why you need the same object for N tests?</p>
<p>There really is a problem with your tests if they need to run in a certain order. Each test should be totally independent of the others: it helps you with defect localization, and allows you to get repeatable (and therefore debuggable) results.</p> <p>Checkout <a href="http://www.xunitpatterns.com" rel="nofollow noreferrer">this site</a> for a whole load of ideas / information, about how to factor your tests in a manner where you avoid these kinds of issues.</p>
3,143
<p>I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: </p> <pre><code>if (datetime.now() - self.timestamp) &gt; 100 # Where 100 is either seconds or minutes </code></pre> <p>This generates a type error. </p> <p>What is the proper way to do date time comparison in python? I already looked at <a href="http://wiki.python.org/moin/WorkingWithTime" rel="noreferrer">WorkingWithTime</a> which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. </p> <p>Please post lists of datetime best practices.</p>
<p>Use the <code>datetime.timedelta</code> class:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime, timedelta &gt;&gt;&gt; then = datetime.now() - timedelta(hours = 2) &gt;&gt;&gt; now = datetime.now() &gt;&gt;&gt; (now - then) &gt; timedelta(days = 1) False &gt;&gt;&gt; (now - then) &gt; timedelta(hours = 1) True </code></pre> <p>Your example could be written as:</p> <pre><code>if (datetime.now() - self.timestamp) &gt; timedelta(seconds = 100) </code></pre> <p>or</p> <pre><code>if (datetime.now() - self.timestamp) &gt; timedelta(minutes = 100) </code></pre>
<p>You can subtract two <a href="http://docs.python.org/lib/module-datetime.html" rel="nofollow noreferrer">datetime</a> objects to find the difference between them.<br> You can use <code>datetime.fromtimestamp</code> to parse a POSIX time stamp.</p>
15,866
<p>I would like to compress a folder and all its sub-folders/files, and email the zip file as an attachment. What would be the best way to achieve this with Python? </p>
<p>You can use the <a href="http://docs.python.org/dev/library/zipfile.html" rel="nofollow noreferrer">zipfile</a> module to compress the file using the zip standard, the <a href="http://docs.python.org/dev/library/email.html" rel="nofollow noreferrer">email</a> module to create the email with the attachment, and the <a href="http://docs.python.org/dev/library/smtplib.html" rel="nofollow noreferrer">smtplib</a> module to send it - all using only the standard library.</p> <h1>Python - Batteries Included</h1> <p>If you don't feel like programming and would rather ask a question on stackoverflow.org instead, or (as suggested in the comments) left off the <code>homework</code> tag, well, here it is:</p> <pre><code>import smtplib import zipfile import tempfile from email import encoders from email.message import Message from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart def send_file_zipped(the_file, recipients, sender='you@you.com'): zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip') zip = zipfile.ZipFile(zf, 'w') zip.write(the_file) zip.close() zf.seek(0) # Create the message themsg = MIMEMultipart() themsg['Subject'] = 'File %s' % the_file themsg['To'] = ', '.join(recipients) themsg['From'] = sender themsg.preamble = 'I am not using a MIME-aware mail reader.\n' msg = MIMEBase('application', 'zip') msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=the_file + '.zip') themsg.attach(msg) themsg = themsg.as_string() # send the message smtp = smtplib.SMTP() smtp.connect() smtp.sendmail(sender, recipients, themsg) smtp.close() """ # alternative to the above 4 lines if you're using gmail server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.login("username", "password") server.sendmail(sender,recipients,themsg) server.quit() """ </code></pre> <p>With this function, you can just do:</p> <pre><code>send_file_zipped('result.txt', ['me@me.org']) </code></pre> <p>You're welcome.</p>
<p>You can use <a href="http://www.python.org/doc/2.5.2/lib/module-zipfile.html" rel="nofollow noreferrer">zipfile</a> that ships with python, and <a href="http://snippets.dzone.com/posts/show/2038" rel="nofollow noreferrer">here</a> you can find an example of sending an email with attachments with the standard smtplib</p>
20,445
<p>I must confess I'm somewhat of an OOP skeptic. Bad pedagogical and laboral experiences with object orientation didn't help. So I converted into a fervent believer in Visual Basic (the classic one!).</p> <p>Then one day I found out C++ had changed and now had the STL and templates. I really liked that! Made the language useful. Then another day MS decided to apply facial surgery to VB, and I really hated the end result for the gratuitous changes (using "end while" instead of "wend" will make me into a better developer? Why not drop "next" for "end for", too? Why force the getter alongside the setter? Etc.) plus so much Java features which I found useless (inheritance, for instance, and the concept of a hierarchical framework).</p> <p>And now, several years afterwards, I find myself asking this philosophical question: Is inheritance <strong>really</strong> needed?</p> <p>The gang-of-four say we should favor object composition over inheritance. And after thinking of it, I cannot find something you can do with inheritance you cannot do with object aggregation plus interfaces. So I'm wondering, why do we even have it in the first place?</p> <p>Any ideas? I'd love to see an example of where inheritance would be definitely needed, or where using inheritance instead of composition+interfaces can lead to a simpler and easier to modify design. In former jobs I've found if you need to change the base class, you need to modify also almost all the derived classes for they depended on the behaviour of parent. And if you make the base class' methods virtual... then not much code sharing takes place :(</p> <p>Else, when I finally create my own programming language (a long unfulfilled desire I've found most developers share), I'd see no point in adding inheritance to it...</p>
<p>Really really short answer: No. Inheritance is not needed because only byte code is truly needed. But obviously, byte code or assemble is not a practically way to write your program. OOP is not the only paradigm for programming. But, I digress.</p> <p>I went to college for computer science in the early 2000s when inheritance (is a), compositions (has a), and interfaces (does a) were taught on an equal footing. Because of this, I use very little inheritance because it is often suited better by composition. This was stressed because many of the professors had seen bad code (along with what you have described) because of abuse of inheritance. </p> <p><strong>Regardless of creating a language with or without inheritances, can you create a programming language which prevents bad habits and bad design decisions?</strong> </p>
<p>In the following, inheritance is used to present a particular property for all of several specific incarnations of the same type thing. In this case, the GeneralPresenation has a properties that are relevant to all "presentation" (the data passed to an MVC view). The Master Page is the only thing using it and expects a GeneralPresentation, though the specific views expect more info, tailored to their needs.</p> <pre><code> public abstract class GeneralPresentation { public GeneralPresentation() { MenuPages = new List&lt;Page&gt;(); } public IEnumerable&lt;Page&gt; MenuPages { get; set; } public string Title { get; set; } } public class IndexPresentation : GeneralPresentation { public IndexPresentation() { IndexPage = new Page(); } public Page IndexPage { get; set; } } public class InsertPresentation : GeneralPresentation { public InsertPresentation() { InsertPage = new Page(); ValidationInfo = new PageValidationInfo(); } public PageValidationInfo ValidationInfo { get; set; } public Page InsertPage { get; set; } } </code></pre>
35,167