input
stringlengths
51
42.3k
output
stringlengths
18
55k
How to do effective paging in Classic ASP? <p>I'm trying to page a table, and while I have paging already working, it displays every page in a single line along with Previous/Next links, causing the HTML page to break if there are a lot of results (which often there are).</p> <p>What I'd like to do is display the pages in batches of 10, e.g. 1...10, if you're on page 10 and click "Next" then it changes to 11-20, and so on. How should I go about doing this? </p>
<p>Wayne I would recommend you have a look at <strong><a href="http://www.ajaxed.org" rel="nofollow">ajaxed asp library</a></strong>. It is a still active classic ASP project which provides generic paging (for all kind of data structures) and also uses the paging mechanism within its <a href="http://www.ajaxed.org/article/Using--Understanding-Datatables/22/" rel="nofollow">Datatable control</a>. </p> <p>That control easily allows you to create a table with just a SQL Query. Similar to asp.net's Datagrid. Fully AJAX as well.</p> <p>Check the datatable examples and you will see the batch paging and more... everything fully configureable.</p> <p>Supported DBs are MySQL, sqlite, MS Access, MS Sqlserver, Oracle</p>
AS3 - How to do a synchronous load of an asynchronous call? <p>I have a function that loads a user object from a web service asynchronously.</p> <p>I wrap this function call in another function and make it synchronous.</p> <p>For example:</p> <pre><code> private function getUser():User{ var newUser:User; var f:UserFactory = new UserFactory(); f.GetCurrent(function(u:User):void{ newUser = u; }); return newUser; } </code></pre> <p>UserFactory.GetCurrent looks like this:</p> <pre><code>public function GetCurrent(callback:Function):void{ } </code></pre> <p>But my understanding is there is no guarantee that when this function gets called, newUser will actually be the new user??</p> <p>How do you accomplish this type of return function in Flex?</p>
<p>This way madness lies. </p> <p>Seriously, you're better off not trying to force an asynchronous call into some kind of synchronous architecture. Learn how the event handling system works in your favour and add a handler for the result event. In fact, here's the advice straight from the <a href="http://tech.groups.yahoo.com/group/flexcoders/">flexcoders</a> FAQ :</p> <pre>Q: How do I make synchronous data calls? A: You CANNOT do synchronous calls. You MUST use the result event. No, you can't use a loop, or setInterval or even callLater. This paradigm is quite aggravating at first. Take a deep breath, surrender to the inevitable, resistance is futile. There is a generic way to handle the asynchronous nature of data service calls called ACT (Asynchronous Call Token). Search for this in Developing Flex Apps doc for a full description. </pre>
The diff between openssl-2 and openssl-3 <p>New to this. </p> <p>How can you tell what the openssl version is and what's the diff?</p>
<p>Find the current <a href="http://openssl.org/" rel="nofollow">OpenSSL</a> version on the <a href="http://openssl.org/" rel="nofollow">OpenSSL webpage</a> (0.9.8k as of 25-Mar-2009 and 1.0.0, third beta as of 15-Jul-2009). OpenSSL is a implementation of the <a href="http://en.wikipedia.org/wiki/Transport%5FLayer%5FSecurity" rel="nofollow">TLS</a> cryptographic protocol suite (amongst other things).</p>
Any free tools for webservice testing with NTLM2 support? <p>What tools are free tools are available for testing WebServices that are behind NTLM2 authentication.</p> <p>SoapUI Is Excellent tool with all functionality that I need, however, it doesn't support NTLMv2. If someone has a way of making that work, please provide solution.</p>
<p>Throwing up a custom web service testing app ought to be a pretty simple thing to do...</p>
How do I configure authentication between linked servers? <p>I am trying to test a proof of concept that I can run a distributed transaction across two linked SQL Servers, linked using sp_addlinkedserver - their names are Server1 and Server2, both running under default instances. Each server holds a single database, Source and Destination respectively and the destination database holds a single table called Output, i.e.</p> <pre><code>Server1.Source Server2.Destination.Output </code></pre> <p>The OUTPUT table has the following structure:</p> <pre><code>OUT_PKEY int identity(1,1) primary key, OUT_TEXT nvarchar(255) </code></pre> <p>From Server1 I have called *sp_addlinkedserver 'Server2'* to link the two databases and I've attempted to run the following query to test that the link does indeed work:</p> <pre><code>Select * From Server2.Destination.dbo.Output </code></pre> <p>I am returned the following exception:</p> <blockquote> <p>Access to the remote server is denied because no login-mapping exists.</p> </blockquote> <p>Fair enough, so from Server1, I run *sp_addlinkedsrvlogin 'Server2'* which according to the documentation says that it should take the user credentials of whomever runs the query remotely (i.e. from Server1) and apply those credentials to Server2. This implies that since I am connected to Server1 using Windows Authentication, this should mean that my Windows Credentials are applied to Server2 also.</p> <p>Now the exception message changes to:</p> <blockquote> <p>Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.</p> </blockquote> <p>Having Googled this exception, I came up with nothing useful that pointed me in the right direction. What am I missing? I would expect [should the login fail at all] the exception to reference <em>my</em> Windows Credentials, <em>not</em> the anonymous logon credentials.</p> <p>It looks like once I get the link itself working, the distributed transactions themselves should be a fairly simple affair - the documentation implies that I just need to ensure that the DTC Service is running on Server1 and that any queries run on Server1 that will be transacted across the link:</p> <ul> <li>Include *SET XACT_ABORT ON* prior to initializing my distributed transaction</li> <li>I use <em>BEGIN DISTRIBUTED TRANSACTION</em> instead of <em>BEGIN TRANSACTION</em></li> <li>If I wish to reference a non-default instance of SQL Server on Server2, I replace any instances of the name <em>Server2</em> in my query with <em>[Server2\InstanceName]</em></li> </ul> <p>My questions are these:</p> <ul> <li>how do I get past this login issue? The *sp_addlinkedsrvlogin* stored procedure alone doesn't seem to be doing the trick.</li> <li>Is it indeed as simple as that to run the distributed transaction as the documentation implies?</li> </ul> <p>TIA</p>
<p>If you're on a domain, then the setting should be "Be made using the login's current security context", but there's one more step - you need to grant an SPN to each of the servers involved in the transaction.</p> <p>Assuming you're running the SQL Services on both servers as a domain user (which you'll need to in order to make this work - LocalSystem won't do it), here are the instructions you'll need:</p> <p><a href="http://technet.microsoft.com/en-us/library/bb735885.aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/bb735885.aspx</a></p> <p>Remember that the user will need an SPN for both servers, but not the client - for example, if you are going from client -> server1 -> server2, the SQL Service account will need an SPN for both server1 and server2.</p> <p>If you're confused (it's a confusing process), post a comment and I'll clarify the instructions.</p>
MVC frameworks for .NET desktop applications <p>I've been playing a lot with MVC lately in the forms of ASP.NET MVC and Django (MTV actually) and I must say that I love it.</p> <p>Are there any similar frameworks for creating desktop WinForm apps?</p>
<p>Not that I know of.</p> <p>Most of my Winforms apps use the MVC or MVP pattern though. I've noticed that when creating Winforms apps you don't really need much of a framework. There is no routing infrastructure and no view-rendering. I find that I don't have to do much plumbing to use these patterns.</p> <p>That might explain why there are no high profile frameworks in that space.</p>
SaveFileDialog blocking removeable drive <p>I'm using a SaveFileDialog to let a user pick a directory and filename on a removeable drive. Afterwards I create that file, write to it, and close it again.</p> <p>By then the file itself is not locked (editable, deleteable), but I can't eject the drive because windows claims it is still in use. I have to exit the application before an eject is possible.</p> <p>Incidentally the drive gets locked even when I only pick the file with the SaveFileDialog. Hitting "Cancel" on the dialog doesn't cause the problem</p> <pre><code>SaveFileDialog dlg = new SaveFileDialog(); dlg.DefaultExt = ".csv"; dlg.InitialDirectory = mySettings.defaultPath; dlg.Filter = "(CSV-Dateien) *.csv|"; dlg.FileName = exportDate.ToString("yyyy-MM-dd") + ".csv"; if (dlg.ShowDialog() != DialogResult.OK){ // USB-Drive is ejectable }else{ // USB-Drive is locked } </code></pre>
<p>I found 2 <strong>Solutions</strong>:</p> <p>The Dialog changes the current working directory once the user clicks "save". It's not the file that was blocking the removable drive, but the program itself .</p> <p>So you either need to readjust the working directory once you're done: </p> <pre><code>String oldDir = Directory.GetCurrentDirectory(); // ... do dialog... Environment.CurrentDirectory = oldDir; </code></pre> <p>or you simply configure the file dialog to restore the directory before calling ShowDialog()</p> <pre><code>dlg.RestoreDirectory = true; dlg.ShowDialog() </code></pre>
Is there an idiomatic way to listen for changes to the DOM using the Prototype library? <p>I'm trying to add a listener to DOM change events. I was hoping something as simple as 'dom:loaded' was baked into Prototype. I'm not sure of the 'Prototype-way' to handle this.</p> <p>EDIT: I cannot control every case in which the DOM may be altered, so I can't get away with firing a custom event on every DOM change.</p>
<p>There is no standard handler to watch this. However, you can fire custom events in Prototype. Combined with Function.wrap, you should be able to do exactly what you need.</p> <p>Essentially, you take any function that can modify the DOM, such as Element.insert(), and wrap it with a function that fires your change event:</p> <pre><code>Element.prototype.insert = Element.prototype.insert.wrap( function(original) { var ret = original.call(this, $A(arguments).slice(1)); document.fire('dom:changed'); }.bind(this) ); </code></pre> <p>Now, whenever you call Element.insert, it will fire 'dom:changed', which can be watched with Event.observe().</p> <p>I can't guarantee what I just wrote is 100% perfect nor 100% versatile, but it should get you started.</p>
Expose a specific .net object as JSON <p>I'm currently enabling JSON calls to my web services using the ScriptService attribute. The problem is that one of my classes references a second class and .Net is not picking up and writing out the JavaScript for the second class. </p> <p>As a workaround I can write a dummy method that just returns the second class. Then .Net writes the JSON to allow it to be serialized. So in the following example:</p> <pre><code>[ScriptService] public class MyService : WebService { [WebMethod] public void SaveClass1(Class1 class1) { ... } } [Serializable] public class Class1 { public Class2 class2 { get; set; } } [Serializable] public class Class2 { } </code></pre> <p>MyService.asmx/js won't write code to allow me to instantiate Class2 in order for me to populate Class1. But I can make it work if I add:</p> <pre><code>[WebMethod] public Class2 Dummy() { return new Class2(); } </code></pre> <p>to MyService. Any alternatives to my nasty workaround would be greatly appreciated.</p>
<p>You need to use <a href="http://msdn.microsoft.com/en-us/library/system.web.script.services.generatescripttypeattribute.aspx" rel="nofollow">System.Web.Script.Services.GenerateScriptTypeAttribute</a>, which specifies that a server type should be included in the generated proxy code. You can apply this attribute to the web service itself or any method marked with <a href="http://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute.aspx" rel="nofollow">WebMethodAttribute</a>.</p> <p>For example:</p> <pre><code>[ScriptService] [GenerateScriptType(typeof(Class2))] public class MyService : WebService { [WebMethod] public void SaveClass1(Class1 class1) { // ... } } </code></pre>
DataTable to JSON <p>I recently needed to serialize a datatable to JSON. Where I'm at we're still on .Net 2.0, so I can't use the JSON serializer in .Net 3.5. I figured this must have been done before, so I went looking online and <a href="http://www.codeproject.com/KB/aspnet/ASPNET_DataTable_to_JSON.aspx" rel="nofollow">found</a> a <a href="http://www.dennydotnet.com/post/A-DataTable-Serializer-for-ASPNET-AJAX.aspx" rel="nofollow">number</a> of <a href="http://schotime.net/blog/index.php/2008/07/27/dataset-datatable-to-json/" rel="nofollow">different</a> <a href="http://geekswithblogs.net/shahed/archive/2008/03/22/120709.aspx" rel="nofollow">options</a>. Some of them depend on an additional library, which I would have a hard time pushing through here. Others require first converting to <code>List&lt;Dictionary&lt;&gt;&gt;</code>, which seemed a little awkward and needless. Another treated all values like a string. For one reason or another I couldn't really get behind any of them, so I decided to roll my own, which is posted below. </p> <p>As you can see from reading the <code>//TODO</code> comments, it's incomplete in a few places. This code is already in production here, so it does "work" in the basic sense. The places where it's incomplete are places where we know our production data won't currently hit it (no timespans or byte arrays in the db). The reason I'm posting here is that I feel like this can be a little better, and I'd like help finishing and improving this code. Any input welcome.</p> <p><em>Note that this capability is built into .Net 3.5 and later, and so the only reason to use this code today is if you're still limited to .Net 2.0. Even then, JSON.Net has become the goto library for this kind of thing.</em></p> <pre><code>public static class JSONHelper { public static string FromDataTable(DataTable dt) { string rowDelimiter = ""; StringBuilder result = new StringBuilder("["); foreach (DataRow row in dt.Rows) { result.Append(rowDelimiter); result.Append(FromDataRow(row)); rowDelimiter = ","; } result.Append("]"); return result.ToString(); } public static string FromDataRow(DataRow row) { DataColumnCollection cols = row.Table.Columns; string colDelimiter = ""; StringBuilder result = new StringBuilder("{"); for (int i = 0; i &lt; cols.Count; i++) { // use index rather than foreach, so we can use the index for both the row and cols collection result.Append(colDelimiter).Append("\"") .Append(cols[i].ColumnName).Append("\":") .Append(JSONValueFromDataRowObject(row[i], cols[i].DataType)); colDelimiter = ","; } result.Append("}"); return result.ToString(); } // possible types: // http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype(VS.80).aspx private static Type[] numeric = new Type[] {typeof(byte), typeof(decimal), typeof(double), typeof(Int16), typeof(Int32), typeof(SByte), typeof(Single), typeof(UInt16), typeof(UInt32), typeof(UInt64)}; // I don't want to rebuild this value for every date cell in the table private static long EpochTicks = new DateTime(1970, 1, 1).Ticks; private static string JSONValueFromDataRowObject(object value, Type DataType) { // null if (value == DBNull.Value) return "null"; // numeric if (Array.IndexOf(numeric, DataType) &gt; -1) return value.ToString(); // TODO: eventually want to use a stricter format. Specifically: separate integral types from floating types and use the "R" (round-trip) format specifier // boolean if (DataType == typeof(bool)) return ((bool)value) ? "true" : "false"; // date -- see http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx if (DataType == typeof(DateTime)) return "\"\\/Date(" + new TimeSpan(((DateTime)value).ToUniversalTime().Ticks - EpochTicks).TotalMilliseconds.ToString() + ")\\/\""; // TODO: add Timespan support // TODO: add Byte[] support //TODO: this would be _much_ faster with a state machine //TODO: way to select between double or single quote literal encoding //TODO: account for database strings that may have single \r or \n line breaks // string/char return "\"" + value.ToString().Replace(@"\", @"\\").Replace(Environment.NewLine, @"\n").Replace("\"", @"\""") + "\""; } } </code></pre> <p><strong>Update:</strong><br> This is old now, but I wanted to point out something about how this code handles dates. The format I used made sense at the time, for the exact rationale in the url. However, that rationale includes the following:</p> <blockquote> <p>To be perfectly honest, JSON Schema does solve the problem by making it possible to "subtype" a string as a date literal, but this is still work in progress and it will take time before any significant adoption is reached.</p> </blockquote> <p>Well, time has passed. Today, it's okay to just use the <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="nofollow">ISO 8601</a> date format. I'm not gonna bother changing the code, 'cause really: this is ancient. Just go use JSON.Net.</p>
<p>Would it help you convince your bosses to install a library if it's Microsoft's <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&amp;displaylang=en">AJAX extensions for .NET 2.0</a>?</p> <p>Included in them is <a href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx">System.Web.Script.Serialization.JavascriptSerializer</a>, which is used in Step 4 of the <a href="http://geekswithblogs.net/shahed/archive/2008/03/22/120709.aspx">last link</a> in your post.</p>
How can i determine which of my product's .net assemblies are registered, when i have several on my pc? <p>I have the code for various versions of a software product I work on on my machine. The product includes one or more assemblies that are registered for com interop. How can I determine which one is currently registered?</p>
<p>If you know the GUID of your assembly, look under <code>HKCR\CLSID\{your guid}\InprocServer32</code>. The <code>Assembly</code> key will have a value including the version.</p> <p>If you only have the ProgId, you can just search the registry for that string which will tell you the GUID.</p>
How do I know what encoding scheme to use when converting a string to a byte array? <p>From my database I am getting a very long string which is basically xml. I need to change it to a byte array.</p> <p>I can't get my head around the potential encoding issues.</p> <p>What do I need to be careful of when doing this conversion?</p> <pre><code> public static byte[] StringToByteArray1(string str) { return Encoding.ASCII.GetBytes(str); } public static byte[] StringToByteArray2(string str) { return Encoding.UTF8.GetBytes(str); } </code></pre> <p>Encoding.ASCII.GetBytes vs Encoding.UTF8.GetBytes</p>
<p>If you are dealing with ASCII characters then the result is identical.</p> <p>On the other hand if you have non-ASCII characters in your string (for example π) then: in ASCII encoding these will be replaced by "?".</p> <p>in UTF8 they will be represented by a (possibly several byte character).</p> <p>It is probably worth pointing out that internally .NET uses UTF16 to encode its strings.</p> <p>In general though you are probably best off using UTF8 unless you have specific reason not to.</p>
What's the most efficient way to access sibling dictionary value in a Python dict? <p>In Python, I've got a list of dictionaries that looks like this:</p> <pre><code>matchings = [ {'id': 'someid1', 'domain': 'somedomain1.com'}, {'id': 'someid2', 'domain': 'somedomain2.com'}, {'id': 'someid3', 'domain': 'somedomain3.com'} ] </code></pre> <p>and, I have a variable:</p> <pre><code>the_id = 'someid3' </code></pre> <p>What's the most efficient way to retrieve the domain value of the item?</p>
<p>You can use a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p> <pre><code>domains = [matching['domain'] for matching in matchings if matching['id'] == the_id] </code></pre> <p>Which follows the format standard format of:</p> <pre><code>resulting_list = [item_to_return for item in items if condition] </code></pre> <p>And basically encapsulates all the following functionality:</p> <pre><code>domains = [] for matching in matchings: if matching['id'] == the_id: domains.append(matching['domain']) </code></pre> <p>All that functionality is represented in a single line using list comprehensions.</p>
No Process Is on the Other End of the Pipe <p>I receive this error when I try to connect to SQL Server 2005. I have enabled TCP/IP, Named Pipes, and restarted the server but that is not working.</p>
<p>FYI, I've just had the same error.</p> <p>I switched to Windows authentication, disconnected, then tried to login again with SQL authentication. This time I was told my password had expired. I changed the password and it all worked again.</p>
Same module multiple times as TabItems <p>Here's my scenario:</p> <ol> <li>Shell with 1 TabControl and 1 region called MenuRegion</li> <li>MenuRegion contains Buttons for each of the available modules (applications).</li> </ol> <p>I want to achieve the following using Prism (Composite Application Library for WPF): When one of the buttons is clicked, I need to add a new TabItem to the TabControl, and load and individual instance of the corresponding module (application) inside this TabItem. One module may appear several times in the TabControl.</p> <hr> <p>I really appreciate your answer. But I don't believe you're using Prism (<a href="http://www.codeplex.com/CompositeWPF" rel="nofollow">http://www.codeplex.com/CompositeWPF</a>) are you? My question was more related to Prism, and I've edited it to be more clear now.</p> <p>In Prism you dynamically load modules' views into regions. I am not sure how to do that in my scenario because the regions are to be set dynamically. How would I name them? </p> <p>Thanks!</p>
<p>I'm new to this PRISM world (1 week experience :)) ) and had the same requirement! First of all you have to get the Regionextensions from <a href="http://blogs.southworks.net/matiasb/2009/07/02/how-to-hide-views-inside-composite-application-guidance-aka-prism-v2-regions/" rel="nofollow">here</a>.</p> <p>The solution to my (may be your) problem is as follows:</p> <ul> <li><p>have 2 regions (menu and tabcontrol - for mdi like behaviour)</p></li> <li><p>tabitem header has to be prepared with a button for closing (which is bound to a command for closing this tabitem-actually hiding this tabitem)</p></li> <li><p>send event from menu item to the module which should load the view (I've instantiated the modules on demand). In the module's initialize method subscribe to the event sent by the menu item. In the event handling method you simply re-show the tabitem</p></li> </ul> <p>If this is to abstract to you I can send you a skeleton application I've developed to play around.</p>
Determine if flash OCX is installed? <p>What is the best way to determine if the flash ocx is installed in Innosetup (or any installer for that matter). I don't want to attempt to install it myself, I will simply force the user to go to the flash site and install, I just want to make sure that the flash.ocx (version 9+) is installed.</p> <p>Is it enough to check for HKEY_CLASSES_ROOT\ShockwaveFlash.ShockwaveFlash and check that CurVer >= 9? Is there a better way to test for this?</p>
<p>Add a function in the code section to check whether you can create an instance of the Flash control, like so:</p> <pre><code>function IsFlashInstalled(): boolean; var V: Variant; begin try V := CreateOleObject('ShockwaveFlash.ShockwaveFlash.9'); Result := True; except Result := False; end; end; </code></pre> <p>Check out the various examples in the Inno Setup package on how to use your own function to show a message box to the user, cancel the installation, open the Flash site in the default browser or whatever you want to do.</p>
How do I efficiently transform a series of strings in powershell? <p>Suppose I have a large number of strings formatted something like:</p> <pre><code>&lt;tag&gt;blah blahXXXXXblah blah&lt;/tag&gt; </code></pre> <p>I want to transform these strings into something like:</p> <pre><code>blah blahZZZZZblah blah </code></pre> <p>on a powershell command line. All instances of XXXXX get replaced by ZZZZZ in the transformation and the outer tags are stripped out. It isn't well-formed XML.</p> <p>I can write a script that would evaluate this easily enough, I believe, but when dealing with this particular bit of software I find myself performing tasks like this more often than I'd like. I'm interested in learning how to do this straight from the powershell command line without the additional step of writing a .ps1 script to run.</p> <p>It seems like something powershell would be good at, I just don't know how. :)</p>
<p>Well the simplest way that I can think of (assumes your list is held in $foo):</p> <pre><code>$foo | %{$_.Replace("XXXXX", "ZZZZZ")} </code></pre>
Get the XPath to an XElement? <p>I've got an XElement deep within a document. Given the XElement (and XDocument?), is there an extension method to get its full (i.e. absolute, e.g. <code>/root/item/element/child</code>) XPath?</p> <p>E.g. myXElement.GetXPath()?</p> <p><strong>EDIT: Okay, looks like I overlooked something very important. Whoops! The index of the element needs to be taken into account. See my last answer for the proposed corrected solution.</strong></p>
<p>The extensions methods:</p> <pre><code>public static class XExtensions { /// &lt;summary&gt; /// Get the absolute XPath to a given XElement /// (e.g. "/people/person[6]/name[1]/last[1]"). /// &lt;/summary&gt; public static string GetAbsoluteXPath(this XElement element) { if (element == null) { throw new ArgumentNullException("element"); } Func&lt;XElement, string&gt; relativeXPath = e =&gt; { int index = e.IndexPosition(); string name = e.Name.LocalName; // If the element is the root, no index is required return (index == -1) ? "/" + name : string.Format ( "/{0}[{1}]", name, index.ToString() ); }; var ancestors = from e in element.Ancestors() select relativeXPath(e); return string.Concat(ancestors.Reverse().ToArray()) + relativeXPath(element); } /// &lt;summary&gt; /// Get the index of the given XElement relative to its /// siblings with identical names. If the given element is /// the root, -1 is returned. /// &lt;/summary&gt; /// &lt;param name="element"&gt; /// The element to get the index of. /// &lt;/param&gt; public static int IndexPosition(this XElement element) { if (element == null) { throw new ArgumentNullException("element"); } if (element.Parent == null) { return -1; } int i = 1; // Indexes for nodes start at 1, not 0 foreach (var sibling in element.Parent.Elements(element.Name)) { if (sibling == element) { return i; } i++; } throw new InvalidOperationException ("element has been removed from its parent."); } } </code></pre> <p>And the test:</p> <pre><code>class Program { static void Main(string[] args) { Program.Process(XDocument.Load(@"C:\test.xml").Root); Console.Read(); } static void Process(XElement element) { if (!element.HasElements) { Console.WriteLine(element.GetAbsoluteXPath()); } else { foreach (XElement child in element.Elements()) { Process(child); } } } } </code></pre> <p>And sample output:</p> <pre><code>/tests/test[1]/date[1] /tests/test[1]/time[1]/start[1] /tests/test[1]/time[1]/end[1] /tests/test[1]/facility[1]/name[1] /tests/test[1]/facility[1]/website[1] /tests/test[1]/facility[1]/street[1] /tests/test[1]/facility[1]/state[1] /tests/test[1]/facility[1]/city[1] /tests/test[1]/facility[1]/zip[1] /tests/test[1]/facility[1]/phone[1] /tests/test[1]/info[1] /tests/test[2]/date[1] /tests/test[2]/time[1]/start[1] /tests/test[2]/time[1]/end[1] /tests/test[2]/facility[1]/name[1] /tests/test[2]/facility[1]/website[1] /tests/test[2]/facility[1]/street[1] /tests/test[2]/facility[1]/state[1] /tests/test[2]/facility[1]/city[1] /tests/test[2]/facility[1]/zip[1] /tests/test[2]/facility[1]/phone[1] /tests/test[2]/info[1] </code></pre> <p>That should settle this. No? </p>
Which versions of SQL Server does LINQ to SQL support? <p>Can SQL Server 2000 be used as the database for LINQ to SQL?</p> <p>Does LINQ to SQL rely on a specific version of Microsoft SQL Server?</p>
<p>Yes, LINQ to SQL works with SQL Sever 2000 with one exception: you do need the ROW_NUMBER() function, available only in SQL Server 2005/2008, to support efficient server-side paging. Without it, paging functions (as Mehrdad points out) are delivered using the classic Top N strategy - <em>very</em> inefficient as you page further and further through your dataset because you end up throwing out most of your selected records from the third page on.</p>
Can I programmatically set the object type for a DirectCast command? <p>I'm helping a colleague develop a "catch all" type error handler for some controls his application. What he wants to do is pass the object that has the error, and the type of that object, such a TextBox or ComboBox, and then call the DirectCast method within his handler to properly address the Text attribute within it. In general, the method is looking like this:</p> <pre><code>Protected Sub SpecialErrorHandler(ByVal TargetControl As Object, ByVal ControlType As String) MessageBox.Show("Bad Juice: " &amp; DirectCast(TargetControl, ControlType(ObjType)).Text) End Sub </code></pre> <p>So far any attempts to do a type conversion within the DirectCast method (since it is expecting an object in the general signature) or to even pass in the a Type object properly set is not working.</p> <p>Any ideas here, or is this one of those "Casting doesn't work that way." type scenarios?</p>
<p><code>DirectCast()</code> needs a real type at compile time, so it knows what the result of the call looks like. The best you can hope for here is to cast to a common base type for each of the objects you're expecting. In this case you're lucky have in that you have a fairly useful base type: <code>Control</code>.</p>
How do I make a universal type conversion method <p>What I want to do is:</p> <pre><code>bool Convert( out Object output, Object source) { // find type of output. // convert source to that type if possible // store result in output. return success } </code></pre> <p>Is it possible? </p> <p>Obviously, there is a brute force massive "if" construct that could work, but that would require writing an if block for every conceivable data type. Even assuming we'll limit it to primitives and strings, it's still a huge chunk of code. I'm thinking about something a bit more reflective.</p> <p>Aside: While going through the api, I came across the Convert.IsDBNull() method, which will save me a lot of </p> <pre><code> if ( !databasefield.GetType().Equals( DBNull.Value ) ) </code></pre> <p>Why in the name of G-d is it in Convert? Why not DBNull.IsDBNull() ?</p>
<p>Here is a sample that I use, you can inject other complex conversions into it by registering other type converters.</p> <pre><code>public static class Converter { public static T Convert&lt;T&gt;(object obj, T defaultValue) { if (obj != null) { if (obj is T) { return (T)obj; } TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); if (converter.CanConvertFrom(obj.GetType())) { return (T)converter.ConvertFrom(obj); } } return defaultValue; } </code></pre>
How do I use a pre-defined CSS style for a programmatically drawn TextField? <p>I have a graphical application that renders text to BitmapData - right now it's hardcoded to use a specific font, and that's fine for testing, but for production I really need it to be style-able.</p> <p>The rest of the application uses specific fonts, and I want to be able to just use a stylename (the style of the font) to create a TextFormat object to pass to the text sprites embedded TextField object..</p> <p>So here's the sequence now, roughly:</p> <pre><code> var format:TextFormat = new TextFormat(); format.font = "Arial"; format.color = 0xFF0000; format.size = 12; // tf is a previously instantiated TextField() tf.defaultTextFormat = format; tf.autoSize = TextFieldAutoSize.LEFT; tf.text = _text; </code></pre> <p>Then later, it's simply drawn with:</p> <pre><code> bmpData.fillRect(srcRect,0x00000000); bmpData.draw(tf); </code></pre> <p>Now this is nasty, so how do I get a StyleSheet or TextFormat from my apps css definitions? I've looked in the StyleManager, the CSSStyleDeclaration, nothing seems to quite fit. What's the sequence here, anyone?</p>
<p>Basically you can just add <code>[style]</code> metadata tags to your custom class to define your custom style properties, specify values for those properties in your css, and use <code>getStyle("myCustomStylePropertyName")</code> in your code to get the values set in the css.</p> <p>See <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=skinstyle_3.html" rel="nofollow">Flex 3 help: Example: Creating style properties</a> for more info.</p>
Trying to build an SQL statement for complex search scenario <p>I am trying to build an SQL Statement for the following search scenario:</p> <p>I have trying to return all of the columns for an individual record for Table A based on the value of the status column in Table B. Each record in table A can have multiple rows in table B, making it a one to many relationship. The status column is nullable with a data type of integer.</p> <p>Here are the possible values for status in table B:</p> <ul> <li>NULL = Pending,</li> <li>1 = Approved,</li> <li>2 = Denied,</li> <li>6 = Forced Approval,</li> <li>7 = Forced Denial</li> </ul> <p>The end user can search on the following scenarios:</p> <ul> <li>Approved - All table B records must have a value of 1 or 6 for status.</li> <li>Denied - One table B record must have a value of 2 or 5. Any other records can have 1,6, or null.</li> <li>Pending - All table B records can have a value of 1,6 or null. One record must be null because it is not considered completed.</li> </ul> <p><b>UPDATE</b><br /> I consulted with one of our DBAs and he developed the following solution:</p> <p>Approved:</p> <pre><code>SELECT a.* FROM TableA a INNER JOIN TableB ON b.id = a.id WHERE (b.status in (1,6) and b.status IS NOT NULL) AND b.id NOT IN (SELECT id from TableB WHERE status IS NULL) AND b.id NOT IN (SELECT id from TableB WHERE status in (2,7)) </code></pre> <p>Denied:</p> <pre><code>SELECT a.* FROM TableA a INNER JOIN TableB ON b.id = a.id WHERE (b.status in (2,7)) </code></pre> <p>Pending:</p> <pre><code>SELECT a.* FROM TableA a INNER JOIN TableB ON b.id = a.id WHERE (b.status IN (1,6) OR b.status IS NULL) AND b.id NOT IN (SELECT b.id FROM TableA a INNER JOIN TableB b ON b.id = a.id WHERE (b.status IN (1,6) AND b.status IS NOT NULL) AND b.id NOT IN (SELECT id from TableB WHERE status IS NULL)) AND b.id NOT IN (SELECT id FROM TableB WHERE status IN (2,7)) </code></pre> <p><b>UPDATE 2:</b><br /> @Micth Wheat - How would I refactor the following solution using the EXIST/NOT EXIST t-sql keyword?</p>
<p>As an example for 'Approved':</p> <pre><code>select * from A where (select count(*) from B where B.parent_id = A.id and B.status in (1,6)) &gt; 0 and (select count(*) from B where B.parent_id = A.id and B.status not in (1,6)) = 0 </code></pre> <p>Refactored to use <em>exists</em> and <em>not exists</em>:</p> <pre><code>select * from A where exists (select * from B where B.parent_id = A.id and B.status in (1,6)) and not exists (select * from B where B.parent_id = A.id and B.status not in (1,6)) </code></pre> <p>If you have passed in a criteria, you can package it all up in one query like this, if it is more convenient:</p> <pre><code>select * from A where (@Criteria = 'Approved' and (select count(*) from B where B.parent_id = A.id and B.status in (1,6)) &gt; 0 and (select count(*) from B where B.parent_id = A.id and B.status not in (1,6)) = 0 ) or (@Criteria = 'Denied' and (select count(*) from B where B.parent_id = A.id and B.status in (2,7)) &gt; 0 ) or (@Criteria = 'Pending' and (select count(*) from B where B.parent_id = A.id and B.status not in (2,7)) = 0 and (select count(*) from B where B.parent_id = A.id and B.status is null) &gt; 0 ) </code></pre> <p>Note, I changed the Denied example to be values of 2 and 7, rather than 2 and 5, based on your sample data.</p> <p>Edit: You could also use <em>exists</em> and <em>not exists</em>, as Joe suggests.</p> <p>Edit: The method using max(case ...), often also seen as sum(case ...) for counting values, does perform better in some cases (depends mostly on your volume of data whether the performance increase is noticeable - sometimes it can be a big difference). I personally find the subqueries more readable, so I start with them, and if better performance is needed, I would benchmark both methods, and if max(case ...) works better, I would switch.</p>
How to split on NULs in shell <p>I am using zsh as a shell.</p> <p>I would like to execute the unix find command and put the result into a shell array variable, something like:</p> <pre><code>FILES=($(find . -name '*.bak')) </code></pre> <p>so that I can iterate over the values with something like</p> <pre><code>for F in "$FILES[@]"; do echo "&lt;&lt;$F&gt;&gt;"; done </code></pre> <p>However, my filenames contain spaces at least, and perhaps other funky characters, so the above doesn't work. What does work is:</p> <pre><code>IFS=$(echo -n -e "\0"); FILES=($(find . -name '*.bak' -print0)); unset IFS </code></pre> <p>but that's fugly. This is already a bit beyond my comfort limit with zsh syntax, so I'm hoping someone can point me to some basic feature that I never knew about but should.</p>
<p>I tend to use <code>read</code> for that. A quick google search showed me zsh also seem to support that:</p> <pre><code>find . -name '*.bak' | while read file; do echo "&lt;&lt;$file&gt;&gt;"; done </code></pre> <p>That doesn't split with zero bytes, but it will make it work with file-names containing whitespace other than newlines. If the file-name appears at the very last of the command to be executed, you can use <code>xargs</code>, working also with newlines in filenames:</p> <pre><code>find . -name '*.bak' -print0 | xargs -0 cp -t /tmp/dst </code></pre> <p>copies all files found into the directory <code>/tmp/dst</code>. Downside of the xargs approach is that you don't have the filenames in a variable, of course. So this not always applicable.</p>
Python object.__repr__(self) should be an expression? <p>I was looking at the builtin object methods in the <a href="http://docs.python.org/reference/datamodel.html#objects-values-and-types">Python documentation</a>, and I was interested in the documentation for <code>object.__repr__(self)</code>. Here's what it says:</p> <blockquote> <p>Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form &lt;...some useful description...> should be returned. The return value must be a string object. If a class defines <strong>repr</strong>() but not <strong>str</strong>(), then <strong>repr</strong>() is also used when an “informal” string representation of instances of that class is required.</p> <p>This is typically used for debugging, so it is important that the representation is information-rich and unambiguous</p> </blockquote> <p>The most interesting part to me, was...</p> <blockquote> <p>If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value</p> </blockquote> <p>... but I'm not sure exactly what this means. It says it should <em>look</em> like an expression which can be used to recreate the object, but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?</p> <p>In general I'm a bit confused as to exactly what I should be putting here.</p>
<pre><code>&gt;&gt;&gt; from datetime import date &gt;&gt;&gt; &gt;&gt;&gt; repr(date.today()) # calls date.today().__repr__() 'datetime.date(2009, 1, 16)' &gt;&gt;&gt; eval(_) # _ is the output of the last command datetime.date(2009, 1, 16) </code></pre> <p>The output is a string that can be parsed by the python interpreter and results in an equal object.</p> <p>If that's not possible, it should return a string in the form of <code>&lt;...some useful description...&gt;</code>.</p>
Best way to organize a class hierarchy including an overridable "Update" function <p>I have a base class "Foo" that has an Update() function, which I want to be called once per frame for every instance of that class. Given an object instance of this class called "foo", then once per frame I will call foo->Update().</p> <p>I have a class "Bar" derived from my base class, that also needs to update every frame.</p> <p>I could give the derived class an Update() function, but then I would have to remember to call its base::Update() function - nothing enforces my requirement that the base::Update() function is called because I have overriden it, and could easily just forget to (or choose not to) call the base:Update function.</p> <p>So as an alternative I could give the base class a protected OnUpdate() function, which could be made overrideable, and call it from the base::Update() function. This removes the onus on me to remember to call base::Update() from the derived update function because I'm no longer overriding it. A Bar instance called "bar" will have bar->Update() called on it; this will first call the base class' Update() method, which will in turn call the overriden OnUpdate() function, performing the derived class' necessary updates.</p> <p>Which solves everything. Except. What if I want to derive yet another updatable class, this time from the "Bar" class.</p> <p>Baz (which derives from Bar) also has update requirements. If I put them in Baz's OnUpdate() function, I'm back to the original problem in that I'd have to remember to tell Baz's OnUpdate() function to call Bar's OnUpdate() function, otherwise Bar's OnUpdate() function wouldn't get called.</p> <p>So really, I'd want Bar's OnUpdate() function to be non-overridable, and instead for it to call an overridable function after it has done whatever it needed to do, perhaps called OnUpdate2()...</p> <p>And if I wanted to derive yet another class? OnUpdate3? OnUpdate4? AfterUpdate?</p> <p>Is there a Better Way?</p> <p><hr /></p> <p>Further Info:</p> <p>My specific problem domain is a 3d world. I've decided my base class is a "Locator" (an object with a location and orientation).</p> <p>My first derived class is a "PhysicsObject" - a Locator that also has mass, velocity, collision information, etc.</p> <p>My next derived class is a "Camera" - which derives from PhysicsObject. As well as position, and velocity, it also has information about the viewport, depth of field, etc.</p> <p><hr /></p> <p>MattK suggests simplifying the hierarchy - if a Locator is never referred to, incorporate it into PhysicsObject.</p> <p>I'm also thinking about how I would go about turning the layout upside down and using composition instead of inheritance.</p> <p>Perhaps a Camera HAS physics properties. Perhaps a PhysicsObject HAS a location.</p> <p>I'll have to think some more about this problem.</p> <p><hr /></p> <p>I like Uri's approach: "Observe the contract." Here's the rule - please follow it. Uri is right in that whatever kind of safeguards I try to put in, anyone could circumvent them, so perhaps in this case, the simplest solution is best. All my update() functions are going to have the requirement of calling their base::update() function.</p> <p>Thanks for the help everyone!</p>
<p>Sounds like you want composition instead of inheritance. What if there was an interface IUpdateable, and Foo held a collection of IUpdateable objects, and called an Update method on each one every tick? Then Bar and Baz could just implement Update; your only worry would be how best to register them with Foo.</p> <p>Based on your further info: You might want to consider your main object being analagous to your PhysicsObject, and using composition to include objects that implement specific behaviors, such as those of the Camera object.</p>
How can I test that I have a Python module successfully installed? <p>I tried to install beautifulsoup. I get such an error:<br> &lt;-- snip --></p> <pre><code>raise MissingSectionHeaderError(fpname, lineno, line) ConfigParser.MissingSectionHeaderError: File contains no section headers. file: /Users/Sam/.pydistutils.cfg, line: 1 'install_lib = ~/Library/Python/$py_version_short/site-packages\n' </code></pre> <p>I get an similar error as I run my Python code in vim by: :!python %</p>
<p>You can test if a module is installed like so:</p> <pre><code>$ python &gt;&gt;&gt; import modulename </code></pre>
Is there an algorithm to determine contiguous colored regions in a grid? <p>Given a basic grid (like a piece of graph paper), where each cell has been randomly filled in with one of n colors, is there a tried and true algorithm out there that can tell me what contiguous regions (groups of cells of the same color that are joined at the side) there are? Let's say n is something reasonable, like 5.</p> <p>I have some ideas, but they all feel horribly inefficient.</p>
<p>The best possible algorithm is O(number of cells), and is not related to the number of colors. </p> <p>This can be achieved by iterating through the cells, and every time you visit one that has not been marked as visited, do a graph traversal to find all the contiguous cells in that region, and then continue iterating.</p> <p>Edit:</p> <p>Here's a simple pseudo code example of a depth first search, which is an easy to implement graph traversal:</p> <pre><code>function visit(cell) { if cell.marked return cell.marked = true foreach neighbor in cell.neighbors { if cell.color == neighbor.color { visit(neighbor) } } } </code></pre>
What's your favorite log4 viewer / monitor? <p>We've decided to standardize on log4net and log4cxx for our logging infrastructure. I'd like to give our system administrators and other staff access to the events and information we are logging. So the short is, I'm looking for some a some recommended tools that help you keep track of the events coming out of your logger.</p> <p>Preferably any tool that can do so, could watch for events in real-time so that we can proactively respond, but that could simply be a matter of combining products.</p> <p>Here's my short list of products that appear to be easy to integrate with a log4 environment.</p> <ul> <li>Chainsaw</li> <li>Log4viewer</li> <li>Log4net Dashboard</li> </ul> <p>What viewers are you using?</p> <p>FWIW, there is another question on stackoverflow that at a glance appears to be similar, but the author seems to be looking for a viewer for Enterprise Library, not log4*.</p> <p><a href="http://stackoverflow.com/questions/50575/whats-your-favorite-free-log-viewer-for-entlib-or-log4net">http://stackoverflow.com/questions/50575/whats-your-favorite-free-log-viewer-for-entlib-or-log4net</a></p>
<p>I use <a href="http://www.baremetalsoft.com/baretail/" rel="nofollow">BareTail</a>.</p>
A SuggestBox for wxPython? <p>Is there a widget for wxPython like the <a href="http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html" rel="nofollow">SuggestBox</a> in Google Web Toolkit? It is basically a magic text box that can invoke some code to come up with suggestions relevant to whatever the user has entered so far. Like the search box on Google's web page.</p> <p>If such a widget isn't already floating out there, I'd appreciate a sketch of how I might implement it with the existing widgets.</p>
<p>You might want to look at <a href="http://wiki.wxpython.org/Combo%20Box%20that%20Suggests%20Options" rel="nofollow">Combo Box that Suggests Options</a>.</p> <p>I hope this is what you were thinking of.</p>
How to tell when a QTMovie starts playing? <p>So <code>QTMovie</code>s have <code>QTMovieDidEndNotification</code>, but no <code>QTMovieDidStartNotification</code>. How can I be notified when a <code>QTMovie</code> starts playing?</p>
<p>Answering my own question: the <code>QTMovieRateDidChangeNotification</code> is activated when the movie starts to play. Of course the documentation doesn't actually document that. Bah.</p>
SSAS cube design, semi-additive measures, and running totals <p>I have what is to me a bit of a tricky design issue in my SSAS cube. The question is related to general accounting practices, I have a fact table containing financial transactions (i.e. a ledger) and each of those transactions is tagged with a transaction date and a period. The period does NOT related directly to a day, or a series of days. Users may close a period in the middle of a day if that is when they have finished their months work. </p> <p>I need to be able to report on Accounts Receivable (AR) by both date and period. I am not using Enterprise Edition of SSAS so the time intelligence semi-additive options are not availabe to me, and even if they were they would only allow one time dimension to use non-standard aggregation and I believe in this case I need two that allow this.</p> <p>Accounts Receivable is a running total, it should be the sum of the latest ledger item selected and everything that came before it. I know how do do this calculation in MDX for a single time dimension, but how can I allow this to work with two time dimensions, transaction date, and period close? Is period close even considered a "time" dimension in this case? It does have a temporal aspect to it, and I do want the sums from all periods up to the current.</p> <p>I am stumped on how to related the two time dimensions to a single fact table and use different aggregation for each. Maybe the best solution here is to have two periodic snapshot tables (instead of trying to aggregate this info from the FactLedger table), one aggregated by transaction date and one by period which is the solution I am currently leaning towards but I would love a second opinion.</p>
<p>You can most certainly have more than one time dimension in a cube, and in this case I would actually just create one common time dimension and have it role play as two, transaction date and period close. To role play a dimension, just add it to the cube again in the Dimension Usage tab of the cube designer and rename it. Set up your references appropriately to key off of the two different fact columns.</p> <p>Or maybe I'm not understanding the issue correctly. This sounds pretty straight-forward.</p>
C# enumeration property null vs. 0 <p>I'm using IIS/asmx to support a Flash client. Some of my service layer data transfer objects have properties that are enumeration values. There are cases where these properties should be null. </p> <p>When an object with a null value for such an enumeration property is rendered to soap, I receive this error:</p> <pre><code>System.InvalidOperationException: There was an error generating the XML document. ---&gt; System.InvalidOperationException: Instance validation error: '0' is not a valid value for NameSpaceX.Model.NodeType. at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write1_NodeType(NodeType v) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write4_PackageDTO(String n, String ns, PackageDTO o, Boolean isNullable, Boolean needType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write15_ArrayOfPackageDTO(Object o) at Microsoft.Xml.Serialization.GeneratedAssembly.ListOfPackageDTOSerializer1.Serialize(Object objectToSerialize, XmlSerializationWriter writer) at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) --- End of inner exception stack trace --- at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces) at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o) at System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse response, Stream outputStream, Object returnValue) at System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream) at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues) at System.Web.Services.Protocols.WebServiceHandler.Invoke() </code></pre> <p>Is there a better solution then to create an enumeration member with value 0 (e.g. [0, "null"]? I suspect that I'm lacking basic knowledge here.</p> <p>Thanks.</p>
<p>My first inclination was to point you to the <code>Nullable&lt;T&gt;</code> type. However, after looking around for documentation on <code>Nullable&lt;T&gt;</code> and SOAP, it appears that it might not be supported. You might want to explore this further.</p> <p>That said, it is very common for Enums to declare a <code>NotSet = 0</code> member.</p>
How do I create a list of Python lambdas (in a list comprehension/for loop)? <p>I want to create a list of lambda objects from a list of constants in Python; for instance:</p> <pre><code>listOfNumbers = [1,2,3,4,5] square = lambda x: x * x listOfLambdas = [lambda: square(i) for i in listOfNumbers] </code></pre> <p>This will create a list of lambda objects, however, when I run them:</p> <pre><code>for f in listOfLambdas: print f(), </code></pre> <p>I would expect that it would print</p> <pre><code>1 4 9 16 25 </code></pre> <p>Instead, it prints:</p> <pre><code>25 25 25 25 25 </code></pre> <p>It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.</p> <p>EDIT: a bit more of trying things and such came up with this:</p> <pre><code>listOfLambdas = [] for num in listOfNumbers: action = lambda: square(num) listOfLambdas.append(action) print action() </code></pre> <p>Prints the expected squares from 1 to 25, but then using the earlier print statement:</p> <pre><code>for f in listOfLambdas: print f(), </code></pre> <p>still gives me all <code>25</code>s. How did the existing lambda objects change between those two print calls?</p> <p>Related question: <a href="http://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different">Why results of map() and list comprehension are different?</a></p>
<p>You have:</p> <pre><code>listOfLambdas = [lambda: i*i for i in range(6)] for f in listOfLambdas: print f() </code></pre> <p>Output:</p> <pre><code>25 25 25 25 25 25 </code></pre> <p>You need currying! Aside from being delicious, use this default value "hack".</p> <pre><code>listOfLambdas = [lambda i=i: i*i for i in range(6)] for f in listOfLambdas: print f() </code></pre> <p>Output:</p> <pre><code>0 1 4 9 16 25 </code></pre> <p>Note the <code>i=i</code>. That's where the magic happens. </p>
Suggest a JPA Unit test framework <p>How to unit test JPA code? is there any way to generate Unit Test case itself? </p> <p>Note: I am lazy and new to Unit Test code.</p>
<p>Check this out, <a href="http://www.unitils.org/summary.html">Unitils</a>. Here is a <a href="http://www.theserverside.com/news/thread.tss?thread_id=50487">related discussion</a>, with some example codes.</p> <p>Here is the example, showing <a href="http://bill.dudney.net/roller/bill/entry/20070428">DBUnit, Spring and OpenJPA</a> together. You might not using all, but this can take you somewhere if you want to go with <a href="http://www.dbunit.org/">DBUnit</a>, I believe.</p>
Implementation of Single Responsibility Principle <p>If I break my Objects down to 'Single Responsibilities', is there a fundamental thought whether like objects should live together or separately, for example if I have</p> <pre><code>class Employee_DataProvider() : IEmployee_DataProvider { ... }; class Employee_Details() : IEmployee_Details { ... }; class Employee_Payroll() : IPayroll() { ... }; class Employee_LeaveProcessing() : ILeaveProcessing_Client { ... }; ... </code></pre> <p>Is it bad smell to have all these living inside, yet loosely coupled to through interfaces, an owning Employee class:</p> <pre><code>class Employee { IEmployee_DataProvider _dataProvider; IEmployee_Details _details; IPayroll _payroll; ILeaveProcessing_Client _leaveProcessing; //My functions call the interfaces above } </code></pre> <p>or is the thinking more around keeping these classes completely separate (or as least as separate as is posible) in the code? Or are both these methods a valid usage of SRP?</p> <p><strong>EDIT:</strong> I do not want critique on the feasibility of the object given in the example, I just made it up to illustrate the question. I agree data, leave and payroll processing are not the domain of the employee class. </p> <p>It does appear though that SRP is asking me to move away from the object as real world representation to object as a properties and methods around a single functional concept</p>
<p>Go back to OOP basics: the Employee object should have methods that reflect what it does, not what is done to it.</p>
Why the slow WADL uptake? <p>I've been researching WADL and am wondering why it isn't more widely adopted? </p> <p>With the rate at which REST usage seems to be growing, I'm surprised that more development efforts don't use it.</p> <p>Is there are fundamental flaw in its design, is it not a good match for the culture that typically surrounds RESTful web services, or is it something else entirely?</p>
<p>I think the main reason why WADL doesn't gain popularity is that it might bring back to life all those problem we had with SOAP and WSDL. To me, the interoperability aspect is the single most important aspect of web-services.<br> By following the RESTful way of using pure HTTP standards you get interoperability "for free". Once you need a document to describe the services, there will be different client frameworks (or different servers frameworks) that will interpret this document differently. Once different frameworks auto-generate code from WADL you will have to deal with the interoperability problems again.</p> <p>The lack of standards is the weakness and strength of the RESTful way, let's give the simple approach a chance. (even though we really enjoy automatic code generation :-) ) </p>
String altering in Ant <p>Given a property:</p> <pre><code>&lt;property name="classes" value="com.package.Class1,com.package.Class2" /&gt; </code></pre> <p>I'm trying to compile only the classes specified like:</p> <pre><code>&lt;javac srcdir="${src.dir}" destdir="${build.dir}"&gt; &lt;include name="${classes}" /&gt; &lt;/javac&gt; </code></pre> <p>However the 'include' tag is specifying the file names to include, not the qualified class names.</p> <p>Is there a way I can create a new property/include tag that has all the classes in 'classes' in the correct format? ie. </p> <pre><code>"com.package.Class1" -&gt; "com\\package\\Class1.java" </code></pre>
<p>I figured it out. After ant-contrib I can do one of these:</p> <pre><code>&lt;propertyregex property="classes.resolved" input="${classes}" regexp="\." replace="\\\\" /&gt; </code></pre>
All the reasons I can't access an instance of SQL 2005 <p>I've installed an instance of SQL 2005 Express on <code>&lt;computername&gt;/SQLEXPRESS</code>. There is only once instance installed. I've allowed remote connections, turned on SQL authentication, enabled TCP/IP, Named Pipes and VIA but I still can't access the database from another computer. I keep getting:</p> <blockquote> <p>A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)</p> </blockquote> <p>What else can I look for? I'm sure my code is correct as it was used to connect to this same system prior to it being wiped. I'm pretty confident the connection string is correct as well:</p> <pre><code>Server=&lt;computername&gt;\SQLEXPRESS;User Id=&lt;username&gt;;Password=&lt;password&gt;; </code></pre> <p>There's also no firewalls standing between the two systems. They're on the same network segment and Windows Firewall has been shut off completely.</p>
<p>Is the SQL Server Browser running on the machine? For named instances, like \SQLExpress, the SQL Browser allows client machines to identify which port to connect to. </p> <p>By default, only the default instance runs on TCP 1433. If the client can't connect on the default port, it queries the SQL Browser at UDP 1434 to locate the correct port to use for a given named instance.</p>
How to add a server image control to html container using innerHTML = <p>I have a td that I want to inject with a server image control (asp.net) using innerHTML = "". The webcontrol's toString is giving the type.</p> <p>Is there a way to extract the generated from the server control? Or, is there a different solution...?</p> <p>Thanks</p>
<pre><code>StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); img.RenderControl(new HtmlTextWriter(writer)); td.InnerHtml = sb.ToString(); </code></pre> <p>or the more obvious</p> <pre><code>td.Controls.Add(img); </code></pre>
How can I create a product key for my C# application? <p>How can I create a product key for my C# Application?</p> <p>I need to create a product (or license) key that I update annually. Additionally I need to create one for trial versions.</p> <blockquote> <p>Related: </p> <ul> <li><a href="http://stackoverflow.com/questions/501988/how-do-i-best-obfuscate-my-c-product-license-verification-code">How do I best obfuscate my C# product license verification code?</a> </li> <li><a href="http://stackoverflow.com/questions/437049/web-based-license-activation">Web-based license activation</a> </li> <li><a href="http://stackoverflow.com/questions/109997/how-do-you-protect-your-software-from-illegal-distribution">How do you protect your software from illegal distribution?</a></li> <li><a href="http://stackoverflow.com/questions/118031/best-activation-key-software-for-net-application">Best activation key software for .NET application?</a></li> </ul> </blockquote>
<p>You can do something like create a record which contains the data you want to authenticate to the application. This could include anything you want - e.g. program features to enable, expiry date, name of the user (if you want to bind it to a user). Then encrypt that using some crypto algorithm with a fixed key or hash it. Then you just verify it within your program. One way to distribute the license file (on windows) is to provide it as a file which updates the registry (saves the user having to type it).</p> <p>Beware of false sense of security though - sooner or later someone will simply patch your program to skip that check, and distribute the patched version. Or, they will work out a key that passes all checks and distribute that, or backdate the clock, etc. It doesn't matter how convoluted you make your scheme, anything you do for this will ultimately be security through obscurity and they will always be able to this. Even if they can't someone will, and will distribute the hacked version. Same applies even if you supply a dongle - if someone wants to, they can patch out the check for that too. Digitally signing your code won't help, they can remove that signature, or resign it.</p> <p>You can complicate matters a bit by using techniques to prevent the program running in a debugger etc, but even this is not bullet proof. So you should just make it difficult enough that an honest user will not forget to pay. Also be very careful that your scheme does not become obtrusive to paying users - it's better to have some ripped off copies than for your paying customers not to be able to use what they have paid for.</p> <p>Another option is to have an online check - just provide the user with a unique ID, and check online as to what capabilities that ID should have, and cache it for some period. All the same caveats apply though - people can get round anything like this.</p> <p>Consider also the support costs of having to deal with users who have forgotten their key, etc.</p> <p><em>edit: I just want to add, don't invest too much time in this or think that somehow your convoluted scheme will be different and uncrackable. It won't, and cannot be as long as people control the hardware and OS your program runs on. Developers have been trying to come up with ever more complex schemes for this, thinking that if they develop their own system for it then it will be known only to them and therefore 'more secure'. But it really is the programming equivalent of trying to build a perpetual motion machine. :-)</em></p>
Using ant to detect os and set property <p>I want to set a property in an ant task differently by os type.</p> <p>The property is a directory, in windows i want it to be "c:\flag" in unix/linux "/opt/flag".</p> <p>My current script only works when i run it with the default target, but why ? </p> <pre><code> &lt;target name="checksw_path" depends="if_windows, if_unix"/&gt; &lt;target name="checkos"&gt; &lt;condition property="isWindows"&gt; &lt;os family="windows" /&gt; &lt;/condition&gt; &lt;condition property="isLinux"&gt; &lt;os family="unix" /&gt; &lt;/condition&gt; &lt;/target&gt; &lt;target name="if_windows" depends="checkos" if="isWindows"&gt; &lt;property name="sw.root" value="c:\flag" /&gt; &lt;echo message="${sw.root}"/&gt; &lt;/target&gt; &lt;target name="if_unix" depends="checkos" if="isLinux"&gt; &lt;property name="sw.root" value="/opt/flag" /&gt; &lt;echo message="${sw.root}"/&gt; &lt;/target&gt; </code></pre> <p>In all my ant targets i've added a "depends=checksw_path".</p> <p>If i run the default target in windows i've got correctly "c:\flag" but if i run a non default target i've got that the debug goes in the if_windows but the instruction " " does not set the property that remains /opt/flag. I'm using ant 1.7.1.</p>
<p>Move your condition out of the <code>&lt;target /&gt;</code>, as your target probably isn't invoked.</p> <pre><code> &lt;condition property="isWindows"&gt; &lt;os family="windows" /&gt; &lt;/condition&gt; &lt;condition property="isLinux"&gt; &lt;os family="unix" /&gt; &lt;/condition&gt; </code></pre>
Running DOS games under Dosbox 0.72 <p>I am using Windows Vista and with Dosbox 0.72 to load Turbo C for programming a DOS game. My code runs fine (both graphics and sound routines) as long as it runs under DOS shell of Turbo C (Under Dosbox). But when I run the same code under DosBox (outside Turbo C's Dos shell), the graphics flickers, slows down and the sound cracks. Whats wrong??</p> <p>Pramod</p>
<p>Maybe your program gets too much memory when run standalone. You can determine how much memory is available with MEM command, and reduce this amount before running your program with LOADFIX command. You can run LOADFIX command several times, each time it will reduce free memory in the system</p>
Process Guidelines Required <p>My company does not follow any well defined process for software development. I want to implement a simple but effective process which will suit my company. </p> <p>We have all sets of resources right from project managers to developers and testers.</p> <p>Please provide some references or process templates that I can use.</p>
<p>You are really not describing the characteristics of your company or the main challenges you are facing, so it's hard to give good advice. You could try something like <a href="http://en.wikipedia.org/wiki/Scrum_(development)" rel="nofollow">scrum</a> if you want something lightweight, which is probably a good idea if you have little or no existing process. </p>
To what extent can Version Control help in system administration? <p>I'm currently tinkering at an OpenBSD system with a view to building myself a firewall and some other bits and bobs.</p> <p>As this is fairly experimental (I'm an OpenBSD n00b, and I've already trashed my system 3 or 4 times), I wonder what experience others have of making part or all of the file system (I'm thinking in particular of /etc) a working copy of some VCS or other.</p> <ul> <li><p>Is this a good idea?</p></li> <li><p>I'm particularly interested in which VCS people have used for this. I'm considering subversion, bazaar, and git; this won't be a shared repository, so I'm perhaps more interested in the basic vcs functionality than the distributed-or-not argument.</p></li> <li><p>I'd also like to hear about imagined or actual pitfalls people have found. I can imagine the preservation of file ownership and permissions needs careful thought!</p></li> <li><p>And, of course, any alternative approaches not involving VCS</p></li> </ul>
<p><a href="http://bryan-murdock.blogspot.com/2007/07/put-etc-under-revision-control-with-git.html" rel="nofollow">Here</a> you have a detailed revision about putting /etc/ under revision control using git.</p> <p><a href="http://www.jukie.net/~bart/blog/20070312134706" rel="nofollow">Another</a> step by step method. </p>
ASP.NET Web application security in VDS hosting <p>We are designing asp.net web application in wcsf. Web application will be deployed to Windows Server 2003 shared <a href="http://en.wikipedia.org/wiki/Virtual_private_server" rel="nofollow">VDS</a> hosting. Web site will be used for b2b, monthly service fee and credit card transactions used in web application so it must be secure site. I want to consider what must be done before deployment and i need an answer to a few questions:</p> <p>1) How can i copy protect my site &amp; my code. Is code signing enough? What should i do for reflector protection? Obfuscation is enough?</p> <p>2) What about Windows Server 2003 <a href="http://en.wikipedia.org/wiki/Virtual_private_server" rel="nofollow">VDS</a> hosting pros &amp; cons?</p> <p>3) MS SQL Server 2005 Express is suitable for that kind of business use? Limitation of mssql express (4GB storage and 1Gb ram) cause bottlenecks in website? </p> <p>4) Can I transfer database from express edition to mssql 2005 workgroup edition in the future without problem?</p>
<ol> <li><p>Obfuscation would be sufficient. Code signing doesn't provide any protection from prying eyes. Also most respectable hosters aren't interested in your intellectual property and data. They're in the hosting business at the end of the day.</p></li> <li><p>I work for a hosting company and we have a fast growing number of customers hosted on our virtualisation platform. One of the advantages for both the customer and ourselves is that if you need more CPU or memory, we can add them almost immediately because this is just a config setting on the VM. Ultimately it all depends on how your supplier has built his virtual environment. You really need to gather more information about the capabilities and limits of their environment, how many servers per node they typically run etc, and decide if it's adequate for you.</p></li> <li><p>SQL 2005 express will perform as well as full fat SQL 2005. The limitations are in functionality (e.g. no olap, that kinda thing) and as you correctly point out, the maximum amount of memory it can utilise and max size of DB. Performance will degrade however if you outgrow the maximum amount of memory available.</p></li> <li><p>SQL 2005 Express databases can be backed up and restored to any SQL 2005/2008 product without any problems.</p></li> </ol> <p>Without knowing the volume of traffic that will hit your application it would be hard to predict whether a virtual server is the best choice of environment. The same applies to SQL 2005 express. If the app is database intensive you may find yourself under increased memory pressure - the more memory SQL server has the more it can cache. I think you need to do some of your own capacity planning and decide for yourself what is the the optimal solution for now and later down the line.</p>
Shell script for adjusting image size <p>Is there a way to adjust all image sizes in a directory?</p> <p>If I set the max size to 800x600 it will make larger ones smaller and leave smaller ones at their original size.</p>
<pre><code>for img in *.png; do convert "$img" "800x600&gt;" $(basename "$img" .png)_new.png done </code></pre> <p><code>convert</code> is from ImageMagick. ">" says it's only resized if larger. See <a href="http://www.imagemagick.org/script/command-line-options.php#resize">here</a> for its other options.</p>
Help with include function <p>Im trying to make a simple template system in PHP. I'm new to PHP, so it's nothing serious. I have some problems though:</p> <p>A regular include works:</p> <pre><code>$variable = "test"; include("templates/news.html"); </code></pre> <p>But this won't:</p> <p>This says <code>$variable</code> is undefined:</p> <pre><code>$variable = "test"; getTemplate("news"); </code></pre> <p>The Function:</p> <pre><code>function getTemplate($tpl) { $file = "templates/$tpl.html"; if (file_exists($file)) return include($file); return false; } </code></pre> <p>news.html</p> <pre><code>&lt;h1&gt;php echo $variable&lt;/h1&gt; </code></pre> <p>the function works and includes the page but it dont write out the variables</p> <p>I include the function on top of all pages.</p> <p>Thanks in advance!</p>
<p>With the <a href="http://php.net/extract" rel="nofollow">extract</a> function, you can define different variables from an array.</p> <p>You can make it like this:</p> <pre><code>$vars = array('var1' =&gt; "value1", 'var2' =&gt; "value2"); function getTemplate($tpl, $vars) { $file = "templates/$tpl.html"; extract($vars, EXTR_SKIP) if (file_exists($file)) return include($file); return false; } getTemplate('news', $vars); </code></pre> <p>In your template, you can use $var1 and $var2.</p>
COM event handling in C++ <p><b>Without</b> the following:</p> <ul> <li>ATL</li> <li>MFC</li> </ul> <p><b>Question:</b></p> <ul> <li>How to get the COM <b>Server</b>, to report back to the COM <b>Client</b>, once a particular event has terminated? </li> </ul> <p>Regards</p>
<p><b>See:</b> <a href="http://www.codeproject.com/KB/COM/TEventHandler.aspx?fid=133954&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=None&amp;select=2755820#xx2755820xx" rel="nofollow"><b>COM</b> event handling - IConnectionPointContainer - illustration</a></p>
Java's Virtual Machine and CLR <p>As a sort of follow up to the question called <a href="http://stackoverflow.com/questions/95163/differences-between-msil-and-java-bytecode">Differences between MSIL and Java bytecode?</a>, what is the (major) differences or similarity in how the Java Virtual Machine works versus how the <del>.NET Framework</del> Common Language Runtime (CLR) works?</p> <p>Also, is the <del>.NET framework</del> CLR a "virtual machine" or does it not have the attributes of a virtual machine? </p>
<p>There are a lot of similarities between both implementations (and in my opinion: yes, they're both "virtual machines").</p> <p>For one thing, they're both stack-based VM's, with no notion of "registers" like we're used to seeing in a modern CPU like the x86 or PowerPC. The evaluation of all expressions ((1 + 1) / 2) is performed by pushing operands onto the "stack" and then popping those operands off the stack whenever an instruction (add, divide, etc) needs to consume those operands. Each instruction pushes its results back onto the stack.</p> <p>It's a convenient way to implement a virtual machine, because pretty much every CPU in the world has a stack, but the number of registers is often different (and some registers are special-purpose, and each instruction expects its operands in different registers, etc).</p> <p>So, if you're going to model an abstract machine, a purely stack-based model is a pretty good way to go.</p> <p>Of course, real machines don't operate that way. So the JIT compiler is responsible for performing "enregistration" of bytecode operations, essentially scheduling the actual CPU registers to contain operands and results whenever possible.</p> <p>So, I think that's one of the biggest commonalities between the CLR and the JVM.</p> <p>As for differences...</p> <p>One interesting difference between the two implementations is that the CLR includes instructions for creating generic types, and then for applying parametric specializations to those types. So, at runtime, the CLR considers a List&lt;int&gt; to be a completely different type from a List&lt;String&gt;.</p> <p>Under the covers, it uses the same MSIL for all reference-type specializations (so a List&lt;String&gt; uses the same implementation as a List&lt;Object&gt;, with different type-casts at the API boundaries), but each value-type uses its own unique implementation (List&lt;int&gt; generates completely different code from List&lt;double&gt;).</p> <p>In Java, generic types are a purely a compiler trick. The JVM has no notion of which classes have type-arguments, and it's unable to perform parametric specializations at runtime.</p> <p>From a practical perspective, that means you can't overload Java methods on generic types. You can't have two different methods, with the same name, differing only on whether they accept a List&lt;String&gt; or a List&lt;Date&gt;. Of course, since the CLR knows about parametric types, it has no problem handling methods overloaded on generic type specializations.</p> <p>On a day-to-day basis, that's the difference that I notice most between the CLR and the JVM.</p> <p>Other important differences include:</p> <ul> <li><p>The CLR has closures (implemented as C# delegates). The JVM does support closures only since Java 8.</p></li> <li><p>The CLR has coroutines (implemented with the C# 'yield' keyword). The JVM does not.</p></li> <li><p>The CLR allows user code to define new value types (structs), whereas the JVM provides a fixed collection of value types (byte, short, int, long, float, double, char, boolean) and only allows users to define new reference-types (classes).</p></li> <li><p>The CLR provides support for declaring and manipulating pointers. This is especially interesting because both the JVM and the CLR employ strict generational compacting garbage collector implementations as their memory-management strategy. Under ordinary circumstances, a strict compacting GC has a really hard time with pointers, because when you move a value from one memory location to another, all of the pointers (and pointers to pointers) become invalid. But the CLR provides a "pinning" mechanism so that developers can declare a block of code within which the CLR is not allowed to move certain pointers. It's very convenient.</p></li> <li><p>The largest unit of code in the JVM is either a 'package' as evidenced by the 'protected' keyword or arguably a JAR (i.e. Java ARchive) as evidenced by being able to specifiy a jar in the classpath and have it treated like a folder of code. In the CLR, classes are aggregated into 'assemblies', and the CLR provides logic for reasoning about and manipulating assemblies (which are loaded into "AppDomains", providing sub-application-level sandboxes for memory allocation and code execution).</p></li> <li><p>The CLR bytecode format (composed of MSIL instructions and metadata) has fewer instruction types than the JVM. In the JVM, every unique operation (add two int values, add two float values, etc) has its own unique instruction. In the CLR, all of the MSIL instructions are polymorphic (add two values) and the JIT compiler is responsible for determining the types of the operands and creating appropriate machine code. I don't know which is the preferably strategy, though. Both have trade-offs. The HotSpot JIT compiler, for the JVM, can use a simpler code-generation mechanism (it doesn't need to determine operand types, because they're already encoded in the instruction), but that means it needs a more complex bytecode format, with more instruction types.</p></li> </ul> <p>I've been using Java (and admiring the JVM) for about ten years now.</p> <p>But, in my opinion, the CLR is now the superior implementation, in almost every way.</p>
Which numerical values do the F-Keys ( F[1-12]) and the Arrow-keys have? <p>I'd like to write an application in C which uses arrow-keys to navigate and F-keys for other functions, such as saving to a file, language selection, etc.</p> <p>Propably the values depend on the platform, so how could I find out which values the keys have?</p> <p>If they don't, or if you know them, I don't have to know how to find out;)</p> <p>Edit: My platforms are Linux and M$ Windows. Therefore, I'm looking for a solution as portable as possible.</p> <p>(Propably something like</p> <pre><code>#ifdef __unix__ #define F1 'some number' /* ... */ #define ARROW_UP 'some other number' #elif __WIN32__ || MSDOS /*whatever*/ #define F1 'something' /* ... */ #define ARROW_UP 'something different' #endif </code></pre> <p>)</p>
<p>I think that depends on $TERM, but either way it's going to be a sequence of characters. I get this:</p> <pre><code>% read x; echo $x | od -c -- ^[[15~ 0000000 033 [ 1 5 ~ \n 0000006 </code></pre> <p>That's my F5 key, and apologies for this being a *nix-centric answer, if that's not your platform.</p>
Protocol buffers in C# projects using protobuf-net - best practices for code generation <p>I'm trying to use protobuf in a C# project, using protobuf-net, and am wondering what is the best way to organise this into a Visual Studio project structure.</p> <p>When manually using the protogen tool to generate code into C#, life seems easy but it doesn't feel right.</p> <p>I'd like the .proto file to be considered to be the primary source-code file, generating C# files as a by-product, but before the C# compiler gets involved.</p> <p>The options seem to be:</p> <ol> <li>Custom tool for proto tools (although I can't see where to start there)</li> <li>Pre-build step (calling protogen or a batch-file which does that)</li> </ol> <p>I have struggled with 2) above as it keeps giving me "The system cannot find the file specified" unless I use absolute paths (and I don't like forcing projects to be explicitly located).</p> <p>Is there a convention (yet) for this?</p> <p><hr /></p> <p><strong><em>Edit:</em></strong> Based upon @jon's comments, I retried the pre-build step method and used this (protogen's location hardcoded for now), using Google's address-book example:</p> <pre><code>c:\bin\protobuf\protogen "-i:$(ProjectDir)AddressBook.proto" "-o:$(ProjectDir)AddressBook.cs" -t:c:\bin\protobuf\csharp.xslt </code></pre> <p><hr /></p> <p><strong><em>Edit2:</em></strong> Taking @jon's recommendation to minimise build-time by not processing the .proto files if they haven't changed, I've knocked together a basic tool to check for me (this could probably be expanded to a full Custom-Build tool):</p> <pre><code>using System; using System.Diagnostics; using System.IO; namespace PreBuildChecker { public class Checker { static int Main(string[] args) { try { Check(args); return 0; } catch (Exception e) { Console.WriteLine(e.Message); return 1; } } public static void Check(string[] args) { if (args.Length &lt; 3) { throw new ArgumentException( "Command line must be supplied with source, target and command-line [plus options]"); } string source = args[0]; string target = args[1]; string executable = args[2]; string arguments = args.Length &gt; 3 ? GetCommandLine(args) : null; FileInfo targetFileInfo = new FileInfo(target); FileInfo sourceFileInfo = new FileInfo(source); if (!sourceFileInfo.Exists) { throw new ArgumentException(string.Format( "Source file {0} not found", source)); } if (!targetFileInfo.Exists || sourceFileInfo.LastWriteTimeUtc &gt; targetFileInfo.LastAccessTimeUtc) { Process process = new Process(); process.StartInfo.FileName = executable; process.StartInfo.Arguments = arguments; process.StartInfo.ErrorDialog = true; Console.WriteLine(string.Format( "Source newer than target, launching tool: {0} {1}", executable, arguments)); process.Start(); } } private static string GetCommandLine(string[] args) { string[] arguments = new string[args.Length - 3]; Array.Copy(args, 3, arguments, 0, arguments.Length); return String.Join(" ", arguments); } } } </code></pre> <p>My pre-build command is now (all on one line):</p> <pre><code>$(SolutionDir)PreBuildChecker\$(OutDir)PreBuildChecker $(ProjectDir)AddressBook.proto $(ProjectDir)AddressBook.cs c:\bin\protobuf\protogen "-i:$(ProjectDir)AddressBook.proto" "-o:$(ProjectDir)AddressBook.cs" -t:c:\bin\protobuf\csharp.xslt </code></pre>
<p>As an extension of Shaun's code, I am pleased to announce that protobuf-net now has Visual Studio integration by way of a Custom Tool. The msi installer is available from the <a href="http://code.google.com/p/protobuf-net/">project page</a>. More complete information here: <a href="http://marcgravell.blogspot.com/2009/07/protobuf-net-now-with-added-orcas.html">protobuf-net; now with added Orcas</a>.</p> <p><img src="http://lh6.ggpht.com/%5FfeJtUp7IGuI/Sl7rs9FkdHI/AAAAAAAAAJY/zoDaMfuthIw/proto-vs%5Fthumb%5B1%5D.png?imgmax=800" alt="Visual Studio with protobuf-net as a Custom Tool" /></p>
embedding an application within a c# program with gtk# <p>I'd like to embed a movie watching application like VLC into my C# program using the GTK# binding.</p> <p>Googling, I haven't seen many solutions that people have claimed to be easy or that work.</p> <p>Experiences? Help?</p> <p>Please!</p> <p>Thanks, jbu</p>
<p>I'm not sure for VLC but <a href="http://banshee-project.org/" rel="nofollow">Banshee</a>, a C# GTK+ multimedia app, uses <a href="http://gstreamer.freedesktop.org/" rel="nofollow">GStreamer</a> to embed videos in its interface. Maybe their code could help you.</p> <p>GStreamer is cross-platform and has many plugins for most video formats out there.</p>
Suggestions for writing a programming language? <p>What tips can you give a person who is looking to write a programming or script language? I am not worried about how to program nor design a compiler but how to develop one quickly using tools and code generators.</p> <p>Last time i tried i coded it in c++ and the states and syntax took almost as long as writing the actual logic. I know the follow tools would help.</p> <p>I was thinking i could generate c++ code and have gcc compile that. Using the tools above how long would you estimate it would take to write a program or script language?</p> <hr> <p>Variations on this question have been asked repeatedly, as far back as <a href="http://stackoverflow.com/questions/1669/learning-to-write-a-compiler">Learning to Write a Compiler</a>. <a href="http://stackoverflow.com/questions/365602/creating-your-own-language#365636">Here is an incomplete list of SO resources</a> on the topic.</p>
<p>Estimating how long something like that might take is dependent on many different factors. For example, an experienced programmer can easily knock out a simple arithmetic expression evaluator in a couple of hours, with unit tests. But a novice programmer may have to learn about parsing techniques, recursive descent, abstract representation of expression trees, tree-walking strategies, and so on. This could easily take weeks or more, just for arithmetic expressions.</p> <p>However, don't let that discourage you. As Jeff and Joel were discussing with Eric Sink on a <a href="http://blog.stackoverflow.com/2009/01/podcast-36/">recent Stack Overflow podcast</a>, writing a compiler is an excellent way to learn about many different aspects of programming. I've built a few compilers and they are among my most memorable programming projects.</p> <p>Some classic books on building compilers are:</p> <ul> <li><a href="http://dragonbook.stanford.edu/">Compilers: Principles, Techniques, and Tools</a> (also known as The Dragon Book)</li> <li><a href="http://mitpress.mit.edu/sicp/">The Structure and Interpretation of Computer Programs</a> (also known as SICP)</li> <li><a href="http://www.inf.ethz.ch/personal/wirth/books/AlgorithmE0/">Algorithms + Data Structures = Programs</a></li> </ul>
seam-gen, netbeans and completion <p>How can I make <a href="http://docs.jboss.org/seam/1.1BETA2/reference/en/html/gettingstarted.html" rel="nofollow">seam-gen</a> work with <a href="http://www.netbeans.org/" rel="nofollow">NetBeans</a> 6.5 so that completion of tags (s:, ui:, rich:, ...) works? In the free-form project that seam-gen creates, this does not seam to work. If I create a standard NetBeans web application (File -> New Project), completion does work though.</p> <p>Thanks, m.</p>
<p>check your netbeans log. it's propobly facelet parser crashing on richaces taglib. i had this problem with RF v3.2.2, older release worked fine. </p>
DSN-less ODBC connect string for legacy Sybase Adaptive Server Anywhere <p>This is a failed response to this article: <a href="http://www.vbrad.com/article.aspx?id=94" rel="nofollow">Sybase, VB and ADO</a></p> <p>I just did a VB6 project connecting to a legacy ASA 7 database. After failing to use ASAProv OLEDB provider altogether (for one reason or another) and much research, here is the connect string for OLEDB Provider for ODBC shim for a DSN-less ODBC driver connection:</p> <p><code>Provider=MSDASQL.1;Driver={Adaptive Server Anywhere 7.0};CommLinks=TCPIP,SharedMemory;EngineName=&lt;database_name&gt;;UID=DBA;PWD=SQL</code></p> <p>where <code>&lt;database_name&gt;</code> is the instance name dbeng7.exe is running the db under. Check the engine log for 'Starting database "<code>&lt;database_name&gt;</code>"'.</p> <p>You can find all the valid property names for an ODBC connect string by creating a system DSN, adjust settings and inspecting values <code>HKLM\SOFTWARE\ODBC\ODBC.INI\&lt;system_dsn&gt;</code> key.</p> <p>The available ODBC drivers that can be used under Driver property of the MSDASQL provider connect string are subkeys of <code>HKLM\SOFTWARE\ODBC\ODBCINST.INI</code></p> <p>Apparently Sybase login passwords are case insensitive which I find quite hilarious.</p> <p>cheers<br> <code>&lt;/wqw&gt;</code></p>
<p>Wow, I actually wrote that article in the last millennium, I believe.</p> <p>Let me take this point by point. </p> <ol> <li><p>OLEDB provider works fine for it, I remember using them from back in the day. Just follow instructions here: <a href="http://www.vbrad.com/article.aspx?id=81" rel="nofollow">http://www.vbrad.com/article.aspx?id=81</a> on how to create a connection string.</p></li> <li><p>For ODBC, going to <a href="http://www.connectionstrings.com/" rel="nofollow">http://www.connectionstrings.com/</a> has never failed me. They got connection strings up wazoo.</p></li> </ol>
Windows 7 MSDN Expiration <p>I have read that the public beta version of Windows 7 has an expiration on it, but does the MSDN Premium also expire on the same date?</p> <p>And if so, do you think that we might see a newer version before the expiration on MSDN?</p> <p>For the speed improvements alone I am contemplating moving my development PC to Windows 7 over Windows Vista, stability issues aside, I am an early adopter anyway and expect issues with beta operating systems.</p>
<p>As I have done for a while with VStudio 10 CTP, you have the possibility to change the clock on you virtual machine when you start it. In my case, when I lunche VS10, I settle my virtual machine's clock to 11/1/2008 - and it's still running !</p>
Doing a range lookup in C#? <p>I have a list of non-overlaping ranges (ranges of numbers, e.g. 500-1000, 1001-1200 .. etc), is there an elegant and fast way to do lookup by only passing a number? I could use List.BinarySearch() or Array.BinarySearch() but I have to pass the type of the range object (Array.BinarySearch(T[], T)), I can pass a dummy range object and get the job done (only do the comparison with the range start) but I was wondering if this can be done in a cleaner way by only passing an integer and getting the range object, is there a way to achieve this?</p>
<p>Three options:</p> <ul> <li>Create a dummy Range and suck it up. Urgh.</li> <li>Hand-craft a binary search just for this case. Not too bad.</li> <li>Generalise the binary search for any IList and a TValue, given an IRangeComparer. I'm not wild on the name "TRange" here - we're not necessarily talking about ranges, but just finding the right place based on a comparison between two different types.</li> </ul> <p>The third option would go <em>something</em> like:</p> <pre><code>public interface IRangeComparer&lt;TRange, TValue&gt; { /// &lt;summary&gt; /// Returns 0 if value is in the specified range; /// less than 0 if value is above the range; /// greater than 0 if value is below the range. /// &lt;/summary&gt; int Compare(TRange range, TValue value); } /// &lt;summary&gt; /// See contract for Array.BinarySearch /// &lt;/summary&gt; public static int BinarySearch&lt;TRange, TValue&gt;(IList&lt;TRange&gt; ranges, TValue value, IRangeComparer&lt;TRange, TValue&gt; comparer) { int min = 0; int max = ranges.Count-1; while (min &lt;= max) { int mid = (min + max) / 2; int comparison = comparer.Compare(ranges[mid], value); if (comparison == 0) { return mid; } if (comparison &lt; 0) { min = mid+1; } else if (comparison &gt; 0) { max = mid-1; } } return ~min; } </code></pre> <p>Apologies if I've got any off-by-one errors. I haven't tested it at all, but it does at least compile :)</p>
C# whats best method of saving dynamically created controls <p>I am currently saving a .net ( c# ) usercontrol to the disk as a XML file by saving each property as an element in the xml document. The file is used for later recreation of the controls at runtime. I am wondering if it is possible or better to save the control as a binary file. There would be many controls so I guess it would have to have a header section describing the location and length of each saved controls. Thoughts?</p> <p>Brad</p> <p>BTW this is a windows app</p> <p>EDIT:</p> <p>what I currently have inplace is a public member function that uses the propertyDescriptior class to itinerate through all the properties and create an xml document from that.</p> <pre><code> PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(this); for (int i = 0; i &lt;= pdc.Count - 1; i++) { pdc[i].Name pdc[i].PropertyType pdc[i].Category </code></pre> <p>}</p> <p>I will look into creating the class Serializable - thanks</p>
<p>Winforms controls don't serialize especially well, and you might have a lot of difficulty getting the base-classes (i.e. not your code) to play ball. Things like <code>Color</code>, for example, regularly provide surprisingly troublesome to serialize.</p> <p>Xml would be an obvious (if somewhat predictable) choice, but you generally need to nominate sub-classes ahead of time. And of course, the base-classes won't be marked serializable. <code>BinaryFormatter</code> would avoid some of that, but as a field-based serializer, you'd have problems with the "handles" etc in the base-classes, which are meaningless serialized.</p> <p>I'm not saying it can't be done - but it won't be trivial either. As a starter, you'd want to look at <code>TypeConverter.GetProperties</code>, and use the <code>Converter</code> of each to get the value as an invariant string.</p>
How to write a Vertical Right-Side IE Explorer Bar <p>I've written explorer bars (band object) before and <strong>AFAIK vertical explorer bars can only be on the left side</strong>. However, I was amazed when I saw this explorer bar by HP that is docked on the right hand side instead:</p> <p><img src="http://farm4.static.flickr.com/3493/3204746881_58eb9706fc.jpg" alt="A vertical explorer bar on the right hand side" /></p> <p>I've searched up google for a bit and I can't find any resources on this. Does anyone know how to <strong>build a vertical right-sided explorer bar</strong>?</p>
<p>I've just been digging into how <a href="http://www.kutano.com/" rel="nofollow">Kutano</a>'s right-side bar works as I'd like to do the same. This doesn't directly help your question as I don't have an answer yet, but here's what I know:</p> <p>Kutano doesn't appear to be a normal Explorer Bar, as there's no entry for it in <code>HKCR\Software\Microsoft\Internet Explorer\Explorer Bars</code>, nor does it appear in the <code>View|Explorer Bar</code> menu.</p> <p>The following entries in the registry referencing the Kutano sidebar DLL:</p> <pre><code>HKCR\AppID\{6D6036C6-692F-4211-903B-943D94E1CCC3} kutano_ie_client HKCR\CLSID\{18D81A5F-F8A5-4B78-A6CC-7E37DCAFC0BB} Kutano Add-on TypeLib {24DA2415-9F99-403F-801B-A74AE4101C27} HKCR\CLSID\{2AE98FD7-4E58-4400-8113-B5018ED48676} Kutano Sidebar TypeLib {24DA2415-9F99-403F-801B-A74AE4101C27} HKCR\CLSID\{2F698BD8-48CD-45B4-ACDF-67F92082EE7E} MenuItem TypeLib {24DA2415-9F99-403F-801B-A74AE4101C27} HKCR\CLSID\{A5B02961-E212-4195-A77D-6E1346C2DE18} kutanoSidebarExtInterface Class TypeLib {24DA2415-9F99-403F-801B-A74AE4101C27} HKCR\CLSID\{E163FD8B-2ADD-4F2E-86E8-7678D008ED43} KutanoToolbarBtn Class TypeLib {24DA2415-9F99-403F-801B-A74AE4101C27} HKCR\TypeLib\{24DA2415-9F99-403F-801B-A74AE4101C27} kutano_ie_client 1.0 Type Library HKLM\Software\Classes\AppID\kutano_ie_client.DLL AppID {6D6036C6-692F-4211-903B-943D94E1CCC3} </code></pre> <p>Some of these are more apparent as to what they do than others.</p> <p>Delving about with Spy++ it seems to add an extra Shell DocObject View to the window hierarchy:</p> <pre><code>TabWindowClass ATL:63CB39A0 Kutano_SplitterWindow AtlAxWin90 Shell Embedding Shell DocObject View Internet Explorer_Server </code></pre> <p>It does leave the original in place and appears to continue to use it:</p> <pre><code>TabWindowClass Shell DocObject View Internet Explorer_Server </code></pre> <p>This seems somewhat different and more involved than your HP example, but hope it might glean some information to the same end. I've a <a href="http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/367731dd-faf1-47f0-b538-693cdac1ab9f" rel="nofollow">thread</a> about this on the MSDN Internet Explorer Extension Development forum.</p>
In Batch: Read only the filename from a variable with path and filename <p>I am currently looking for a way to take a variable in batch and only parse out the filename.</p> <p>For example, I pass my batch file a -s parameter from another application which is subsequently set to my source variable. The source file variable typically contains something like: C:\Program Files\myapp\Instance.1\Data\filetomove.ext.</p> <p>I assume to read from the end of the variable until the first "\" and set the result to a new variable filename but I have not been able to use the "for /f" commmand successfully. </p> <p>Any help would be much appreciated!</p> <p>Update: Only standard XP or Windows 2000/2003 available...(can't assume resource kits installed).</p>
<p>If its coming in as an argument to the script, i.e. %1, %2, etc, you can extract just the filename and extension into a variable like this:</p> <pre><code>set FILENAME=%~nxN </code></pre> <p>where N is the index of the argument. For example, this script will echo just the filename of the first argument:</p> <pre><code>@echo off set FILENAME=%~nx1 echo %FILENAME% </code></pre>
In Workflow need to listen for multiple events <p>I need a workflow where need to listen for multiple events any event will drive workflow further.</p> <p>some actions --> Call external method --> Here there 3 events any one would be the response.</p> <p>What kind of activity i can use there where i can have three event handler. Any event will drive it further.</p> <p>Thought of using state machine workflow but if there is anything i can use instead?</p>
<p>Whether you use a sequential workflow or state machine workflow activity as your root workflow type, you can still handle events. The state machine is much better for handling events and swapping states as it pretty much forces you to do both. In my opinion, it is much more powerful than sequential workflows and provide all of the same functionality plus some. Personally, I have no reason to ever use a sequential workflow again.</p> <p>However, sequential workflows do have one great pro to them. They are SIMPLE. It doesn't get much easier to understand than a top-to-bottom workflow, and is great if you are actually making the designer available to your end users. In a sequential workflow, you can listen for events the same way using the ListenActivity. Drop the ListenActivity out, right click and add as many different forks as you will need, one per event you want to listen for. Finally, drop and configure the HandleEventActivity in each one, assigning them to the events you are wanting to subscribe.</p> <p><a href="http://blogs.microsoft.co.il/blogs/bursteg/archive/2006/07/13/Event-Driven-Activities.aspx" rel="nofollow" title="Event Driven Activities in your Workflow">Listening for Events in a Sequential Workflow</a></p> <p><a href="http://www.odetocode.com/Articles/460.aspx" rel="nofollow" title="State Machines In Windows Workflow">Listening for Events in a State Machine Workflow</a></p>
What are the differences between LLVM and java bytecode? <p>I dont understand the difference between LLVM and the java (bytecode), what are they?</p> <p>-edit- by 'what are they' i mean the differences between LLVM and java (bytecode) not what are LLVM and java.</p>
<p>Assuming you mean JVM rather than Java:</p> <p>The LLVM is a <em>low level</em> register-based virtual machine. It is designed to abstract the underlying hardware and draw a clean line between a compiler back-end (machine code generation) and front-end (parsing, etc.).</p> <p>The JVM is a much higher level stack-based virtual machine. The JVM provides garbage collection, has the notion of objects and virtual method calls and more. Thus, the JVM provides much higher level infrastructure for language interoperability (much like Microsoft's CLR).</p> <p>(It is possible to build these abstractions over LLVM just as it is possible to build them on top of C.)</p>
PostgreSQL Authentication Under XP <p>I'm using Windows XP and I've installed PostgreSQL 8.3.5-2. I can create databases via pgAdmin but not from Powershell. When I try, I get the following error:</p> <pre>createdb: could not connect to database postgres: FATAL: password authentication failed for user "gvkv"</pre> <p>where postgres is the server's only user account and "gvkv" is the account I work under. I've tried creating a separate account just for the the server and installing under that account but the installer keeps crashing.</p> <p>More fundamentally, I want to create some Powershell scripts to automate various tasks of database creation and administration but at this point, I can't even create a data store!</p>
<p>I think this is because you're connecting via the IP of the computer and not localhost. Most databases make a difference between connections to the local IP address (even if this is from a local application) and localhost: the first is an external connection and has to be enabled and the second is a local connection and is allowed. </p> <p>So try to connect to localhost instead and see if that works. </p>
Does the number of projects in a Visual Studio 9 solution impact the solution load and build times? <p>I'm specifically interested in solution load times &amp; build times - does fewer solutions mean better performance?</p> <p>Note that I'm <em>not</em> referring to the performance of the built application.</p> <p>Are load times and build times more efficient when working with a smaller number of projects?</p> <p>As a guide, we have 50-60 projects in our Visual Studio solution.</p>
<blockquote> <p>(I'm specifically interested in solution load times &amp; build times - does fewer solutions mean better performance?)</p> </blockquote> <p><a href="http://codebetter.com/blogs/patricksmacchia/archive/2008/12/08/advices-on-partitioning-code-through-net-assemblies.aspx">Here is</a> related topic by Patrick Smacchia describing benefits of having small number of assemblies (thereafter small number of projects). He talks exactly about how number of assemblies can affect build time and other factors.</p> <p>I encourage you to read Patrick blog. He has a lot of articles about code componentization.</p> <p><a href="http://codebetter.com/blogs/patricksmacchia/archive/2008/12/08/advices-on-partitioning-code-through-net-assemblies.aspx">Advices on partitioning code through .NET assemblies</a> </p> <p><a href="http://codebetter.com/blogs/patricksmacchia/archive/2009/01/11/lessons-learned-from-the-nunit-code-base.aspx">Lessons learned from the NUnit code base</a></p> <p><a href="http://codebetter.com/blogs/patricksmacchia/archive/2007/12/16/hints-on-how-to-componentize-existing-code.aspx">Hints on how to componentized existing code.</a></p> <p>From my personal experience it's a pain to have a solution with a few dozens of projects. IMO having more than 10 projects will lead to noticeable maintenance problems and affect your productivity.</p>
How do I disallow clicking on a link while an ajax request is in progress? <p>I have "a" element which servers as button. It has no href attribute.</p> <p>I'm using jQuery to achieve very simple thing: on click start ajax request and prevent further clicks. After ajax completes, enable clicking. I don't use form or input button.</p> <pre><code>var contact= { send: function() { $.ajax({ type: "POST", url: "ws/ContactService.asmx/SendEmail", data: '{"fromEmail":"' + $("#email").val() + '", "fromName":"' + $('#name').val() + '", "subject":"' + $('#subject').val() + '", "message":"' + $('#message').val() + '"}', contentType: "application/json; charset=utf-8", dataType: "json", error: function() { alert("Error"); }, success: function(msg) { alert(msg.d); }, complete: function() { $("#send").text("Send"); } }); } }; $(document).ready(function() { $("#send").("click", function() { $("#send").text("Sending..."); contact.send(); }); } ); </code></pre> <p>This works fine, except that I can click on send as many times as I want and every click will produce new ajax request. How to prevent clicks on "a" element while ajax request is in progress?</p>
<p>You could use something like this:</p> <pre><code>var contact = { inprogress: false, send: function() { if (contact.inprogress) return; contact.inprogress = true; $.ajax({ ... complete: function() { $("#send").text("Send"); contact.inprogress = false; } }); } }; </code></pre>
protecting adobe air apps <p>I am about to deliver an Adobe AIR app to a customer. But it's my first delivery of any sort, I.e. I have no experience whatsoever with licensing etc.</p> <p>Users of this app may or may not be online, so can't count on that. In fact it's 99% sure that they will be offline.</p> <p>Nor do I expect them to very tech-savvy, who will spend enough time scouting for ways to "crack" it.</p> <p>So, is there an okeish type of way to protect this app. That is, I don't want people to simply copy the installation folder, take it to another machine and run it. It should be slightly harder than this.</p> <p>Oh, and I am also using PHP and MySql, with which this AIR app communicates. So anything you guys could help me with is very very welcome.</p>
<p>protect the php api and not the frontend app. have a license key which is bound to an ip address and authenticate the request (which contains the key) is coming from the correct ip.</p>
Restricting T to string and int? <p>I have built myself a generic collection class which is defined like this. </p> <pre><code>public class StatisticItemHits&lt;T&gt;{...} </code></pre> <p>This class can be used with <code>int</code> and <code>string</code> values only. However this</p> <pre><code>public class StatisticItemHits&lt;T&gt; where T : string, int {...} </code></pre> <p>won't compile. What am I doing wrong?</p>
<p>The type restriction is meant to be used with Interfaces. Your sample suggests that you want to allow classes that <strong>inherit from int and string</strong>, which is kinda nonsense. I suggest you design an interface that contains the methods you'll be using in your generic class StatisticItemHits, and use that interface as restriction. However I don't really see your requirements here, maybe you could post some more details about your scenario?</p>
Which editor would you give your mom to let her edit her own website? <p>I mean this quite literally. A close relative wants to create her own website for her business and asked me for help. I've offered her to set up the website, take care of domain registration and all, but I don't have the time to design the website for her. So, I want to give her a software in which she can edit the page and publish it on her own.</p> <p>My feature-wish-list. The software should</p> <ul> <li>of course, be easy-to-use, as she's not a pro at the computer</li> <li>be able to publish the website, once the ftp-connection has been entered</li> <li>have some predefined themes, but also the possibilites to define a custom theme</li> <li>offer a german UI, since she doesn't understand english</li> </ul> <p>I so far looked at Nvu (too complicated), zeta Producer (crashed even before I could start editing the first page), CityDesk (very promising, but still too complicated and not in german). I'm quite happy with <a href="http://namu6.com">Namu6</a>, but unfortunately, it is english only.</p> <p>I'd be happy for any suggestion.</p> <p>[edit]</p> <p>Some were asking for a platform: She is only using windows, so Mac or Linux is not an option.</p>
<p>My mom uses vi for this</p>
Eclipse editor plugin: "ERROR" when opening file outside project <p>I'm developing an editor plugin for eclipse. It works fine on files within eclipse projects, but when an external file is opened via the "File -> Open File" menu (which works file with, e.g. Java files), I get a page displaying nothing but a horizontal blue line and the word "ERROR". The Error Log of eclipse is empty, as is the log file in the .metadata directory. </p> <p>What could cause this? How can I diagnose the error when I have no error message that tells me where to look? There doesn't seem to be a way to get more detailed logging from eclipse.</p> <p><strong>Edit:</strong></p> <p>I've found that the source of the problem is close to what jamesh mentioned, but not a ClassCastException - there simply is no <code>IDocument</code> instance for the text viewer to display because <code>StorageDocumentProvider.createDocument()</code> returns null. The reason for this is that it only knows how to create documents for instances of <code>org.eclipse.ui.IStorageEditorInput</code>, but in this case it gets an instance of <code>org.eclipse.ui.ide.FileStoreEditorInput</code>, which does not implement that interface, but instead implements <code>org.eclipse.ui.IURIEditorInput</code></p>
<p>I had the same probleam and finally found solution working for me. You have to provide 2 different document providers - first extending <strong>FileDocumentProvider</strong> for files inside your workbench, and second extending <strong>TextFileDocumentProvider</strong> for other resources outside your workspace. Then you register the right provider acording to the input in your editors <strong>doSetInput</strong> method like this:</p> <pre><code>private IDocumentProvider createDocumentProvider(IEditorInput input) { if(input instanceof IFileEditorInput){ return new XMLTextDocumentProvider(); } else if(input instanceof IStorageEditorInput){ return new XMLFileDocumentProvider(); } else { return new XMLTextDocumentProvider(); } } @Override protected final void doSetInput(IEditorInput input) throws CoreException { setDocumentProvider(createDocumentProvider(input)); super.doSetInput(input); } </code></pre> <p>then in your new document provider (extending TextFileDocumentProvider) insert somethnig like this:</p> <pre><code>protected FileInfo createFileInfo(Object element) throws CoreException { FileInfo info = super.createFileInfo(element); if(info==null){ info = createEmptyFileInfo(); } IDocument document = info.fTextFileBuffer.getDocument(); if (document != null) { /* register your partitioner and other things here same way as in your fisrt document provider */ } return info; } </code></pre> <p>This works for me :) Finally I have to mention, that I'm not so clever and that I copied this solution from project Amateras (Opensource HTML editor plugin for eclipse)</p>
Sending a password to a Windows Service <p>What is the best way to send a password to a Windows Service? Our application needs a password in order to start. I don't care that services are "normally" supposed to run without user interaction. Its good enough for us that an operator can start the application and then log off.</p> <p>On a unix system, I would just echo the password over stdin but the service has no stdin.</p> <p>Currently, we use the DPAPI to just store the password using CryptProtectData. While this, works, it presents other problems that are beginning to become troublesome.</p> <p>I'm guessing that I'll need to use some form of IPC between the service and the application that is sending the password but I'm not sure which method is appropriate, if any.</p> <p>Thanks</p>
<p>Two main options:</p> <p>You could listen on a socket on startup and wait for the required password to be supplied (maybe embed an SSH server in there, so that the password cannot be snooped over the wire)</p> <p>My preferred option would be to read the password from a configuration file (that can be secured to the minimum readership) or registry setting (again, sufficiently secure such that only your service and administrators can read/change it)</p>
IE automation: How to determine when a user-initiated navigation is taking place / has taken place? <p>I have an Internet Explorer BHO (in c# .net) and want to identify either when a user initiates a navigation, or when a user-initiated navigation has completed. By user-initiated I mean clicking on a link or similar action. In particular if there are multiple frames in the document being loaded I want to treat them as a single 'navigation', but I can't think of any easy way to do this. I know the BeforeNavigate2 and DocumentComplete events, but can't see any way to differentiate between BeforeNavigate/DocumentComplete firing when a user has clicked on a link and it firing because a frame is loading.</p> <p>One possible solution I'm thinking is that the BeforeNavigate2 for the top frame always gets fired before that of the inner frames (obviously), and then the DocumentComplete of the child frames get called before the DocumentComplete of the top, which is always called last. So for instance I could increment a counter in BeforeNavigates and decrement it in DocumentComplete, and only when it's 0 is it a user-initiated navigation.</p> <p>But I'm not sure if I can rely on this or if there's a better way to do it. e.g. What happens if the user presses ESC after one of the frames but not all have finished loading: does the DocumentComplete of the top frame ever get called?</p> <p>Any suggestions?</p>
<p>You can test whether <em>BeforeNavigate/NavigateComplete/DocumentComplete</em> event came from ineere frame or the topmost one simple by testing <em>pDispParams</em> agruments against pointer to browser object you have stored in <em>SetSite</em> method of your BHO.</p> <p>Here's C++ code to do this, I hope you can convert it easily to C#:</p> <pre><code>STDMETHODIMP MyBHO::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pDispParams, VARIANT* pvarResult, EXCEPINFO* pExcepInfo, UINT* puArgErr) { if( dispidMember != DISPID_BEFORENAVIGATE2 &amp;&amp; dispidMember != DISPID_NAVIGATECOMPLETE2 &amp;&amp; dispidMember != DISPID_DOCUMENTCOMPLETE ) return S_OK; CComQIPtr&lt;IWebBrowser2, &amp;IID_IWebBrowser2&gt; frame = pDispParams-&gt;rgvarg[ 1 ].pdispVal; if( webBrowser2 != frame ) return S_OK; } </code></pre> <p><em>webBrowser2</em> is pointer to browser object that you got in <em>SetSite</em> method,</p>
How does firefox know when an update is available for an extension (plugin) <p>I am in the process of creating my first firefox extension and am starting to think about deployment.</p> <p>There is a nice discussion about creating an template <a href="http://stackoverflow.com/questions/274639/how-to-create-a-quick-minimal-firefox-extension">here</a> and signing the extension <a href="http://stackoverflow.com/questions/129920/how-do-you-sign-your-firefox-extensions">here</a></p> <p>But later down the road ... how does firefox know that an extension has been updated?</p>
<p>From <a href="https://developer.mozilla.org/en/Extension_Versioning%2c_Update_and_Compatibility#Automatic_Add-on_Update_Checking" rel="nofollow">developer.mozilla.org</a> :</p> <blockquote> <p>Applications will periodically check for updates to installed add-ons by retrieving the updateURL. The information returned can be used to notify the user of an updated version to the add-on as well as inform the application of new application versions that the add-on is compatible with.</p> </blockquote> <p>More details about <a href="https://developer.mozilla.org/en/Install.rdf#updateURL" rel="nofollow">updateURL</a>.</p>
Can I have a hit-point in VisualStudio that skips lines? <p>I often run into the situation where I want to disable some code while debugging without actually changing the code.</p> <p>What I end up doing is having a break-point (usually conditional) and then when the break-point fires I perform a <em>Set Next Statement</em>. This can be very labor intensive when the code is reached many times so I created a macro:</p> <pre><code>Sub Skip3Lines() DTE.ActiveDocument.Selection.LineDown(False, 3) DTE.Debugger.SetNextStatement() End Sub </code></pre> <p>I then changed my break-point to be a hit-point (<code>right-click -&gt; When Hit...</code>) and told it to execute this macro.</p> <p>Visual studio was all too happy to spit out the following dialog box:</p> <blockquote> <p><code>---------------------------</code><br /> <code>Error</code><br /> <code>---------------------------</code><br /> <code>A macro called a debugger action which is not allowed while responding to an event or while being run because a breakpoint was hit.</code><br /> <code>---------------------------</code><br /> <code>OK </code><br /> <code>---------------------------</code> </p> </blockquote> <p>Does anyone know how to get around this?</p>
<p>DTE.ExecuteCommand("Debug.SetNextStatement")</p>
Detecting WAN radio power off <p>Like most laptops, mine (a Dell Inspiron 1420) has a small button which can be used to turn the wifi card on and off. Is there any way to detect that the radio has been turned off in a Win32 C program or service? I'm looking for a better way than to get the list of the visible access points, something that only depends on the state of that button.</p> <p><em>Update</em> - the solution is monitoring hardware events with a Windows service. You can get some code that does that <a href="http://www.codeproject.com/KB/system/Windows_Services.aspx" rel="nofollow">here</a>.</p> <p><em>Update 2</em> - after more research it seems that the hardware events are sent for the Bluetooth device that is disabled when you hit the radio off switch. So, hardware monitoring works only for laptops that have both internal Bluetooth and wifi (probably on the same card). I never found a definite solution to this problem and have to live with the Bluetooth-based heuristic.</p>
<p>I think it just disables the card in Windows - would this be different than detecting if there's a WLAN card in the the device manager that's currently disabled?</p> <p>I'm a VB programmer, so I can't help with the specifics, but just wanted to give somewhere to start.</p>
Programming Problem - Fax Compression <p>I'm preparing to go to a computer science contest by completing problems from past contests. Most of them are pretty easy, but this one is bugging me...it seems simple but I'm just not being able to do it.</p> <p>If you have a string of ones and zeros:</p> <pre><code>100111010001111100101010 </code></pre> <p>What would be the code to take that as an input and then output this:</p> <pre><code>1:1 2:0 3:1 1:0 1:1 3:0 5:1 2:0 1:1 1:0 1:1 1:0 </code></pre> <p>Where the digit to the left of each colon is the number of times the digit after the colon appears.</p> <p>So, another example...inputting:</p> <pre><code>1100011 </code></pre> <p>Would output:</p> <pre><code>2:1 3:0 2:1 </code></pre> <p>According to the problem this is similar to the algorithm used to compress fax transmissions. </p> <p>An answer in java would be best, but all I'm really looking for is pseudocode or even thoughts on how to do it. </p> <p>Thanks in advance.</p>
<p>This is called Run-Length-Encoding (RLE) and is used in a number of things (such as the Windows Bitmap file-format) to provide very basic compression (especially if the original includes lots of repeated values (like a bitmap or fax) containing a long run of the same colour).</p> <pre><code>int[] array = { ........ }; // your values... for ( int i=0; i &lt; array.Length; i++ ) { int count = 1; int value = array[i]; // Consume until different.. while ( i+1 &lt; array.Length &amp;&amp; array[i] == array[i+1] ) { count++; i++ } Console.WriteLine("{0}:{1}", count, value); } // OR, as suggested by @jon [done in my head, so could probably be improved a lot...] int count = 0; int oldValue = -1; for ( int i=0; i&lt;array.Length; i++ ) { int newValue = array[i]; count = ( newValue != oldValue ) ? 1 : count+1; if ( i+1 &gt;= array.Length || array[i+1] != newValue) { Console.WriteLine("{0}:{1}", count, newValue); } oldValue = newValue; } </code></pre>
JSON datetime between Python and JavaScript <p>I want to send a datetime.datetime object in serialized form from Python using <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> and de-serialize in JavaScript using JSON. What is the best way to do this?</p>
<p>You can add the 'default' parameter to json.dumps to handle this:</p> <pre><code>date_handler = lambda obj: ( obj.isoformat() if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date) else None ) json.dumps(datetime.datetime.now(), default=date_handler) '"2010-04-20T20:08:21.634121"' </code></pre> <p>Which is <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> format. </p> <p>A more comprehensive default handler function:</p> <pre><code>def handler(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() elif isinstance(obj, ...): return ... else: raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj)) </code></pre> <p>Update: Added output of type as well as value.<br> Update: Also handle date </p>
Is it possible to run ASP.NET MVC routes in different AppDomains? <p>I am having problems with thinking up a solution for the following. I got a blog which I recently upgraded from web forms to MVC. The blog is avalible in both swedish and english on two different domains and are running in the same web site in IIS.</p> <p>The problem is that I would like language specific urls on the both sites, like this:</p> <p>English: <a href="http://codeodyssey.com/archive/2009/1/15/code-odyssey-the-next-chapter" rel="nofollow">http://codeodyssey.com/archive/2009/1/15/code-odyssey-the-next-chapter</a></p> <p>Swedish: <a href="http://codeodyssey.se/arkiv/2009/1/15/code-odyssey-nasta-kapitel" rel="nofollow">http://codeodyssey.se/arkiv/2009/1/15/code-odyssey-nasta-kapitel</a></p> <p>At the moment I have made this to work by registering the RouteTable on each request depending on which domain is called. My Global.asax Looks something like this (not the whole code):</p> <pre><code>public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); string archiveRoute = "archive"; if (Thread.CurrentThread.CurrentUICulture.ToString() == "sv-SE") { archiveRoute = "arkiv"; } routes.MapRoute( "BlogPost", archiveRoute+"/{year}/{month}/{day}/{slug}", new { controller = "Blog", action = "ArchiveBySlug" } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); routes.MapRoute( "404-PageNotFound", "{*url}", new { controller = "Error", action = "ResourceNotFound" } ); } void Application_BeginRequest(object sender, EventArgs e) { //Check whcih domian the request is made for, and store the Culture string currentCulture = HttpContext.Current.Request.Url.ToString().IndexOf("codeodyssey.se") != -1 ? "sv-SE" : "en-GB"; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(currentCulture); Thread.CurrentThread.CurrentUICulture = new CultureInfo(currentCulture); RouteTable.Routes.Clear(); RegisterRoutes(RouteTable.Routes); Bootstrapper.ConfigureStructureMap(); ControllerBuilder.Current.SetControllerFactory( new CodeOdyssey.Web.Controllers.StructureMapControllerFactory() ); } protected void Application_Start() { } </code></pre> <p>This works at the moment but I know it not a great solution. I have been getting a "Item has already been added. Key in dictionary" error when stating up this app and it does not seems stable at times.</p> <p>I would like to only set up my routes in the Application_Start as they should and not having to clear them on every request like I am doing now. Problem is that the request object does not exist and I have no way of knowing which of the language specific routes I should register.</p> <p>Been reading about the AppDomain but could not find many examples on how to use it on a web site. I'we been thinking to star something like this:</p> <pre><code>protected void Application_Start() { AppDomain.CreateDomain("codeodyssey.se"); AppDomain.CreateDomain("codeodyssey.com"); } </code></pre> <p>Then registring each web sites routes in each app domain and send the requests to one of them based on the url. Can't find any examples on how to work with AppDomains in this manner.</p> <p>Am I completely off track? Or is there a better solution for this?</p>
<p>The ASP.Net runtime manages AppDomains for you, so its probably not a good idea to create AppDomains in your code.</p> <p>However, if you can, I would suggest creating multiple IIS Applications (one for <a href="http://codeodyssey.com" rel="nofollow">http://codeodyssey.com</a> and one for <a href="http://codeodyssey.se" rel="nofollow">http://codeodyssey.se</a>). Point both applications at the same directory on disk. This will give you the two AppDomains you are looking for.</p> <p>Then, in your Application_Start code, you can check the domain and build routes accordingly.</p>
What is the best method to merge two PHP objects? <p>We have two PHP5 objects and would like to merge the content of one into the second. There are no notion of subclasses between them so the solutions described in the following topic cannot apply.</p> <p><a href="http://stackoverflow.com/questions/119281/how-do-you-copy-a-php-object-into-a-different-object-type">How do you copy a PHP object into a different object type</a></p> <pre><code>//We have this: $objectA-&gt;a; $objectA-&gt;b; $objectB-&gt;c; $objectB-&gt;d; //We want the easiest way to get: $objectC-&gt;a; $objectC-&gt;b; $objectC-&gt;c; $objectC-&gt;d; </code></pre> <p><strong>Remarks:</strong></p> <ul> <li>These are objects, not classes.</li> <li>The objects contain quite a lot of fields so a <strong>foreach</strong> would be quite slow.</li> <li>So far we consider transforming objects A and B into arrays then merging them using <strong>array_merge()</strong> before re-transforming into an object but we can't say we are proud if this.</li> </ul>
<blockquote> <p>If your objects only contain fields (no methods), this works:</p> </blockquote> <pre><code>$obj_merged = (object) array_merge((array) $obj1, (array) $obj2); </code></pre> <p>This actually also works when objects have methods. (tested with PHP 5.3 and 5.6)</p>
Fast read/write from file in delphi <p>I am loading a file into a array in binary form this seems to take a while is there a better faster more efficent way to do this. i am using a similar method for writing back to the file.</p> <pre><code>procedure openfile(fname:string); var myfile: file; filesizevalue,i:integer; begin assignfile(myfile,fname); filesizevalue:=GetFileSize(fname); //my method SetLength(dataarray, filesizevalue); i:=0; Reset(myFile, 1); while not Eof(myFile) do begin BlockRead(myfile,dataarray[i], 1); i:=i+1; end; CloseFile(myfile); end; </code></pre>
<p>If your really want to read a binary file fast, let windows worry about buffering ;-) by using <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dngenlib/html/msdn_manamemo.asp">Memory Mapped Files</a>. Using this you can simple map a file to a memory location an read like it's an array.</p> <p>Your function would become:</p> <pre><code>procedure openfile(fname:string); var InputFile: TMappedFile; begin InputFile := TMappedFile.Create; try InputFile.MapFile(fname); SetLength(dataarray, InputFile.Size); Move(PByteArray(InputFile.Content)[0], Result[0], InputFile.Size); finally InputFile.Free; end; end; </code></pre> <p>But I would suggest not using the global variable <code>dataarray</code>, but either pass it as a var in the parameter, or use a function which returns the resulting array.</p> <pre><code>procedure ReadBytesFromFile(const AFileName : String; var ADestination : TByteArray); var InputFile : TMappedFile; begin InputFile := TMappedFile.Create; try InputFile.MapFile(AFileName); SetLength(ADestination, InputFile.Size); Move(PByteArray(InputFile.Content)[0], ADestination[0], InputFile.Size); finally InputFile.Free; end; end; </code></pre> <p>The TMappedFile is from my article <a href="http://landman-code.blogspot.com/2006/04/it-has-been-six-months-since-i-last.html">Fast reading of files using Memory Mapping</a>, this article also contains an example of how to use it for more "advanced" binary files.</p>
Does PHP feature short hand syntax for objects? <p>In javascript you can easily create objects and Arrays like so:</p> <pre><code>var aObject = { foo:'bla', bar:2 }; var anArray = ['foo', 'bar', 2]; </code></pre> <p>Are simialar things possible in PHP?<br /> I know that you can easily create an array using the array function, that hardly is more work then the javascript syntax, but is there a similar syntax for creating objects? Or should I just use associative arrays?</p> <pre><code>$anArray = array('foo', 'bar', 2); $anObjectLikeAssociativeArray = array('foo'=&gt;'bla', 'bar'=&gt;2); </code></pre> <p>So to summarize:<br /> Does PHP have javascript like object creation or should I just use associative arrays?</p>
<p>For simple objects, you can use the associative array syntax and casting to get an object:</p> <pre><code>&lt;?php $obj = (object)array('foo' =&gt; 'bar'); echo $obj-&gt;foo; // yields "bar" </code></pre> <p>But looking at that you can easily see how useless it is (you would just leave it as an associative array if your structure was that simple).</p>
Android : Getting file name from camera? <p>I have run into a small issue with something that I am probably just overlooking.</p> <p>I want to take a picture from the surface preview of the camera, and save it to the sd_card. This works ALMOST perfectly. I assign it a file name, and for one reason or another, it does not use the filename. </p> <p>This is what I have been trying to do :</p> <pre><code> Button imagecapture = (Button)findViewById(R.id.imagecapture); imagecapture.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String filename = null; ImageCaptureCallback iccb = null; try { filename = timeStampFormat.format(new Date()); ContentValues values = new ContentValues(); values.put(Media.TITLE, filename); values.put(Media.DESCRIPTION, "Image capture by camera"); Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values); iccb = new ImageCaptureCallback( getContentResolver().openOutputStream(uri)); } catch(Exception ex ){ ex.printStackTrace(); Log.e(getClass().getSimpleName(), ex.getMessage(), ex); } camera.takePicture(mShutterCallback, mPictureCallbackRaw, iccb); com.froogloid.android.gspot.Park.imageFileName = filename; } }); </code></pre> <p>It won't use the filename (i.e. time/date stamp I ask it to.)</p>
<p>This was resolved by implementing PictureCallback via a ImageCaptureCallback class, and Overriding the onPictureTaken where the file was being written via a file output stream. All you had to do was change the fileoutput stream to the filename you want.</p>
How to determine using reflection the generic parameter of the base class <p>I have the following structure</p> <pre><code>public class MyClass : MyBaseClass&lt;System.Int32&gt; { } </code></pre> <p>In a static method and without instantiating a new MyClass instance how do I get the type of the generic parameter used to build the concrete base class? e.g in the above example System.Int32</p>
<p>Try this</p> <pre><code>public static Type GetBaseTypeGenericArgument(Type type) { return type.BaseType.GetGenericArguments()[0]; } ... GetBaseTypeGenericArgument(typeof(MyClass)); </code></pre>
What is the function __construct used for? <p>I have been noticing <code>__construct</code> a lot with classes. I did a little reading and surfing the web, but I couldn't find an explanation I could understand. I am just beginning with OOP.</p> <p>I was wondering if someone could give me a general idea of what it is, and then a simple example of how it is used with PHP?</p>
<p>The "__construct" was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor). You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.</p> <p>An example could go like this:</p> <pre><code>class Database { protected $userName; protected $password; protected $dbName; public function __construct ( $UserName, $Password, $DbName ) { $this-&gt;userName = $UserName; $this-&gt;password = $Password; $this-&gt;dbName = $DbName; } } // and you would use this as: $db = new Database ( 'user_name', 'password', 'database_name' ); </code></pre> <p>Everything else is explained in the PHP manual: <a href="http://php.net/manual/en/language.oop5.decon.php">click here</a></p>
dynamic allocating array of arrays in C <p>I don't truly understand some basic things in C like dynamically allocating array of arrays. I know you can do:</p> <pre><code>int **m; </code></pre> <p>in order to declare a 2 dimensional array (which subsequently would be allocated using some *alloc function). Also it can be "easily" accessed by doing <code>*(*(m + line) + column)</code>. But how should I assign a value to an element from that array? Using gcc the following statement <code>m[line][column] = 12;</code> fails with a segmentation fault.</p> <p>Any article/docs will be appreciated. :-)</p>
<p>The <code>m[line][column] = 12</code> syntax is ok (provided <code>line</code> and <code>column</code> are in range).</p> <p>However, you didn't write the code you use to allocate it, so it's hard to get whether it is wrong or right. It should be something along the lines of</p> <pre><code>m = (int**)malloc(nlines * sizeof(int*)); for(i = 0; i &lt; nlines; i++) m[i] = (int*)malloc(ncolumns * sizeof(int)); </code></pre> <p>Some side-notes:</p> <ul> <li>This way, you can allocate each line with a different length (eg. a triangular array)</li> <li>You can realloc() or free() an individual line later while using the array</li> <li>You must free() every line, when you free() the entire array</li> </ul>
C# App.Config location <p>I have a solution with 10 or so projects in it, and have started having issues with SystemConfiguration returning empty configuration instead of locating my App.Config file.</p> <p>Should I have multiple App.Configs, one for each project (I am assuming and hoping not), if not, where is the best place for it to be located in my projects?</p>
<p>Choose one of the projects as the one responsible for maintaining the App.config file. Then for the other projects, use "Add existing item" , navigate to the App.config file and click on the "Add as a link" (it is the right side of the Add button).</p>
Usage history of Stored Procedures in SQL Server 2008 <p>I work with legacy systems that have tens of thousand of lines of stored procedure code, where many of the stored procedures are obsolete and not used anymore. There doesn't seem to be a way to check execution history, so my question is if it might be a good idea to start each stored procedure by inserting a row into a table that keeps records of the execution?</p> <p>could be very simple like:</p> <p>insert into executionHistory ( name, date ) select 'spName', getdate()</p> <p>-- then rest of procedure</p> <p>I imagine this could be very useful for doing cleanups of old unused code, and might also be handy when trying to decide where to optimize. I mean it's better to shave 10 seconds off execution time on a procedure that is executed 50 times a day, than saving 10 minutes execution time on a procedure that is only used once a year.</p>
<p>There is a tracing option (SQL Profiler) in SQL server. you could take a trace of a days SQL activity and see which sprocs are executed there. </p> <p>This will give you a good idea of where to focus your optimisations.</p>
SCons problem - dont understand Variables class <p>I'm working on an SConstruct build file for a project and I'm trying to update from Options to Variables, since Options is being deprecated. I don't understand how to use Variables though. I have 0 python experience which is probably contributing to this.</p> <p>For example, I have this:</p> <pre><code>opts = Variables() opts.Add('fcgi',0) print opts['fcgi'] </code></pre> <p>But I get an error:</p> <pre><code>AttributeError: Variables instance has no attribute '__getitem__': </code></pre> <p>Not sure how this is supposed to work</p>
<p>Typically you would store the variables in your environment for later testing.</p> <pre><code>opts = Variables() opts.Add('fcgi',0) env = Environment(variables=opts, ...) </code></pre> <p>Then later you can test:</p> <pre><code>if env['fcgi'] == 0: # do something </code></pre>
Does asp.net remove <script> tags in repeaters and inside the <% for loop %> in mvc <p>I have some <code>&lt;script type="javascript"/script</code> tags inside both a repeater and a for loop in mvc. </p> <p>On page render the script is gone and is not displayed both inside the repeater and the for loop (they are separate). </p> <p>Is there some option I need to set to stop this from happening? Has anyone had this happen to them?</p>
<p>Based on url: <a href="http://stackoverflow.com/questions/455912/script-script-inside-a-repeater-control-code-not-showing-up-in-the-source-code">http://stackoverflow.com/questions/455912/script-script-inside-a-repeater-control-code-not-showing-up-in-the-source-code</a> you are injecting the javascript into the repeater using the code behind.</p> <p>For testing purposes, can you try placing your script tags within the ItemTemplate?</p> <p>My second suggestion would be to pass the values required to construct the javascript as part of your datasource and then output them as part of your template:</p> <pre><code>&lt;script type="text/javascript"&gt; AudioPlayer.embed('&lt;%#DataBinder.Eval(Container.DataItem, "ID")%&gt;', {soundFile: '&lt;%#DataBinder.Eval(Container.DataItem, "Url")%&gt;'}); &lt;/script&gt; </code></pre> <p>Regards</p> <p>Gavin</p>
Are there compelling reasons not to use Groovy? <p>I'm developing a LoB application in Java after a long absence from the platform (having spent the last 8 years or so entrenched in Fortran, C, a smidgin of C++ and latterly .Net).</p> <p>Java, the language, is not much changed from how I remember it. I like it's strengths and I can work around its weaknesses - the platform has grown and deciding upon the myriad of different frameworks which appear to do much the same thing as one another is a different story; but that can wait for another day - all-in-all I'm comfortable with Java. However, over the last couple of weeks I've become enamoured with Groovy, and purely from a selfish point of view: but not just because it makes development against the JVM a more succinct and entertaining (and, well, "groovy") proposition than Java (the language).</p> <p>What strikes me most about Groovy is its inherent maintainability. We all (I hope!) strive to write well documented, easy to understand code. However, sometimes the languages we use themselves defeat us. An example: in 2001 I wrote a library in C to translate EDIFACT EDI messages into ANSI X12 messages. This is not a particularly complicated process, if slightly involved, and I thought at the time I had documented the code properly - and I probably had - but some six years later when I revisited the project (and after becoming acclimatised to C#) I found myself lost in so much C boilerplate (mallocs, pointers, etc. etc.) that it took three days of thoughtful analysis before I finally understood what I'd been doing six years previously.</p> <p>This evening I've written about 2000 lines of Java (it is the day of rest, after all!). I've documented as best as I know how, but, but, of those 2000 lines of Java a significant proportion is Java boiler plate.</p> <p>This is where I see Groovy and other dynamic languages winning through - maintainability and later comprehension. Groovy lets you concentrate on your intent without getting bogged down on the platform specific implementation; it's almost, but not quite, self documenting. I see this as being a huge boon to me when I revisit my current project (which I'll port to Groovy asap) in several years time and to my successors who will inherit it and carry on the good work.</p> <p>So, are there any reasons not to use Groovy? </p>
<p>There are two reasons I can think of not to use Groovy (or Jython, or JRuby):</p> <ul> <li>If you really, truly need performance</li> <li>If you will miss static type checking</li> </ul> <p>Those are both big ifs. Performance is probably less of a factor in most apps than people think, and static type checking is a religious issue. That said, one strength of all of these languages is their ability to mix and match with native Java code. Best of both worlds and all that.</p> <p>Since I'm not responsible for your business, I say "Go for it".</p>
Debugging ASP.NET Session State server issues <p>We have an application that runs over load balanced server instances, and therefore is configured to use the ASP.NET session state service, which is running on one of our DB servers. While both instances of our app can successfully connect to the state server, changes in session state data are not being reflected across both of them. FI, If I call <code>Session.Add('SomeKey', SomeData)</code> on Server A, this is not being reflected if I then try to access <code>Session['SomeKey']</code> on Server B. </p> <p>Session.SessionID returns the same value on both servers, and I have checked that they are both using the same validationkey and decryptionkey values configured in the machinekey section of machine.config. I even tried specifying these values in the apps web.config.</p> <p>What other things should I be looking out for which may be causing these symptoms, and what steps can people recommend to help debug this issue?</p>
<p>Does this help:</p> <p><a href="http://support.microsoft.com/kb/325056">http://support.microsoft.com/kb/325056</a> ?</p> <blockquote> <p>To maintain session state across different Web servers in the Web farm, the application path of the Web site (for example, \LM\W3SVC\2) in the Microsoft Internet Information Services (IIS) metabase must be the same for all of the Web servers in the Web farm. The case also needs to be the same because the application path is case-sensitive.</p> </blockquote>
Recommended website resolution (width and height)? <p>Is there any standard on common website resolution?</p> <p>We are targeting newer monitors, perhaps at least 1280px wide, but the height may varies, and each browser may have different toolbar heights too.</p> <p>Is there any sort of standard to this?</p>
<p>The advice these days is:</p> <p><strong>Optimize for 1024x768</strong>. For most sites this will cover most visitors. Most logs show that 92-99% of your visits will be over 1024 wide. While 1280 is increasingly common, there are still lots at 1024 and some below that. Optimize for this but don't ignore the others.</p> <p><strong>1024 = ~960</strong>. Accounting for scrollbars, window edges, etc means <a href="http://mentalized.net/journal/2006/10/24/size_does_matter_actual_numbers/">the real width</a> of a 1024x768 screen is <a href="http://www.cameronmoll.com/archives/001220.html">about 960 pixels</a>. Some tools are based on a <strong>slightly smaller size, about 940</strong>. This is the default container width in <a href="http://twitter.github.com/bootstrap/">twitter bootstrap</a>.</p> <p><strong>Don't design for one size</strong>. Window sizes vary. Don't assume screen size equals windows size. Design for a reasonable minimum, but assume it will adjust.</p> <p><strong>Use responsive design and liquid layouts</strong>. Use layouts that will adjust when the window is resized. People do this a lot, especially on big monitors. This is just good CSS practice. There are several front-end frameworks that support this.</p> <p><strong>Treat mobile as a first-class citizen</strong>. You are getting more traffic from mobile devices all the time. These introduce even more screen sizes. You can still optimize for 960, but using responsive web design techniques means your page will adjust based on the screen size. </p> <p><strong>Log browser display info</strong>. You can get actual numbers about this. I found some numbers <a href="http://www.w3schools.com/browsers/browsers_display.asp">here</a> and <a href="http://www.boutell.com/newfaq/creating/resolution.html">here</a> and <a href="http://www.upsdell.com/BrowserNews/stat_trends.htm#res">here</a>. You can also rig your site to collect the same data.</p> <p><strong>User will scroll so don't worry much about height</strong>. The old argument was that users wouldn't scroll and anything important should be "above the fold." This was overturned years ago. <a href="http://www.useit.com/alertbox/scrolling-attention.html">Users scroll a lot</a>.</p> <p>More about screen resolutions:</p> <ul> <li><a href="http://www.useit.com/alertbox/screen_resolution.html">Screen Resolution and Page Layout</a></li> <li><a href="http://www.baekdal.com/reports/Actual-Browser-Sizes/actual-browser-sizes/">Actual browser sizes</a></li> <li><a href="http://www.hobo-web.co.uk/tips/25.htm">Best Screen Resolution to Design Websites</a></li> <li><a href="http://justaddwater.dk/2006/08/17/design-for-browser-size-not-screen-size/">Design for browser size - not screen size</a></li> </ul> <p>More about responsive design:</p> <ul> <li><a href="http://www.alistapart.com/articles/responsive-web-design/">Responsive Web Design</a> (2010, May 25), Ethan Marcotte, A List Apart.</li> <li><a href="http://en.wikipedia.org/wiki/Responsive_Web_Design|">Responsive Web Design</a> at Wikipedia</li> <li><a href="http://www.lukew.com/ff/entry.asp?1514">Multi-device layout patterns</a> (2012, Mar 14) Luke Wroblewski. Catalogs the most popular patterns for adaptable multi-device screen layouts.</li> </ul> <p>Tools and front-end frameworks for responsive design and liquid layouts:</p> <ul> <li><a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a></li> <li><a href="http://foundation.zurb.com/">Zurb Foundation</a></li> <li><a href="http://www.creativebloq.com/css3/tools-responsive-web-design-5132770">50 fantastic tools for responsive web design</a> (2012, April 24) Denise Jacobs &amp; Peter Gasston</li> </ul>
Destructors of builtin types (int, char etc..) <p>In C++ the following code gives a compiler error:</p> <pre><code>void destruct1 (int * item) { item-&gt;~int(); } </code></pre> <p>This code is nearly the same, I just typedef the int to another type and something magic happens:</p> <pre><code>typedef int myint; void destruct2 (myint * item) { item-&gt;~myint(); } </code></pre> <p>Why does the second code works? Does an int gets a destructor just because it has been typedefed?</p> <p>In case you wonder why one ever would like to do this: This comes from refactoring C++ code. We're removing the standard heap and replacing it with selfmade pools. This requires us to call placement-new and the destructors. I know that calling destructors for primitive types is useless, but we want them in the code nevertheless in case we later replace PODs with real classes.</p> <p>Finding out that naked int's don't work but typedefed ones do was quite a surprise.</p> <p>Btw - I have a solution that involves template-functions. We just typedef inside the template and everything is fine.</p>
<p>It's the reason that makes your code work for generic parameters. Consider a container C:</p> <pre><code>template&lt;typename T&gt; struct C { // ... ~C() { for(size_t i = 0; i&lt;elements; i++) buffer[i].~T(); } }; </code></pre> <p>It would be annoying to introduce special cases for built-in types. So C++ allows you to do the above, even if T happens to equal to <code>int</code>. The holy Standard says in <code>12.4 p15</code>:</p> <blockquote> <p>The notation for explicit call of a destructor can be used for any scalar type name. Allowing this makes it possible to write code without having to know if a destructor exists for a given type. </p> </blockquote> <p>The difference between using a plain int and a typedef'ed int is that they are syntactically different things. The rule is, that in a destructor call, the thing after the <code>~</code> is a type-name. <code>int</code> is not such a thing, but a typedef-name is. Look it up in <code>7.1.5.2</code>. </p>
Software visualization for C# <p>Does any of you know a tool for software visualization, or visual code navigation in c#?</p> <p>I found a bunch of tools but they're all for Java for some reason.</p> <p>There's a list of them in wikipedia but none is for the .Net platform.</p> <p><a href="http://en.wikipedia.org/wiki/Software_visualization#Tools" rel="nofollow">http://en.wikipedia.org/wiki/Software_visualization#Tools</a></p> <p>I'm very much interested in visual code navigation because I get very disoriented around big projects.</p>
<p><a href="http://www.red-gate.com/products/reflector/" rel="nofollow">Reflector</a> itself may not offer reasonable visualization of code. But there are addins that can enhance it with such functionality.</p> <p>Try the following addins on <a href="http://www.codeplex.com/reflectoraddins" rel="nofollow">this</a> page:</p> <ul> <li>Graph </li> <li>AutoDiagrammer </li> <li>SequenceViz</li> </ul>
Synchronize two databases schema in MySQL <p>I was looking for a portable script or command line program that can synchronize two MySQL databases schema. I am not looking for a GUI based solution because that can't be automated or run with the buid/deployment tool.</p> <p>Basically what it should do is scan database1 and database2. Check the schema difference (tables and indexes) and propose a bunch of SQL statements to run on one so that it gets the similiar structure of the other minimizing data damage as much as possible.</p> <p>If someone can indicate a PHP, Python or Ruby package where this type of solution is implemented, I can try to copy the code from there.</p> <p>A lot of MySQL GUI tools probably can do this, but I am looking for a scriptable solution.</p> <p>Edit: Sorry for not being more clear: What I am looking for is synchronization in table structure while keeping data intact as far as possible. Not data replication.</p> <p>More info:</p> <p>Why replication won't work.</p> <ol> <li>The installation bases are spread around the state.</li> <li>We want the installer to perform dynamic fixes on the DB based on chagnes made in the latest version, regardless of what older version the end user might be using.</li> <li>Changes are mostly like adding new column to a tables, creating new indexes, or dropping indexes, adding tables or dropping tables used by the system internally (we don't drop user data table).</li> </ol> <p>If it's a GUI: No it can't be used. We don't want to bunddle a 20MB app with our installer just for DB diff. Specially when the original installer is less than 1 MB.</p>
<p>Have you considered using <a href="http://dev.mysql.com/doc/refman/5.0/en/replication.html">MySQL replication</a> ?</p>
SQL Queries - How Slow is Too Slow? <p>Do you have any formal or informal standards for reasonably achievable SQL query speed? How do you enforce them? Assume a production OLTP database under full realistic production load of a couple dozen queries per second, properly equipped and configured.</p> <p>Personal example for illustrative purposes (not a recommendation, highly contingent on many factors, some outside your control):</p> <p>Expectation:</p> <p>Each transactional unit (single statement, multiple SQL statements from beginning to end transaction boundaries, or a single stored procedure, whichever is largest) must execute in 1 second or less on average, without anomalous outliers.</p> <p>Resolution:</p> <p>Slower queries must be optimized to standard. Slow queries for reports and other analysis are moved to an OLAP cube (best case) or a static snapshot database.</p> <p>(Obviously some execution queries (Insert/Update/Delete) can't be moved, so must be optimized, but so far in my experience it's been achievable.)</p>
<p>Given that you can't expect deterministic performance on a system that could (at least in theory) be subject to transient load spikes, you want your performance SLA to be probabilistic. An example of this might be:</p> <p>95% of transactions to complete within 2 seconds.<br> 95% of search queries (more appropriate for a search screen) to complete within 10 seconds.<br> 95% of operational reports to complete within 10 seconds.</p> <p>Transactional and search queries can't be moved off transactional system, so the only actions you can take are database or application tuning, or buying faster hardware. </p> <p>For operational reports, you need to be ruthless about what qualifies as an operational report. Only reports that <em>absolutely</em> need to have access to up-to-date data should be run off the live system. Reports that do a lot of I/O are very anti-social on a production system, and normalised schemas tend to be quite inefficient for reporting. Move any reports that do not require real-time data off onto a data warehouse or some other separate reporting facility.</p>
Migrate from Subversion to Team Foundation Server <p>We are looking for any proven migration path for moving a Subversion repository to a Team Foundation Server. Seems that there has been a discontinued product named CS-Converter(<a href="http://www.componentsoftware.com/Products/converter/svn2tfs.htm" rel="nofollow">ComponentSoftware homepage</a>) but can't find anybody having used it. </p> <p>Is CS-Converter a solid product, are there any other resources I haven't found or does anybody have some personal experience which can guide us?</p> <p>UPDATE: Just to clarify, we need to actually move the existing repository from Subversion to Team Foundation Server (orders from up high), so while SVNBridge is nice, it just does do the job. We need a proven, safe way to migrate the repository</p>
<p>Maybe <a href="http://social.msdn.microsoft.com/Forums/en-US/tfsversioncontrol/thread/dafc9550-1c17-40ae-ad0a-fc463b336507/" rel="nofollow">this discussion</a> is interesting for you.</p> <p>There's another software mentioned from <a href="http://www.kyrosoft.com" rel="nofollow">Krysoft</a> which has been tested and proved working well.</p>
How lean do my C++ exception classes really need to be? <p>There are lots of places where guidelines for designing exception classes can be found. Almost everywhere I look, there's this list of things exception objects should never do, which impacts the design of those classes.</p> <p>For instance, the <a href="http://www.boost.org/community/error_handling.html">Boost people recommend</a> that the class contain no <code>std::string</code> members, because their constructor could throw, which would cause the run-time to terminate the program immediately.</p> <p>Now, it seems to me that this is rather theoretical. If <code>std::string</code>'s constructor throws, it's either a bug (I passed a null-pointer in) or an out-of-memory condition (correct me if I'm wrong here). Since I'm on a desktop, I just pretend I have an infinite amount of memory, and <strong>running out of memory is fatal to my application no matter what</strong>.</p> <p>With that in mind, why shouldn't I embed <code>std::string</code> objects in my exception classes? In fact, why couldn't my exception classes be full-featured, and also take care of logging, stack tracing, etc. I'm aware of the one-responsibility principle, and it seems to me to be a fair trade-off to have the exception class do all that. Surely, if my parser needs to report a syntax error, an full-featured exception would be more helpful than an exception built around a statically allocated character array.</p> <p>So: lean C++ exception classes - how big a deal is it in the real-world? What are the trade-offs? Are there good discussions on the topic?</p>
<p>You could use the Boost.Exception library to help define your exception hierarchy. The Boost.Exception library supports the:</p> <blockquote> <p>transporting of arbitrary data to the catch site, which is otherwise tricky due to the no-throw requirements (15.5.1) for exception types.</p> </blockquote> <p>The limitations of the framework will provide you with reasonably defined design parameters.</p> <p><a href="http://www.boost.org/doc/libs/1_37_0/libs/exception/doc/boost-exception.html" rel="nofollow">Boost.Exception</a><br> See also: <a href="http://www.boost.org/doc/libs/1_37_0/libs/system/doc/index.html" rel="nofollow">Boost.System</a></p>
Condition evaluation in loops? <pre><code>string strLine;//not constant int index = 0; while(index &lt; strLine.length()){//strLine is not modified}; </code></pre> <p>how many times <code>strLine.length()</code> is evaluated</p> <p>do we need to put use <code>nLength</code> with <code>nLength</code> assigned to <code>strLine.length()</code> just before loop </p>
<p><code>length</code> will be evaluated every time you go via the loop, however since <code>length</code> is constant time (<code>O(1)</code>) it doesn't make much difference and adding a variable for storing this value will probably have a negligible effect with a small hit on code readability (as well as breaking the code if the string is ever changed).</p>
How to display text in system tray icon with win32 API? <p>Trying to create a small monitor application that displays current internet usage as percentage in system tray in C using win32 API. </p> <p>Also wanting to use colour background or colour text based on how much is used relative to days left in month.</p> <p><strong>EDIT:</strong> To clarify I am wanting the system tray icon to be dynamic. As the percentage changes I update the system tray icon. Looking for solution that uses just plain old win32 (ie. No MFC or WTL).</p>
<p>Okay here is my win32 solution:</p> <pre><code>HICON CreateSmallIcon( HWND hWnd ) { static TCHAR *szText = TEXT ( "100" ); HDC hdc, hdcMem; HBITMAP hBitmap = NULL; HBITMAP hOldBitMap = NULL; HBITMAP hBitmapMask = NULL; ICONINFO iconInfo; HFONT hFont; HICON hIcon; hdc = GetDC ( hWnd ); hdcMem = CreateCompatibleDC ( hdc ); hBitmap = CreateCompatibleBitmap ( hdc, 16, 16 ); hBitmapMask = CreateCompatibleBitmap ( hdc, 16, 16 ); ReleaseDC ( hWnd, hdc ); hOldBitMap = (HBITMAP) SelectObject ( hdcMem, hBitmap ); PatBlt ( hdcMem, 0, 0, 16, 16, WHITENESS ); // Draw percentage hFont = CreateFont (12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TEXT ("Arial")); hFont = (HFONT) SelectObject ( hdcMem, hFont ); TextOut ( hdcMem, 0, 0, szText, lstrlen (szText) ); SelectObject ( hdc, hOldBitMap ); hOldBitMap = NULL; iconInfo.fIcon = TRUE; iconInfo.xHotspot = 0; iconInfo.yHotspot = 0; iconInfo.hbmMask = hBitmapMask; iconInfo.hbmColor = hBitmap; hIcon = CreateIconIndirect ( &amp;iconInfo ); DeleteObject ( SelectObject ( hdcMem, hFont ) ); DeleteDC ( hdcMem ); DeleteDC ( hdc ); DeleteObject ( hBitmap ); DeleteObject ( hBitmapMask ); return hIcon; } </code></pre>