input
stringlengths
51
42.3k
output
stringlengths
18
55k
SPARQL query - Class and subclass give a class name and namespace <p>How can i get all the class properties and its sub classes with properties from an RDF datasource using SPARQL query given a class name and namespace?</p>
<p>How about <a href="http://dbpedia.org/snorql/?query=%0D%0ASELECT+%3FsubClass%2C+%3Fpredicate+%0D%0AWHERE+%7B%0D%0A+++%3FsubClass+rdfs%3AsubClassOf+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2FWork%3E+.%0D%0A+++%3Fpredicate+rdfs%3Adomain+%3FsubClass%0D%0A%7D" rel="nofollow">this</a>: </p> <pre><code>PREFIX rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; SELECT ?subClass ?predicate WHERE { ?subClass rdfs:subClassOf &lt;http://dbpedia.org/ontology/Work&gt; . ?predicate rdfs:domain ?subClass } </code></pre> <p>Give it a try on a SPARQL tool such as <a href="http://dbpedia.org/snorql/" rel="nofollow">DBPedia's SNORQL interface</a>.</p>
How does one test a file to see if it's a valid XML file before loading it with XDocument.Load()? <p>I'm loading an XML document in my C# application with the following:</p> <pre><code>XDocument xd1 = new XDocument(); xd1 = XDocument.Load(myfile); </code></pre> <p>but before that, I do test to make sure the file exists with:</p> <pre><code>File.Exists(myfile); </code></pre> <p>But... is there an (easy) way to test the file before the XDocument.Load() to make sure it's a valid XML file? In other words, my user can accidentally click on a different file in the file browser and trying to load, say, a .php file causes an exception. </p> <p>The only way I can think of is to load it into a StreamWriter and simple do a text search on the first few characters to make sure they say " <p>Thanks!</p> <p>-Adeena</p>
<p>It's probably just worth catching the specific exception if you want to show a message to the user:</p> <pre><code> try { XDocument xd1 = new XDocument(); xd1 = XDocument.Load(myfile); } catch (XmlException exception) { ShowMessage("Your XML was probably bad..."); } </code></pre>
Prevent ftplib from Downloading a File in Progress? <p>We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list.</p> <p>We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in.</p> <p>What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased. </p> <p>What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method.</p> <p>Yet again let me reiterate this, we have 0 control over the remote ftp sites.</p> <p>Thanks.</p> <p>UPDATE1:</p> <p>I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail?</p> <p>We don't have any real options here... do we?</p> <p>UPDATE2: Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts.</p> <p>E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete.</p> <p>Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file.</p> <p>:'(</p>
<p><strong>“Damn the torpedoes! Full speed ahead!”</strong></p> <p>Just download the file. If it is a large file then after the download completes wait as long as is reasonable for your scenario and continue the download from the point it stopped. Repeat until there is no more stuff to download.</p>
ASP.Net Localization & Bound controls <p>When I localize an asp.net page that is using bound controls (DetailsView, etc) that has TemplateFields bound using the &lt;%# Bind() #> syntax, after the localization all of the bindings are removed and I have to go back in &amp; rebind everything. I'm creating the localized resource file by switching to design view, then Tools / Generate Local Resource from the menu.</p> <p>Has anyone else seen this problem, and if so, do you have any suggestions for a workaround?</p> <p>Before:</p> <pre><code>&lt;asp:TemplateField HeaderText="First Name:"&gt; &lt;InsertItemTemplate&gt; &lt;uc:FirstNameTextBox runat="server" ID="FirstName" ValidationGroup="Main" Text='&lt;%# Bind("FirstName") %&gt;' /&gt; &lt;/InsertItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre> <p>After:</p> <pre><code>&lt;asp:TemplateField HeaderText="First Name:" meta:resourcekey="TemplateFieldResource1"&gt; &lt;InsertItemTemplate&gt; &lt;uc:FirstNameTextBox runat="server" ID="FirstName" ValidationGroup="Main" /&gt; &lt;/InsertItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre> <p><hr /></p> <p>Edit: Looks like its just my own UserControls that lose the binding. I tried adding the Bindable and Localizable(false) attributes to the properties, but that didn't seem to help.</p>
<p>Just found this... <a href="http://blog.smart-ms.ordina.nl/Generate+Local+Resource+Files.aspx" rel="nofollow">http://blog.smart-ms.ordina.nl/Generate+Local+Resource+Files.aspx</a></p> <p>Seems to do the trick without mangling your ASPX file at all... I've not run it over a master page / user control yet.</p>
Detect failure to load contents of an iframe <p>I can detect when the content of an iframe has loaded using the <em>load</em> event. Unfortunately, for my purposes, there are two problems with this:</p> <ul> <li>If there is an error loading the page (404/500, etc), the load event is never fired.</li> <li>If some images or other dependencies failed to load, the load event is fired as usual.</li> </ul> <p>Is there some way I can reliably determine if either of the above errors occurred?</p> <p>I'm writing a semi-web semi-desktop application based on Mozilla/XULRunner, so solutions that only work in Mozilla are welcome.</p>
<p>If you have control over the iframe page (and the pages are on the same domain name), a strategy could be as follows:</p> <ul> <li>In the parent document, initialize a variable <code>var iFrameLoaded = false;</code></li> <li>When the iframe document is loaded, set this variable in the parent to <code>true</code> calling from the iframe document a parent's function <code>(setIFrameLoaded();</code> for example).</li> <li>check the <code>iFrameLoaded</code> flag using the <code>timer</code> object (set the timer to your preferred timeout limit) - if the flag is still false you can tell that the iframe was not regularly loaded.</li> </ul> <p><em>I hope this helps.</em></p>
How do I create a wx.Image object from in-memory data? <p>I'm writing a GUI application in Python using wxPython and I want to display an image in a static control (<code>wx.StaticBitmap</code>).</p> <p>I can use <a href="http://www.wxpython.org/docs/api/wx-module.html#ImageFromStream" rel="nofollow"><code>wx.ImageFromStream</code></a> to load an image from a file, and this works OK:</p> <pre><code>static_bitmap = wx.StaticBitmap(parent, wx.ID_ANY) f = open("test.jpg", "rb") image = wx.ImageFromStream(f) bitmap = wx.BitmapFromImage(image) static_bitmap.SetBitmap(bitmap) </code></pre> <p>But, what I really want to be able to do is create the image from data in memory. So, if I write</p> <pre><code>f = open("test.jpg", "rb") data = f.read() </code></pre> <p>how can I create a <code>wx.Image</code> object from <code>data</code>?</p> <p>Thanks for your help!</p>
<p>You should be able to use <code>StringIO</code> to wrap the buffer in a memory file object.</p> <pre><code>... import StringIO buf = open("test.jpg", "rb").read() # buf = get_image_data() sbuf = StringIO.StringIO(buf) image = wx.ImageFromStream(sbuf) ... </code></pre> <p><code>buf</code> can be replaced with any data string.</p>
Getting the .NET Framework directory path <p>How can I obtain the .NET Framework directory path inside my C# application?</p> <p>The folder that I refer is "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727"</p>
<p>The path to the installation directory of the CLR active for the current .NET application can be obtained by using the following method:</p> <pre><code>System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() </code></pre> <p>I would <strong>strongly</strong> advice against reading the registry directly. For example, when a .NET application is running in 64bit systems, the CLR can either be loaded from "C:\Windows\Microsoft.NET\Framework64\v2.0.50727" (AnyCPU, x64 compilation targets) or from "C:\Windows\Microsoft.NET\Framework\v2.0.50727" (x86 compilation target). Reading registry will <strong>not</strong> tell you which one of the two directories was used by the current CLR.</p> <p>Another important fact is that "the current CLR" will be "2.0" for .NET 2.0, .NET 3.0 and .NET 3.5 applications. This means that the GetRuntimeDirectory() call will return 2.0 directory even within .NET 3.5 applications (that load some of their assemblies from 3.5 directory). Depending on your interpretation of the term ".NET Framework directory path", GetRuntimeDirectory might not be the information you are looking for ("CLR directory" versus "directory from which 3.5 assemblies are coming from").</p>
Find frequency of values in an Array or XML (C#) <p>I have an XML feed (which I don't control) and I am trying to figure out how to detect the volume of certain attribute values within the document.</p> <p>I am also parsing the XML and separating attributes into Arrays (for other functionality) </p> <p>Here is a sample of my XML</p> <pre><code>&lt;items&gt; &lt;item att1="ABC123" att2="uID" /&gt; &lt;item att1="ABC345" att2="uID" /&gt; &lt;item att1="ABC123" att2="uID" /&gt; &lt;item att1="ABC678" att2="uID" /&gt; &lt;item att1="ABC123" att2="uID" /&gt; &lt;item att1="XYZ123" att2="uID" /&gt; &lt;item att1="XYZ345" att2="uID" /&gt; &lt;item att1="XYZ678" att2="uID" /&gt; &lt;/items&gt; </code></pre> <p>I want to find the volume nodes based on each att1 value. Att1 value will change. Once I know the frequency of att1 values I need to pull the att2 value of that node.</p> <p>I need to find the TOP 4 items and pull the values of their attributes.</p> <p>All of this needs to be done in C# code behind.</p> <p>If I was using Javascript I would create an associative array and have att1 be the key and the frequency be the value. But since I'm new to c# I don't know how to duplicate this in c#.</p> <p>So I believe, first I need to find all unique att1 values in the XML. I can do this using:</p> <pre><code>IEnumerable&lt;string&gt; uItems = uItemsArray.Distinct(); // Where uItemsArray is a collection of all the att1 values in an array </code></pre> <p>Then I get stuck on how I compare each unique att1 value to the whole document to get the volume stored in a variable or array or whatever data set. </p> <p>Here is the snippet I ended up using:</p> <pre><code> XDocument doc = XDocument.Load(@"temp/salesData.xml"); var topItems = from item in doc.Descendants("item") select new { name = (string)item.Attribute("name"), sku = (string)item.Attribute("sku"), iCat = (string)item.Attribute("iCat"), sTime = (string)item.Attribute("sTime"), price = (string)item.Attribute("price"), desc = (string)item.Attribute("desc") } into node group node by node.sku into grp select new { sku = grp.Key, name = grp.ElementAt(0).name, iCat = grp.ElementAt(0).iCat, sTime = grp.ElementAt(0).sTime, price = grp.ElementAt(0).price, desc = grp.ElementAt(0).desc, Count = grp.Count() }; _topSellers = new SalesDataObject[4]; int topSellerIndex = 0; foreach (var item in topItems.OrderByDescending(x =&gt; x.Count).Take(4)) { SalesDataObject topSeller = new SalesDataObject(); topSeller.iCat = item.iCat; topSeller.iName = item.name; topSeller.iSku = item.sku; topSeller.sTime = Convert.ToDateTime(item.sTime); topSeller.iDesc = item.desc; topSeller.iPrice = item.price; _topSellers.SetValue(topSeller, topSellerIndex); topSellerIndex++; } </code></pre> <p>Thanks for all your help!</p>
<p>Are you using .NET 3.5? (It looks like it based on your code.) If so, I suspect this is pretty easy with LINQ to XML and LINQ to Objects. However, I'm afraid it's not clear from your example what you want. Do all the values with the same att1 <em>also</em> have the same att2? If so, it's something like:</p> <pre><code>var results = (from element in items.Elements("item") group element by element.Attribute("att1").Value into grouped order by grouped.Count() descending select grouped.First().Attribute("att2").Value).Take(4); </code></pre> <p>I haven't tested it, but I <em>think</em> it should work...</p> <ul> <li>We start off with all the item elements</li> <li>We group them (still as elements) by their att1 value</li> <li>We sort the groups by their size, descending so the biggest one is first</li> <li>From each group we take the first element to find its att2 value</li> <li>We take the top four of these results</li> </ul>
Firefox vs IE vs Chrome vs Safari <p>Currently I am designing a website and I am finding it VERY difficult to display the website perfect on ALL browsers. </p> <p>Is there any rules, suggestions etc to follow?</p> <p>Thanks</p>
<h3>Develop to standards, then add exceptions</h3> <p>Currently, the most popular mostly-compliant browser is Firefox, so developing to Firefox is a natural first step. Use the <a href="http://www.w3c.org/">W3C</a>'s validators to make sure you're on track. Once your page is mostly done, verify that it still looks good in Safari and Chrome (also both highly-compliant browsers, so you shouldn't have too much trouble), then start fixing it for IE (both 6 <strong>and</strong> 7). And believe me, it will need fixed! Sites like <a href="http://quirksmode.org/">QuirksMode</a> can be a big help when it comes time to add exceptions.</p> <h3>Always use the HTML 4.01 Strict DOCTYPE</h3> <p>This is probably going to be one of the more controversial points here, as XHTML has a lot of proponents. Unfortunately, it is impossible to serve XHTML files in a manner which is both IE-compatible and standards-compliant — IE won't recognize the XHTML MIME types, and it violates the standard to serve them as <code>text/html</code>. Only the HTML 4.01 Strict DOCTYPE puts all browsers into (near-)standards mode while still complying with the standards. For more info, look up <a href="http://www.webdevout.net/doctype-switching">DOCTYPE switching</a>. If you absolutely can't get by without writing pages which are well-formed XML, use an <a href="http://www.w3.org/TR/xslt/">XSL Transformation</a> to convert your pages from the XML flavor of your choice into HTML.</p> <h3>Don't use CSS "hacks"</h3> <p>They can be very tempting sometimes, but hacks are based on the <em>side-effects of browser bugs</em>. Because of this, it can be difficult-to-impossible to predict how future browsers will react to them. Conditional comments, on the other hand, are an intentional feature of IE browsers and so are safe to use. In fact, they are an excellent way to keep your IE-specific (and often non-validating) CSS out of your valid stylesheets.</p> <h3>Don't create pixel-aligned layouts</h3> <p>Trying to get all browsers to line up, <em>down to the pixel</em> is an exercise in frustration (and, often, futility). Try to create layouts which still look okay when clobbered, as it's easier to fix a misalignment between, say, two left-hand borders than a left and a right which are on opposite sides of the page! Using a background image which has built-in borders should be a <strong>big</strong> warning flag!</p> <h3>Don't use absolute sizes for fonts</h3> <p>Not everyone uses the same size monitor as you do; instead of setting a footnote to <code>font-size: 10px;</code>, set it to <code>font-size: smaller;</code> or <code>font-size: 80%;</code>. This is a big <a href="http://www.w3.org/TR/WCAG20/">acessibility</a> issue.</p> <h3>Don't rely on default values for CSS properties</h3> <p>You never know whether all browsers use the same default. <a href="http://developer.yahoo.com/yui/reset/">YUI's "reset" stylesheet</a> is a great place to start.</p>
NSDictionary with ordered keys <p>I'm curious if this is a situation any other folks have found themselves in. I have an NSDictionary (stored in a plist) that I'm basically using as an associative array (strings as keys and values). I want to use the array of keys as part of my application, but I'd like them to be in a specific order (not really an order that I can write an algorithm to sort them into). I could always store a separate array of the keys, but that seems kind of kludgey because I'd always have to update the keys of the dictionary as well as the values of the array, and make sure they always correspond. Currently I just use [myDictionary allKeys], but obviously this returns them in an arbitrary, non-guaranteed order. Is there a data structure in Objective-C that I'm missing? Does anyone have any suggestions on how to more elegantly do this?</p>
<p>Matt Gallagher just wrote a blog post titled <a href="http://cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html">“OrderedDictionary: Subclassing a Cocoa class cluster”</a> covering exactly this issue, complete with sample code.</p>
RedirectToAction Bug? <p>I Have following code:</p> <p>Controller:</p> <pre><code>public ActionResult Step1() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Step1(FormCollection form) { TempData["messageStatus"] = new Random().Next(1, 1000); return RedirectToAction("Step1"); } </code></pre> <p>View:</p> <pre><code>&lt;%=TempData["messageStatus"]%&gt; </code></pre> <p>in first time in view im getting <strong>12345</strong> for example, but when i request second time of course i must get something else instead <strong>12345</strong> for example <strong>54321</strong> but not, im getting same result <strong>12345</strong>, how can u explain it? <strong>RedirectToAction</strong> cache pages?</p> <p>where does it mean i must put Guid in my urls for resolving problems with cache? what do u think about this issue?</p>
<p>I'm guessing you're running into caching problems. It's not a problem with redirect to action. All RedirectToAction does is issues a redirect response to your browser telling it to request Step01. Then your browser makes a request for Step01.</p> <p>In that case, your browser might have Step01 cached. So you need to add a Response header in STep01 indicating it should never be cached. You can do this like so:</p> <pre><code>[OutputCache(Location = OutputCacheLocation.None)] public ActionResult Step1() { return View(); } </code></pre> <p>Or you can add a random querystring to the redirect to action call by passing in an arbitrary value.</p>
Visual Studio fails to deploy report to MSRS <p>Visual Studio fails to deploy reports or data sources on remote MSRS instance. Error message is</p> <blockquote> <p>Unable to connect to the remote server.</p> </blockquote> <p>The server is up and running and <code>TargetServerURL</code> property of the project points to correct url which works in the browser.</p> <p>I googled around but and found a few forum threads discussing the same issue but none of them had any relevant resolution. </p> <p>I am using <code>VS2008</code> and <code>MSRS 2008</code>.</p> <p>Has anyone seen this before? Any ideas how to fix this?</p>
<p>This was happening to me a couple of weeks ago.</p> <p>Be sure the TargetServerURL is <code>http://server/ReportServer/</code> and not <code>http://server/Reports/</code></p> <p>There is a different URL used for the web services portion of reporting services (publishing/viewing/editing reports programmatically) and the visual UI where you can go in and browse the folders, etc.</p>
Hosting user videos <p>My client would like website visitors to embed videos in their profiles. We've suggested that we use YouTube for a quick and cost-effective (free) solution. However he is not keen that YouTube would control access to the videos which are an important part of his service. It seems unlikely that YouTube would suddenly pull the plug but to do so would be a very bad look for his business. </p> <p>Any recommendations or suggestions for alternative solutions or services? A lot of sites do use YouTube in this way. Do you feel his concerns are valid? </p> <p>This is a small business so large upfront development or service costs are out. The website is built in ASP.NET 3.5 using C# and SQL Server 2005.</p> <p>Thanks for your time!</p>
<p>Take a look at <a href="http://heywatch.com" rel="nofollow">Hey!Watch</a>. </p> <p>It's a video converting webservice. It supports a lot of formats and the converted videos can be stored on FTP, Amazon S3... it also supports watermarking and a lot of other options.</p> <p>And it's not expensive at all.</p> <p>I don't recommend doing your own conversion and storage. Video conversion takes a LOT of CPU and RAM, and storage takes a lot of disk space and bandwidth. The CPU and RAM problems can be solved with Hey!Watch, the storage problem with S3.</p>
Is there a best practice for accessing business logic services in a web app? <p>Is there a best practice for instantiating / calling business logic layer service in a web app? I've got a large number services that I keep instantiating and then disposing for just one method call. </p> <p>Should these be implemented as providers? Or maybe accessed from a singleton?</p> <p>Example code:</p> <pre><code>void ShipProduct(){ ProductService service = new ProductService(); service.Ship(aProduct); } </code></pre> <p>Obviously it's a lot more complicated than that, I just don't know if I'm doing something wrong by creating new instances of these services everywhere.</p>
<p>I'd be wary of the singleton. It's often abused in places where it's not always needed. You should only use a singleton if there should only ever be one instance of that class at a time. In this example, you'd use a singleton only if you wanted to performa exactly one Ship() action at a time.</p> <p>One pattern I like to use a lot is to create a private readonly field for the services in a class which might look like this:</p> <pre><code>public ShippingController { private readonly ProductService productService; public ShippingController(ProductService service) { productService = service; } void ShipProduct(Product aProduct) { service.Ship(aProduct); } } </code></pre> <p>At least this way, you're not bound by either decision, you could create a global ProductService that is used all over your application, or you could create a new instance and pass it in, that way you can have the best of both worlds. </p> <p>As for which way is better, it depends on your situation. Think carefully about what the exact requirements for the use of your service are and implement accordingly.</p>
powershell command to restore remote database <p>Does anyone know the powershell commands to restore a remote database from a local file?</p>
<p>Based on your comment, there are no PowerShell-specific commands. You'll need to use New-PSDrive to map a drive to the server, use Copy-Item to copy the database over to the server, and then use one of the SQL 2008 commands (there are 2 total) to execute the necessary RESTORE DATABASE command. SQL2008 hasn't shipped anything more specific than that, and the SQL Server product itself can't perform a restore from a remote path (well, maybe a UNC, but I assume you're on a client - it'd be easier to copy the backup to the server).</p>
ASP.NET - Ajax requests with jQuery <p>I've got this textBox which triggers off an ajax request using jQuery:</p> <pre><code>&lt;asp:TextBox ID="postcodeTextBox" runat="server" Text='&lt;%# Bind("POSTAL_ZIP_CODE") %&gt;'&gt; $(document).ready(PageLoad); function PageLoad() { $(container + 'parentProjectTextBox').change(GetProjectName); } function GetProjectName() { var projectNumber = $(this).val(); if (projectNumber == '') return; $(container + 'parentProjectPanel').block({ message: '&lt;img src="../Resources/RadControls/Ajax/Skins/Default/loading7.gif" /&gt;' }); $.ajax({ type: 'POST', url: projectMasterWebServicesUrl + 'GetProjectName', data: "{'projectNumber':'" + projectNumber + "'}", contentType: 'application/json; charset=utf-8', dataType: 'json', success: GetProjectNameOnSuccess, error: GetProjectNameOnError }); } </code></pre> <p>This ajax request gets a list to populate this dropdown:</p> <pre><code> &lt;asp:DropDownList ID="cityDropDownList" runat="server" OnDataBound="cityDropDownList_DataBound"&gt; &lt;asp:ListItem Text="...Select..." Value="0"&gt; &lt;/asp:ListItem&gt; &lt;/asp:DropDownList&gt; </code></pre> <p>Everything works fine. The only problem I'm having is that when I update my formView priod to saving that record I can't see the value that was set to that dropdown. As I'm populating this dropdown in the client side I supose ASP.NET loses track of that ....</p> <p>Does anyone have any insights?</p> <p>Apparently when I switch on/off the EnableEventValidation property for that page I sometimes get the correct value.....</p> <p>Thanks !</p>
<p>You should create a hidden field store that value. Update that HiddenField in your Javascript and then read it on the server side. Also, if you have EventValidation=true and you change the items in the dropdown list you will get well known exceptions.</p>
Trailing/leading zero count for a byte <p>I'm using Java and I'm coding a chess engine.</p> <p>I'm trying to find the index of the first 1 bit and the index of the last 1 bit in a byte.</p> <p>I'm currently using Long.numberOfTrailingZeros() (or something like that) in Java, and would like to emulate that functionality, except with bytes.</p> <p>Would it be something like:</p> <pre><code>byte b = 0b011000101; int firstOneBit = bitCount ((b &amp; -b) - 1); </code></pre> <p>If so, how would I implement bitCount relatively efficiently. I don't mind good explainations, please don't just give me code.</p>
<p>use a lookup tabel with 256 entries. to create it: </p> <pre><code>unsigned int bitcount ( unsigned int i ) { unsigned int r = 0; while ( i ) { r+=i&amp;1; i&gt;&gt;=1; } /* bit shift is &gt;&gt;&gt; in java afair */ return r; } </code></pre> <p>this of course does not need to be fast as you do it at most 256 times to init your tabel. </p>
How can I add a context menu to a ListBoxItem? <p>I have a ListBox and I want to add a context menu to each item in the list. I've seen the "solution" to have the right click select an item and suppress the context menu if on white space, but this solution feels dirty. </p> <p>Does anyone know a better way?</p>
<p>Just to elaborate a little further to what Frans has said...Even though the ListBox owns the ContextMenuStrip, you can still customize the items in the menu strip at the time it's opening. Thus customizing it's contents based on the mouse position within the listbox.<br /> The example below selects the item in the listbox based on a right mouse click and then customizes a context menu strip based on the item the user right-clicked on. This is a simple example but should get you going: Add a listbox to a form and add this code:</p> <pre><code>print(" #region Private Members private ContextMenuStrip listboxContextMenu; #endregion private void Form1_Load( object sender, EventArgs e ) { //assign a contextmenustrip listboxContextMenu = new ContextMenuStrip(); listboxContextMenu.Opening +=new CancelEventHandler(listboxContextMenu_Opening); listBox1.ContextMenuStrip = listboxContextMenu; //load a listbox for ( int i = 0; i &lt; 100; i++ ) { listBox1.Items.Add( "Item: " + i ); } } private void listBox1_MouseDown( object sender, MouseEventArgs e ) { if ( e.Button == MouseButtons.Right ) { //select the item under the mouse pointer listBox1.SelectedIndex = listBox1.IndexFromPoint( e.Location ); if ( listBox1.SelectedIndex != -1) { listboxContextMenu.Show(); } } } private void listboxContextMenu_Opening( object sender, CancelEventArgs e ) { //clear the menu and add custom items listboxContextMenu.Items.Clear(); listboxContextMenu.Items.Add( string.Format( "Edit - {0}", listBox1.SelectedItem.ToString() ) ); } "); </code></pre> <p>Hope that help. -Mike</p>
What's the easiest way to detect compilation failures, missing packages, etc in a Perl application? <p>I have a Perl application someone else wrote and I'm trying to make it run on my local machine. But I keep getting an error in one of the modules, which appears to be based on a missing module somewhere. What are some good tools or practices to track this thing down?</p>
<p>If you've got a missing module, you'll get an error like this:</p> <blockquote> <p>Can't locate Does/Not/Exist.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.10.0 /usr/local/share/perl/5.10.0 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 /usr/share/perl/5.10 /usr/local/lib/site_perl .).</p> </blockquote> <p>The best place to track down Perl modules is <a href="http://search.cpan.org/" rel="nofollow">CPAN search</a>. You can install them using the CPAN shell, available by running:</p> <pre><code>perl -MCPAN -e shell </code></pre> <p>You may also be able to get them from your Perl vendor/Linux distro.</p> <p>As for finding them all, two approaches come to mind:</p> <ol> <li><p>When you ran perl Makefile.PL, it should have told you all the modules you need to install. Of course, this is only if whoever wrote the app bothered to make it work.</p></li> <li><p>Search the files for 'use' and 'require' directives.</p></li> </ol>
need help-variable creation in Python (continuation) <p><a href="http://stackoverflow.com/questions/374572/need-help-variable-creation-in-python#374604">That</a> was helpful kgiannakakis. I'm facing a problem as below:</p> <pre><code>a = ['zbc','2.3'] for i in range(0,5): exec('E%d=%s' %(i,a[i])) </code></pre> <p>This results in:</p> <pre> Traceback (most recent call last): File "", line 2, in exec('E%d=%s' %(i,a[i])) File "", line 1, in NameError: name 'zbc' is not defined </pre>
<p>It looks like the code you're generating expands to:</p> <pre><code>E0=zbc E1=2.3 </code></pre> <p>At the next iteration through the loop, you'll get an IndexError exception because <code>a</code> is only two elements long.</p> <p>So given the above, you are trying to assign the value of <code>zbc</code> to <code>E0</code>. If <code>zbc</code> doesn't exist (which it seems that it doesn't), then you will get the NameError you mention.</p> <p>It's hard to determine what you're actually trying to do with this code, so I'm not sure what to recommend. You could assign strings instead:</p> <pre><code>exec('E%d="%s"' %(i,a[i])) </code></pre> <p>This would expand to:</p> <pre><code>E0="zbc" E1="2.3" </code></pre> <p>You would still get the IndexError because your array <code>a</code> is not 5 elements long. That should be an easy fix for you.</p>
DevExpress ASP.Net Component on Mono <p>I'm a happy user of DevExpress components, though currently I'm still on a linux web host. </p> <p>In another thread I've spoken about my plans to move to a Windows environment so that I can use DevExpress's ASP.Net components. For some time now DevExpress's stand has been that their components is not likely to work on Mono, due to heavy usage of P/Invoke. </p> <p>Having no prior experience with their ASP.Net components, my question is, has anyone successfully used their ASP.Net controls under Mono? I've read some posts that indicated that they had much better luck with ASP.Net stuff under mono than WinForms stuff.</p>
<p>If they state their controls are P/Invoke heavy, than you can either drop the controls or drop Linux. Mono is not at fault, only thing to blame is the code that has been written with only Windows in mind. And from my experience - code that breaks on Linux because of using P/Invokes will also break on Windows 64 bit (as the native libraries are not 32/64 bit agnostic like the managed assemblies).</p>
Silverlight Datagrid: Changing cell styles, based on values <p>I have some data. I want to go through that data and change cells (for example - Background color), if that data meets a certain condition. Somehow, I've not been able to figure it out how to do this seemingly easy thing in Silverlight.</p>
<p>This is slightly old code (from before RTM), but does something like what you're looking for. It checks some data on an object in a row and then sets the colour of the row accordingly.</p> <p><strong>XAML:</strong></p> <pre><code>&lt;my:DataGrid x:Name="Grid" Grid.Row="1" Margin="5" GridlinesVisibility="None" PreparingRow="Grid_PreparingRow"&gt; &lt;my:DataGrid.Columns&gt; &lt;my:DataGridTextBoxColumn DisplayMemberBinding="{Binding Cheese}" Header="Cheese"&gt;&lt;/my:DataGridTextBoxColumn&gt; &lt;my:DataGridTextBoxColumn DisplayMemberBinding="{Binding Biscuit}" Header="Biscuit"&gt;&lt;/my:DataGridTextBoxColumn&gt; &lt;/my:DataGrid.Columns&gt; &lt;/my:DataGrid&gt; </code></pre> <p><strong>Code:</strong></p> <pre><code>this.Grid.AlternatingRowBackground = null; private void Grid_PreparingRow(object sender, DataGridRowEventArgs e) { CheesyClass c = e.Row.DataContext as CheesyClass; if (c != null &amp;&amp; c.Cheese == "cheddar") { e.Row.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 255, 125, 125)); } } </code></pre>
.htaccess - Rule being ignored <p>I use this line in my .htaccess file to automatically add a trailing slash if not present</p> <pre><code>rewriteRule ^(([a-z0-9\-]+/)*[a-z0-9\-]+)$ /$1/ [NC,R=301] </code></pre> <p>This works fine, until I use these lines to redirect all requests to not files or dirs to index.php</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule . index.php </code></pre> <p>This now forwards the page, but doesn't add the trailing slash.</p> <p>Does anyone know why this wouldn't be working?</p>
<p>I figured it out, I added the L for last rule to the first rewriteRule.</p> <p>So it now looks like this</p> <pre><code>rewriteRule ^(([a-z0-9\-]+/)*[a-z0-9\-]+)$ /$1/ [NC,R=301,L] </code></pre>
Newest Microsoft Chart and ASP.NET MVC <p>Recently ASP.NET developer launched its newest control, Charting control. (<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=130f7986-bf49-4fe5-9ca8-910ae6ea442c&amp;DisplayLang=en" rel="nofollow">Microsoft Chart</a>). Does this compatible with ASP.NET MVC, or its only compatible with ASP.NET WebForm ?</p>
<p><a href="http://weblogs.asp.net/melvynharbour/archive/2008/11/25/combining-asp-net-mvc-and-asp-net-charting-controls.aspx">They are compatible with MVC</a></p>
Inversion of Control in Compilers <p>Has anyone out there actually used inversion of control containers <em>within</em> compiler implementations yet? I know that by design, compilers need to be very fast, but I've always been curious about how IoC/DI could affect the construction of a programming language--hot-swappable syntaxes, anyone?</p>
<p>Lisp-style languages often do this. <a href="http://www.psg.com/~dlamkins/sl/chapter03-12.html" rel="nofollow">Reader macros</a> are pieces of user-written code which extend the reader (and hence, the syntax) of a language. Plain-old macros are pieces of user-written code which also extend the language.</p> <p>The entire syntaxes aren't hot-swappable, but certain pieces are extendable in various ways.</p> <p>All this isn't a new idea. Before it was deemed worthy of a three-letter acronym, IoC was known as "late binding", and pretty agreed on as a Good Idea.</p>
Is Catalyst+Mason+Template::Toolkit worth learning rather than sticking to LAMP+Axkit? <p>Currently i'm using pretty much Unix + Mysql + Perl + Apache with some javascript to make it more ajax like. and i've been looking at sites which are web 2.0 and stackoverflow and really like the simple design and the smooth flow from pages and action, etc.</p> <p>i'm trying to decide if learning catalyst, mason and the likes are going to be able to provide me with the capability to build powerful and smooth web 2.0 website with less effort and easier and cleaner code to maintain later.</p> <p>as of right now, i don't really like the website that i built as it's pretty much stale and slow. but <a href="http://stackoverflow.com/questions/105226/is-perl-still-a-viable-language-for-web-development">i've read from here</a> that if i want to build a career out of it, then LAMP would be a better choice?</p> <p>just wondering in terms of these three criterias, what would be my best step forward?</p> <ol> <li>career development</li> <li>ease of building powerful web 2.0 websites</li> <li>in what way is the Catalyst actually better than LAMP?</li> </ol> <p>thanks. ~steve</p>
<p>Answers to your questions....</p> <ol> <li><p><em>"career development"</em> - MVC is a good programming practice so gaining knowledge and experience of it would definitely enhance your career potential.</p></li> <li><p><em>"ease of building powerful web 2.0 website"</em> - Catalyst certainly make this a lot easier because there are already people that have been there and done it (ie. modules on CPAN).</p></li> <li><p><em>"in what way is Catalyst actually better than LAMP?"</em> - Well really they're just different. However Catalyst does enforce a clear programming paradigm (MVC) which makes testing, refactoring, producing reusable code and much more a lot easier... IMHO ;-)</p></li> </ol> <p>Hope this helps.</p> <p>/I3az/</p> <p>PS. Catalyst is the daddy of web (MVC) frameworks on Perl and I highly recommend it. However do check out the alternatives... <a href="http://stackoverflow.com/questions/45470/suggest-some-good-mvc-framework-in-perl">Suggest some Good MVC Framework in Perl</a>. </p> <p>PPS. A good list of web frameworks (not just MVC ones) can be found on <a href="http://www.perlfoundation.org/perl5/index.cgi?web_frameworks" rel="nofollow">Perl5 Wiki</a>. </p> <p>PPPS. Perl is and will continue be a good choice for web (2.0) development (ie. ignore the FUD). If by chance I'm wrong then learning something like Catalyst / MVC will provide u with necessary skills which are easily adaptable elsewhere.</p>
JBPM Workflow patch generation <p>I have been using JBPM workflow in my project and I have a small question regarding generating the database patches or SQL statements to apply JBPM workflow modifications. </p> <p>Currently JBPM workflow provides a way to refresh the JBPM tables in schema with the deployment of the latest process definitions. However what if my system is already live with process definition deployed with state X and now I have modified the process definition file to accommodate change X2. I still need to be able to deploy the delta changes without disrupting the instances of old saved data.</p> <p>Is it possible to generate only "delta" database scripts for the JBPM process definition modification? And what are other good tools which can be used to modify process definitions more intuitively? </p> <p>To reiterate on my problem, JBPM deploy cleans the JBPM tables of old instances maintained there and then redeploys the latest files; how do I generate the delta without deleting old data? Are there any user friendly tools for that?</p> <p>Any help in this regard will be appreciated.</p>
<p>I'm not sure to have understood correctly your issue. JBpm doesn't clean tables for old process instances when you deploy a new process definition.</p> <p>When you deploy a new process definition with the same name of an existing one, you get new version of that process definition.</p> <p>Existing process instances continue running with the process definition version they was started with, while new process instances take the latest version unless you specify the precise version to be used.</p> <p>In theory, process definition can also be modified for running process instances using the API. In doing so, you must pay attention to make these changes compatible with the flowing of these instances.</p>
WPF Designer has bug with parsing generic control with overrided property <p>I've created a generic lookless control with virtual property:</p> <pre><code>public abstract class TestControlBase&lt;TValue&gt; : Control { public static readonly DependencyProperty ValueProperty; static TestControlBase() { ValueProperty = DependencyProperty.Register("Value", typeof(TValue), typeof(TestControlBase&lt;TValue&gt;)); } protected TestControlBase() { Focusable = false; Value = default(TValue); } public virtual TValue Value { get { return (TValue)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } } </code></pre> <p>Then I've made a control derived from it and overrided Value property:</p> <pre><code>public class TestControl : TestControlBase&lt;int&gt; { public override int Value { get { return base.Value; } set { base.Value = value; } } } </code></pre> <p>So I use it in a Window XAML:</p> <pre><code> &lt;TestControls:TestControl /&gt; </code></pre> <p>When I open window in designer all is OK, but when I put mouse cursor to this line, or to this control in designer I receive exception:</p> <pre><code>Exception has been thrown by the target of an invocation. at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct&amp; sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Delegate.DynamicInvokeImpl(Object[] args) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) Ambiguous match found. at System.RuntimeType.GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) at System.Type.GetProperty(String name) at MS.Internal.ComponentModel.DependencyPropertyKind.get_IsDirect() at MS.Internal.ComponentModel.DependencyPropertyKind.get_IsAttached() at MS.Internal.ComponentModel.APCustomTypeDescriptor.GetProperties(Attribute[] attributes) at MS.Internal.ComponentModel.APCustomTypeDescriptor.GetProperties() at System.ComponentModel.TypeDescriptor.TypeDescriptionNode.DefaultExtendedTypeDescriptor.System.ComponentModel.ICustomTypeDescriptor.GetProperties() at System.ComponentModel.TypeDescriptor.GetPropertiesImpl(Object component, Attribute[] attributes, Boolean noCustomTypeDesc, Boolean noAttributes) at System.ComponentModel.TypeDescriptor.GetProperties(Object component) at MS.Internal.Model.ModelPropertyCollectionImpl.GetProperties(String propertyNameHint) at MS.Internal.Model.ModelPropertyCollectionImpl.&lt;GetEnumerator&gt;d__0.MoveNext() at MS.Internal.Designer.PropertyEditing.Model.ModelPropertyMerger.&lt;GetFirstProperties&gt;d__0.MoveNext() at MS.Internal.Designer.PropertyEditing.PropertyInspector.UpdateCategories(Selection selection) at MS.Internal.Designer.PropertyEditing.PropertyInspector.OnSelectionChangedIdle() </code></pre> <p>Who know this problem? Please explain :) I have no ideas except that WPF Designer doesn't like generics. If I replace generics by <code>Object</code> all is OK.</p>
<p>Ivan,</p> <p>Maybe the answer is a little bit late to you but other people can use it too. I had the same problem and got very disappointed when I read that this is a bug. But after some googleing I found a <a href="http://jamescrisp.org/2008/05/26/wpf-control-inheritance-with-generics/" rel="nofollow">blog</a> that shows a way to use this kind of inheritance. It seems that the problem is solved including some properties in the xaml. I hope it helps.</p>
Linq to Entities / Entity Framework cross edmx "join" <p>I have two entities, each from a different database and therefore different edmx files. There is, however, an infered relationship between them.</p> <p><code>Foo</code> has many <code>Bar</code>s for example.</p> <p>What's the easiest way to do this join in the EntityFramework, with fewest database calls?</p> <p>Thanks.</p>
<p>You can do this by adding cross-model navigation properties. This requires manually editing the EDMX. There is an example, including LINQ to Entities, <a href="http://blogs.msdn.com/adonet/archive/2008/11/25/working-with-large-models-in-entity-framework-part-2.aspx" rel="nofollow" title="Working With Large Models In Entity Framework">here</a>.</p>
Access Report PageHeader not with GroupHeader <p>I'm stuck with the following:</p> <p>I have an Access2003 report "rptInvoices". Group levels are on CustomerID and PackingListID. </p> <p>What I like to achieve is that every 2nd (or 3rd etc.) page of an invoice starts with a blank section (of say 9cm) at the top of the page. For this I would use an empty PageHeader section. If the Report's property PageHeader had a value like NotWithGroupHeaderX, this would be easy. </p> <p>Since there isn't such a value: how can I hide the PageHeader on a report if there's a GroupHeader named grhCustomerID on that page?</p> <p>Maybe I need a different approach, but I just don't see it.</p>
<p>In the groupheader <code>format event</code> set the <code>pageheadersection.visible</code> to <code>true</code> so the page header prints for pages after the group header. In the group footer format event set the <code>pageheadersection.visible</code> to <code>false</code> so the page header does not print at the top of the next page which has the group header.</p>
MVC framework for huge Java EE application <p>Which MVC-framework is the best option (performance/ease of development) for a web application, that will have + 2 million visits per week.</p> <p>Basically the site is a search engine,but also there will be large amounts of XML parsing, and high db traffic.</p> <p>We are using Java, over Jboss 4.2.3x, with PG as DB, and Solr for the searches.</p> <p>We were thinking on code JSPs with taglibs, and Servlets, but we were feeling like there would be a better alternative, which don't know yet, as we are starting on the Java Web applications world.</p> <p>Any opinions, and shares of your experience will be appreciated!<br> Thanks in advance!</p>
<p>I think you really need to sit down with the options, and assess each one (or combination thereof).</p> <p>Some possible framewords that you might use (that come to mind, beyond plain old JSPs with Servlets) are:</p> <ul> <li>Struts and Tiles</li> <li>Spring</li> <li>Hibernate</li> <li>Roll your own framework (often worthwhile for large projects, but only if you know what you need which is unlikely if you haven't done web apps before)</li> <li>Grails (Groovy on Rails, but it runs on the JVM and can use Java libs)</li> </ul> <p>and many more I'm sure...</p> <p>Do you want to reinvent the wheel? What client-side frameworks will you also want to use?</p>
How can I animate a static object in a WPF storyboard <p>I have a WPF program to which I need to add a "Demo mode". Since I want my designers to be able to modify the demo mode without me having to recompile the program each time, I tough it would be a great idea to use a storyboard from an external XAML file. The "Demo mode" is basically a storyboard animating some of the application's dependency properties.</p> <p>To expose my application's DPs, I have created a public static member (singleton) of the application's class so that the application's DPs are always available externally. In this case, the storyboard will be accessing them.</p> <p>In the external XAML file, I have added the proper xmlns referencing correctly the application's namespace/assembly. So in theory, I should be able to access the application's DP in a Storyboard.</p> <p>The problem is that I don't know how to animate a DP of a static object in a Storyboard when the object is not declared/named in the XAML. When declaring a storyboard animation frame, the only storyboard's attached property are <em>Storyboard.TargetName</em> and <em>Storyboard.TargetProperty</em>.</p> <p>I would appreciate if someone could give me a hint to get me in the right direction.</p>
<p>I haven't tried this out, but if it is doable I would guess it looks something like this:</p> <pre><code>&lt;Storyboard ..&gt; &lt;DoubleAnimation Storyboard.Target="{x:Static MyNS:MyClass.Singleton}" Storyboard.TargetProperty="MyProperty" .../&gt; &lt;/Storyboard&gt; </code></pre>
How to truncate and shrink log files? <p>How to truncate and shrink large log files in SQL Server 2005? How to apply truncation at regular intervals?</p> <p>Is there any difference between truncation and shrinking?</p> <p>Thanks in advance</p>
<p>Use DBCC SHRINKFILE and schedule it as a job that runs regularly (preferably during off-hours). </p> <p>Just be aware that there is a performance hit from regularly growing and shrinking the log file. If you have the space, you may want to set the file size to the maximum that it normally grows to and just leave it.</p>
Using GROUP_CONCAT on subquery in MySQL <p>I have a MySQL query in which I want to include a list of ID's from another table. On the website, people are able to add certain items, and people can then add those items to their favourites. I basically want to get the list of ID's of people who have favourited that item (this is a bit simplified, but this is what it boils down to).</p> <p>Basically, I do something like this:</p> <pre><code>SELECT *, GROUP_CONCAT((SELECT userid FROM favourites WHERE itemid = items.id) SEPARATOR ',') AS idlist FROM items WHERE id = $someid </code></pre> <p>This way, I would be able to show who favourited some item, by splitting the idlist later on to an array in PHP further on in my code, however I am getting the following MySQL error:</p> <blockquote> <p><em>1242 - Subquery returns more than 1 row</em> </p> </blockquote> <p>I thought that was kind of the point of using <code>GROUP_CONCAT</code> instead of, for example, <code>CONCAT</code>? Am I going about this the wrong way?</p> <hr> <p>Ok, thanks for the answers so far, that seems to work. However, there is a catch. Items are also considered to be a favourite if it was added by that user. So I would need an additional check to check if creator = userid. Can someone help me come up with a smart (and hopefully efficient) way to do this?</p> <p>Thank you!</p> <p>Edit: I just tried to do this:</p> <pre><code>SELECT [...] LEFT JOIN favourites ON (userid = itemid OR creator = userid) </code></pre> <p>And <strong>idlist</strong> is empty. Note that if I use <code>INNER JOIN</code> instead of <code>LEFT JOIN</code> I get an empty result. Even though I am sure there are rows that meet the ON requirement.</p>
<p>OP almost got it right. <code>GROUP_CONCAT</code> should be wrapping the columns in the subquery and not the <a href="http://stackoverflow.com/a/4455991/838733">complete subquery</a> (I'm dismissing the separator because comma is the default):</p> <pre><code>SELECT i.*, (SELECT GROUP_CONCAT(userid) FROM favourites f WHERE f.itemid = i.id) AS idlist FROM items i WHERE i.id = $someid </code></pre> <p>This will yield the desired result and also means that the accepted answer is partially wrong, because you can access outer scope variables in a subquery.</p>
How do I exclude records from an associated model in CakePHP? <p>I'm creating a Q&amp;A application in CakePHP, and I want to exclude my associations in some cases. Imagine the following:</p> <p>I'm listing all questions on the first page using $this->Question->findAll();. Since I have the following association in my model:</p> <pre><code>public $hasMany = array('Answer' =&gt; array('className' =&gt; 'Answer', 'order' =&gt; 'Answer.created DESC', 'foreignKey' =&gt; 'post_id', 'dependent' =&gt; true, 'exclusive' =&gt; false, ) ); </code></pre> <p>All answers will get selected at the start page, which is not optimal. How could i do to exclude the answers in this particular method?</p> <p>Thanks</p>
<p>I quick look at the <a href="http://api.cakephp.org">CakePHP API</a> reveals that you've got an <a href="http://api.cakephp.org/class_model.html#0b969d5264205cd3a425980dd53e9658">unbindModel</a> method on the Model. So in you example you can do this:</p> <pre><code>$this-&gt;Question-&gt;unBindModel(array('hasMany' =&gt; array(’Answer’))) </code></pre> <p>Alternatively, you can use the <a href="http://book.cakephp.org/view/474/Containable">Containable</a> behaviour to only select the pieces from MySQL that you require for the current page view.</p>
algorithm to find maximum occurence of a substring <p>Given a string S, what is the best algorithm to find a substring which repeats maximum number of times.</p> <p>For example, in "assdssfssd", it is "ss" which repeats maximum number of times.</p>
<p>I can see building a tree to solve that particular problem.</p> <p>There is a notional root node. The first character is the first child. The second character is a child of the first character a -> s in your case. It also begins a new leaf of the root node. If, in adding a node, you visit an existing node, you increment its count (initial value 1).</p> <p>Once done, you visit every node of the tree to find the one with the highest count at the deepest level (because if "asdf" occurs 5 times then "a", "as" and "asd" occur a minimum of 5 times, by definition).</p>
Setting a font color in VBA <p>I want to set the font color of a cell to a specific RGB value.</p> <p>If I use</p> <pre><code>ActiveCell.Color = RGB(255,255,0) </code></pre> <p>I do get yellow, but if I use a more exotic RGB value like:</p> <pre><code>ActiveCell.Color = RGB(178, 150, 109) </code></pre> <p>I just get a grey color back.</p> <p>How come can't I just use any RGB value? And do you know any workarounds?</p> <p>Thanks.</p>
<p>Excel only uses the colors in the color palette. When you set a cell using the RGB value, it chooses the one in the palette that is the closest match. You can update the palette with your colors and then choose your color and that will work.</p> <p>This will let you see what is currently in the palette:</p> <pre><code> Public Sub checkPalette() Dim i As Integer, iRed As Integer, iGreen As Integer, iBlue As Integer Dim lcolor As Long For i = 1 To 56 lcolor = ActiveWorkbook.Colors(i) iRed = lcolor Mod &amp;H100 'get red component lcolor = lcolor \ &amp;H100 'divide iGreen = lcolor Mod &amp;H100 'get green component lcolor = lcolor \ &amp;H100 'divide iBlue = lcolor Mod &amp;H100 'get blue component Debug.Print "Palette " &amp; i &amp; ": R=" &amp; iRed &amp; " B=" &amp; iBlue &amp; " G=" &amp; iGreen Next i End Sub </code></pre> <p>This will let you set the palette</p> <pre><code>Public Sub setPalette(palIdx As Integer, r As Integer, g As Integer, b As Integer) ActiveWorkbook.Colors(palIdx) = RGB(r, g, b) End Sub </code></pre>
Elegantly determine if more than one boolean is "true" <p>I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would allow me to check this condition in a single if() statement? Target language is C# but I'm interested in solutions in other languages as well (as long as we're not talking about specific built-in functions). </p> <p>One interesting option is to store the booleans in a byte, do a right shift and compare with the original byte. Something like <code>if(myByte &amp;&amp; (myByte &gt;&gt; 1))</code> But this would require converting the separate booleans to a byte (via a bitArray?) and that seems a bit (pun intended) clumsy... <em>[edit]Sorry, that should have been</em> <code>if(myByte &amp; (myByte - 1))</code> <em>[/edit]</em></p> <p>Note: This is of course very close to the classical "population count", "sideways addition" or "Hamming weight" programming problem - but not quite the same. I don't need to know how many of the bits are set, only if it is more than one. My hope is that there is a much simpler way to accomplish this. </p>
<p>I was going to write the Linq version, but five or so people beat me to it. But I really like the params approach to avoid having to manually new up an array. So I think the best hybrid is, based on rp's answer with the body replace with the obvious Linqness:</p> <pre><code>public static int Truth(params bool[] booleans) { return booleans.Count(b =&gt; b); } </code></pre> <p>Beautifully clear to read, and to use:</p> <pre><code>if (Truth(m, n, o, p, q) &gt; 2) </code></pre>
When installing my windows service, how can I programatically make it use a specific domain account <p>I have a windows service that runs fine, but I have to have it run under a special user account.</p> <p>Currently I go into services and change the logon as section, but for deployment this has to be done more professionally.</p> <p>Is there a way for me to have it logon as a custom user account programatically, or during the installation process of the service?</p>
<p>When you open the Service COntrol Manager,(SCM), of course,there is a tab labeled Logon.. In there you can specify which domain or machine account it should run under... </p> <p>But programatically. if you use a Service Installer class in your code you can specify it there..</p> <pre><code> public class MyServiceInstaller : Installer { private ServiceInstaller servInst; private ServiceProcessInstaller servProcInst; public MyServiceInstaller () { InitializeComponent(); } #region Component Designer generated code private void InitializeComponent() { servInst = new ServiceInstaller(); servProcInst = new ServiceProcessInstaller(); // ----------------------------------------------- servProcInst.Account = ServiceAccount.LocalSystem; // or whatever accnt you want servProcInst.Username = null; // or, specify a specifc acct here servProcInst.Password = null; servProcInst.AfterInstall += new InstallEventHandler(this.AfterServProcInstall); servInst.ServiceName = "MyService"; servInst.DisplayName = "Display name for MyService"; servInst.Description = " Description for my service"; servInst.StartType = ServiceStartMode.Automatic; servInst.AfterInstall += new InstallEventHandler(this.AfterServiceInstall); Installers.AddRange(new Installer[] { servProcInst, servInst }); } #endregion } private void AfterServiceInstall(object sender, InstallEventArgs e) { } private void AfterServProcInstall(object sender, InstallEventArgs e) { } </code></pre>
Recursive sql problem <p>I have a problem that I would like have solved via a SQL query. This is going to be used as a PoC (proof of concept).</p> <p>The problem:</p> <p>Product offerings are made up of one or many product instances, a product instance can belong to many product offerings. This can be realised like this in a table:</p> <pre><code>PO | PI ----- A | 10 A | 11 A | 12 B | 10 B | 11 C | 13 </code></pre> <p>Now I would like to get back the product offer from a set of product instances. E.g. if we send in 10,11,13 the expected result back is B &amp; C, and if we send in only 10 then the result should be NULL since no product offering is made up of only 10. Sending in 10,11,12 would result in A (not A &amp; B since 12 is not a valid product offer in it self).</p> <p>Prerequisites: The combination of product instances sent in can only result in one specific combination of product offerings, so there is only one solution to each query.</p>
<p>Okay, I think I have it. This meets the constraints you provided. There might be a way to simplify this further, but it ate my brain a little:</p> <pre><code>select distinct PO from POPI x where PO not in ( select PO from POPI where PI not in (10,11,12) ) and PI not in ( select PI from POPI where PO != x.PO and PO not in ( select PO from POPI where PI not in (10,11,12) ) ); </code></pre> <p>This yields only results who fill the given set which are disjoint with all other results, which I <strong>think</strong> is what you were asking for. For the test examples given:</p> <ul> <li>Providing 10,11,12 yields A</li> <li>Providing 10,11,13 yields B,C</li> </ul>
C++ sql pass integer to sql string <p>I have built a database in MS Access. There I have a table called Customers which also has a cell called Employee type: integer. I also built a program in C++ which controls all data.</p> <p>Let's say I have a string like this:</p> <pre><code>string sqlString = "SELECT * FROM Customers Where Customers.Employee = '" + id + "' "; </code></pre> <p>Id passes through my function correctly and is an integer, so I get an error in compilation saying: "Invalid pointer addition".</p> <p>If I declare id as a string of course there's no error but there are no results in my form also. If I declare in database cell Employee as text and build my query like this:</p> <pre><code>string sqlString = "SELECT * FROM Customers WHERE Customers.Employee = 128"; </code></pre> <p>I get results, but I need that Employee as an integer cause its a foreign key from another table.</p> <p>So, what should I do with my query to have results passing integer as parameter through variable id, to be ok with the cell Employee from database which is also integer? Any ideas? I would really appreciate some help here.</p> <hr> <p>As I said, if I convert id to string, there are no results in my form since Employee in database is an integer. So this:</p> <pre><code>std::ostringstream buf; buf &lt;&lt; "SELECT * FROM Customers Where Customers.Employee = '" &lt;&lt; id &lt;&lt; "' "; string str = buf.str(); </code></pre> <p>won't do the job or any other conversion.</p> <p>How can I pass id as an integer in my query?</p>
<p>You could use sprintf, but in C++ you can do:</p> <pre><code>std::ostringstream buf; buf &lt;&lt; "SELECT * FROM Customers Where Customers.Employee = '" &lt;&lt; id &lt;&lt; "' "; string str = buf.str(); </code></pre> <p>(untested)</p>
How can I set the position of my datagrid scrollbar in my winforms app? <p>In my C# winforms app, I have a datagrid. When the datagrid reloads, I want to set the scrollbar back to where the user had it set. How can I do this?</p> <p>EDIT: I'm using the old winforms DataGrid control, not the newer DataGridView</p>
<p>You don't actually interact directly with the scrollbar, rather you set the <code>FirstDisplayedScrollingRowIndex</code>. So before it reloads, capture that index, once it's reloaded, reset it to that index.</p> <p><strong>EDIT:</strong> Good point in the comment. If you're using a <code>DataGridView</code> then this will work. If you're using the old <code>DataGrid</code> then the easiest way to do that is to inherit from it. See here: <a href="http://www.thescarms.com/dotnet/ScrollDataGrid.aspx" rel="nofollow">Linkage</a></p> <p>The DataGrid has a protected GridVScrolled method that can be used to scroll the grid to a specific row. To use it, derive a new grid from the DataGrid and add a ScrollToRow method.</p> <p><strong>C# code</strong></p> <pre><code>public void ScrollToRow(int theRow) { // // Expose the protected GridVScrolled method allowing you // to programmatically scroll the grid to a particular row. // if (DataSource != null) { GridVScrolled(this, new ScrollEventArgs(ScrollEventType.LargeIncrement, theRow)); } } </code></pre>
ASP.NET Website's BIN directory and references <p>Imagine the following solution:</p> <ul> <li>Website ABC.com (not Web Application)</li> <li>BLL (business logic layer in a seperate assembly)</li> <li>DTO (dto objects in their own assembly)</li> <li><p>DAL (data access layer in it's own assembly as well).</p> <ol> <li>The BLL has a reference to the DAL.</li> <li>The BLL has a reference to the DTO layer.</li> <li>The Website project references the BLL.</li> </ol></li> </ul> <p>When one compiles the website project, the following DLLs will appear in the BIN directory:<br> BLL.dll<br> DTO.dll<br> DAL.dll </p> <p>When one goes to preview the site, an error occurs about not having the necessary assembly references... Now if one right clicks on the website project, Add Reference, and explicitly add the reference to the missing assemblies, it will work fine.</p> <p>It seems to me like ASP.NET pulls the referenced assemblies of the referenced assembly being added/referenced in the website. </p> <p>Why does one need to add explicit references to the references of the references... ? Sorry if I'm not wording this correctly or if it confusing.</p>
<p>I think the problem may have to do with using a web site project, as oppossed to a Web Application. I can't remember off the top of my head, but there's something funky about the way web site projects are compiled, as oppossed to web application projects.</p>
How can I debug a win32 process that unexpectedly terminates silently? <p>I have a Windows application written in C++ that occasionally evaporates. I use the word evaporate because there is nothing left behind: no "we're sorry" message from Windows, no crash dump from the Dr. Watson facility...</p> <p>On the one occasion the crash occurred under the debugger, the debugger did not break---it showed the application still running. When I manually paused execution, I found that my process no longer had any threads.</p> <p>How can I capture the reason this process is terminating?</p>
<p>You could try using the adplus utility in the <a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx" rel="nofollow">windows debugging tool package</a>.</p> <pre><code>adplus -crash -p yourprocessid </code></pre> <p>The auto dump tool provides mini dumps for exceptions and a full dump if the application crashes.</p>
Scaling a rich domain model <p>Domain Driven Design encourages you to use a rich domain model. This means all the domain logic is located in the domain model, and that the domain model is supreme. Persistence becomes an external concern, as the domain model itself ideally knows nothing of persistence (e.g. the database).</p> <p>I've been using this in practice on a medium-size one-man project (>100k lines of Java) and I'm discovering many advantages, mostly the flexibility and refactorability that this offers over a database-oriented approach. I can add and remove domain classes, hit a few buttons and an entire new database schema and SQL layer rolls out.</p> <p>However, I often face issues where I'm finding it difficult to reconcile the rich domain logic with the fact that there's an SQL database backing the application. In general, this results in the typical "1+N queries problem", where you fetch N objects, and then execute a nontrivial method on each object that again triggers queries. Optimizing this by hand allows you to do the process in a constant number of SQL queries.</p> <p>In my design I allow for a system to plug these optimized versions in. I do this by moving the code into a "query module" which contains dozens of domain-specific queries (e.g. getActiveUsers), of which I have both in-memory (naive and not scalable) and SQL-based (for deployment use) implementations. This allows me to optimize the hotspots, but there are two main disadvantages:</p> <ul> <li>I'm effectively moving some of my domain logic to places where it doesn't really belong, and in fact even pushing it into SQL statements.</li> <li>The process requires me to peruse query logs to find out where the hotspots are, after which I have to refactor the code, reducing its level abstraction by lowering it into queries.</li> </ul> <p>Is there a better, cleaner way to reconcile Domain-Driven-Design and its Rich Domain Model with the fact that you can't have all your entities in memory and are therefore confined to a database backend?</p>
<p>There are at least two ways to look at this problem, one is a technical "what can I do to load my data smarter" version. The only really smart thing I know about is dynamic collections that are partially loaded with the rest loaded on-demand, with possible preload of parts. There was an interesting talk at <a href="http://www4.java.no/incogito/session/Managing+one-to-too-many+relations+in+rich+domain+models.html">JavaZone 2008 about this</a></p> <p>The second approach has been more of my focus in the time I've been working with DDD; how can I make my model so that it's more "loadable" without sacrificing too much of the DDD goodness. My hypothesis over the years has always been that a lot of DDD models model domain concepts that are actually the sum of all allowable domain states , across all business processes and the different states that occur in each business process over time. It is my belief that a lot of these loading problems get very reduced if the domain models are normalized slightly more in terms with the processes/states. This usually means there is no "Order" object because an ordrer typically exists in multiple distinct states that have fairly different semantics attached (ShoppingCartOrder, ShippedOrder, InvoicedOrder, HistoricalOrder). If you try to encapsulate this is a single Order object, you invariably end up with a lot of loading/construction problems.</p> <p>But there's no silver bullet here..</p>
Add web part programmatically to a Sharepoint Page and save values into the web part personalization store <p>In my project I programmatically create a web part page and add a web part to it using SPLimitedWebPartManager. I also want to set some properties for the web part and save it into the web part personalization scope. How can I access the personalization store for the web part. </p>
<p>Use the method SaveChanges on SPLimitedWebPartManager after change your properties to set them.</p>
How do I to properly handle spaces in PHP Shell_exec? <p>I'm running on win2003 server, PHP 526, via the cmd-line.</p> <p>I have a cmdline string:</p> <pre><code>$cmd = ' "d:\Prog Files\foo.exe" -p "d:\data path\datadir" '; </code></pre> <p>Trying to do this in php code</p> <pre><code>$out = `$cmd`; # note use of backticks AKA shell_exec </code></pre> <p>results in a failure by foo.exe as it interprets the -p arg as "d:\data".</p> <p>However, the same <code>$cdm</code> string copied to the windows shell cmdline executes successfully.</p> <p>How do I properly handle spaces in PHP <code>shell_exec</code>?</p>
<p>Use escapeshellarg() to escape your arguments, it should escape it with an appropriate combination of quotation marks and escaped spaces for your platform (I'm guessing you're on Windows).</p>
Configuration binding extension could not be found <p>I have created a simple wcf service which used the WCF Service Library template. Everything works fine when using the default soap bindings, however when i attempt to modify the service to add a REST binding it fails with the following error:</p> <p>"Configuration binding extension 'system.serviceModel/bindings/webHttpBinding' could not be found. Verify that this binding extension is properly registered in system.serviceModel/extensions/bindingExtensions and that it is spelled correctly."</p> <p>I think i'm missing some very basic step here. Can anyone help me out?</p> <p>The relevant snippits from my config file are below:</p> <pre><code>&lt;service name="WebService.Service1"&gt; &lt;endpoint address="" binding="webHttpBinding" contract="WebService.IService1" behaviorConfiguration="RestBehavior" /&gt; &lt;/service&gt; &lt;endpointBehaviors&gt; &lt;behavior name="RestBehavior"&gt; &lt;webHttp /&gt; &lt;/behavior&gt; &lt;/endpointBehaviors&gt; </code></pre>
<p>I installed Service Pack 1 for .NET 3.5 and it seemed to fix the problem.</p>
Getting selected value from RadioButtonList <p>New to ASP.NET(C#)...</p> <p>I have a RadioButtonList on my page that is populated via DataBinding</p> <pre><code>&lt;asp:RadioButtonList ID="rb" runat="server"&gt; &lt;/asp:RadioButtonList&gt; &lt;asp:Button Text="Submit" OnClick="submit" runat="server" /&gt; </code></pre> <p>How do I get the value of the radio button that the user selected in my "submit" method?</p>
<p>The ASPX code will look something like this: </p> <pre><code> &lt;asp:RadioButtonList ID="rblist1" runat="server"&gt; &lt;asp:ListItem Text ="Item1" Value="1" /&gt; &lt;asp:ListItem Text ="Item2" Value="2" /&gt; &lt;asp:ListItem Text ="Item3" Value="3" /&gt; &lt;asp:ListItem Text ="Item4" Value="4" /&gt; &lt;/asp:RadioButtonList&gt; &lt;asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" /&gt; </code></pre> <p>And the code behind: </p> <pre><code>protected void Button1_Click(object sender, EventArgs e) { string selectedValue = rblist1.SelectedValue; Response.Write(selectedValue); } </code></pre>
Specify ordinals of C++ exported functions in a DLL <p>I am writing a DLL with mixed C/C++ code. I want to specify the ordinals of the functions I'm exporting. So I created a .DEF file that looks like this</p> <pre><code>LIBRARY LEONMATH EXPORTS sca_alloc @1 vec_alloc @2 mat_alloc @3 sca_free @4 vec_free @5 mat_free @6 ... </code></pre> <p>I would like to specify the ordinals of my C++ functions and class methods too. I have tried using the Dependency Walker to add the mangled names of my functions to the .DEF file:</p> <pre><code> ??0CScalar@@QAE@XZ @25 ??0CScalar@@QAE@O@Z @26 ??0CScalar@@QAE@ABV0@@Z @27 ??1CScalar@@QAE@XZ @28 </code></pre> <p>But this has failed. Any ideas why this could be happening?</p> <p><hr /></p> <p><b>EDIT:</b> kauppi made a good observation, so I'm adding more information to the question.</p> <ul> <li><b>Platform:</b> Windows (and I'm not interested in portability)</li> <li><b>Compiler:</b> Microsoft's C++ compiler (I'm using VS2005)</li> <li><b>Why I want to do this?:</b> Using the ordinals has the advantage of letting me call exported C++ functions from C code.</li> </ul>
<p>Well, I don't have experience with ordinals (which look like some ugly, compiler-specific thing), but I can help you with making C++/C code compatible.</p> <p>Suppose, in C++, that your header file looks like this:</p> <pre><code>class MyClass { void foo(int); int bar(int); double bar(double); void baz(MyClass); }; </code></pre> <p>You can make it C-compatible by doing the following:</p> <pre><code>#ifdef __cplusplus #define EXTERN_C extern "C" // Class definition here; unchanged #else #define EXTERN_C typedef struct MyClass MyClass; #endif EXTERN_C void MyClass_foo (MyClass*, int); EXTERN_C int MyClass_bar_int (MyClass*, int); EXTERN_C double MyClass_bar_double (MyClass*, double); EXTERN_C void MyClass_baz (MyClass*, MyClass*); </code></pre> <p>In the C++ source file, you just define the various <code>extern "C"</code> functions to pass to the desired member functions, like this (this is only one; the rest work similarly)</p> <pre><code>extern "C" void MyClass_foo (MyClass* obj, int i) { obj-&gt;foo(i); } </code></pre> <p>The code will then have a C interface, without having to change the C++ code at all (except for declarations in the header; but those could also be moved to another file <code>"myclass_c.h"</code> or the like). All the functions declared/defined extern "C" won't be mangled, so you can do other operations on them easily. You will also probably want functions to construct/destroy instances of MyClass (you can, of course, use <code>new</code>/<code>delete</code> for this).</p>
Can BlackBerry COD or ALX files be decompiled? <p>If I write Java software for a BlackBerry, can it be decompiled using freely available tools similar to <a href="http://www.red-gate.com/products/reflector/" rel="nofollow">.NET Reflector</a>, or is it a more elaborate process?</p>
<p>Software you write for any language, any platform, can be decompiled. It doesn't matter what code mangling (obfuscation) tools you use, it can be decompiled.</p> <p>Any attempt to worry about this is going to be a waste of time. Just like DRM ;p</p> <p>But the real point is, and I wish I had the link to the discussion I am thinking of because it was very good. But the point is this. Some one can decompile it, and if they just straight recompile it and try and resell it, what has been the point? It's still easy peasy to take them to court and win.</p> <p>But you say "They can look at my code and figure out how I did it and redo it!". And to this I say: Don't flatter your self.</p> <p>Think if you could get your hands on the source code to Windows. There would be a lot of "WTF are they doing here"? And "boy I would have done things differently". A few moments where you scratch your chin and go "Wow, nice". But over all, it's nothing you wouldn't have come to on your own. The real value is the time they spent to truly wrap their heads around the issue and come up with a solution.</p> <p>Anyone who rips off your code won't be doing that. What is harder? writing new software or maintaining software? I think most developers would prefer the former.</p> <p>So someone decompiles your software and either sells it in such an obvious way that you can easily prosecute, or they take the time to fully wrap their mind around the problems and design their own which in the end (years later?) will probably be completely different from yours.</p> <p>It's just such a ridiculous scenario, I really wounder if anyone has ripped off a product by decompiling a competing product.</p> <p>Don't worry about some one "stealing" your code. It CAN be done and there is nothing you can do to prevent it, but it won't be done, because it's ridiculous.</p>
Is it possible to add a description/comment to a table in Microsoft SQL 2000+ <p>Is it possible to add a "metadata"-like description or comments to a table in Microsoft SQL 2000 and above? </p> <p>How would you do this through the CREATE TABLE statement?</p> <p>Is it possible to add a description or comment to fields?</p> <p>How do you query this info back in MSSQL 2000? 2005?</p>
<p>Use extended properties. For example to add an extended property to a table in the dbo schema you can use:</p> <pre><code>EXEC sys.sp_addextendedproperty @name=N'&lt;NameOfProp&gt;', @value=N'&lt;Value&gt;' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'&lt;Table&gt;' </code></pre> <p>You can update them:</p> <pre><code>EXEC sys.sp_updateextendedproperty @name=N'MS_Description', @value=N'My Description' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE' ,@level1name=N'&lt;YOUR TABLE NAME&gt;' </code></pre> <p>You can read them like:</p> <pre><code>SELECT * FROM fn_listextendedproperty (NULL, 'schema','dbo', 'table', '&lt;yourtable&gt;', default, default); </code></pre> <p>or</p> <pre><code>SELECT p.name AS [Name],p.value FROM sys.tables AS tbl INNER JOIN sys.extended_properties AS p ON p.major_id=tbl.object_id AND p.minor_id=0 AND p.class=1 WHERE (tbl.name=N'&lt;yourtablename&gt;' and SCHEMA_NAME(tbl.schema_id)=N'dbo') ORDER BY [Name] ASC </code></pre>
DELPHI IDE - Stopping F12 from bring up the ‘CPU’ Window <p>I am busy developing a Delphi App that uses F12</p> <p>When I am running the software under the Delphi IDE and press F12 the program stops and the ‘CPU’ window opens up</p> <p>What can I do to stop the Delphi IDE from doing this when F12 is pressed ? </p>
<p>Change the value of this registry key..</p> <blockquote> <p><code>HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug\UserDebuggerHotKey</code></p> </blockquote> <p>..to 0x13 (19 in decimal). This changes the key from f12 to pause/break. You will need to reboot for this change to take effect.</p> <p>Reference: <a href="http://blogs.teamb.com/deepakshenoy/2004/12/17/2204" rel="nofollow">this blog post</a>. The MS link in the post is broken, <a href="http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/regentry/11498.mspx?mfr=true" rel="nofollow">so here's a fixed one</a>.</p>
UTF-8 file appending in vbscript/classicasp - can it be done? <p>My current knowledge:</p> <p>If you are trying to write text files in vbscript / asp land you have two options.</p> <ol> <li>the Scripting.FileSystemObject</li> <li>the ADODB.Stream object</li> </ol> <p>Scripting.FileSystemObject does not support utf8. It will write in Ascii, or Unicode (and waste two bytes for most of your characters)</p> <p>ADODB.Stream does not support appending (afaik). I can't figure out how to make the ADODB.Stream object actually open a file and write to it when I call stream.Write. There is a SaveToFile function, but it outputs the entire stream.</p> <p>If you need to write 1GB files, you would have to fill the whole 1GB into the stream before you could write it out.</p> <p>Is there a special trick to get the ADODB.Stream object to <em>link</em> to a file on disk? I tried stream.Open "URL=file:///c:\test.txt" but that gave an error.</p>
<p>In this scenario, I would probably create a COM component that takes a string, and runs it through <a href="http://msdn.microsoft.com/en-us/library/ms776420(VS.85).aspx" rel="nofollow">WideCharToMultiByte</a> to convert it to UTF-8.</p> <p>In case you really want to stay <em>within</em> VBScript, I just hacked up a very quick and very dirty UTF-8 conversion...</p> <pre><code>Function Utf8(ByVal c) Dim b1, b2, b3 If c &lt; 128 Then Utf8 = chr(c) ElseIf c &lt; 2048 Then b1 = c Mod 64 b2 = (c - b1) / 64 Utf8 = chr(&amp;hc0 + b2) &amp; chr(&amp;h80 + b1) ElseIf c &lt; 65536 Then b1 = c Mod 64 b2 = ((c - b1) / 64) Mod 64 b3 = (c - b1 - (64 * b2)) / 4096 Utf8 = chr(&amp;he0 + b3) &amp; chr(&amp;h80 + b2) &amp; chr(&amp;h80 + b1) End If End Function </code></pre> <p>Just open a file with Scripting.FileSystemObject, using system default encoding. Then pass every character of the string you want to write through this function.</p> <p><strong>NOTE</strong> that the function expects a Unicode code point, so be sure to use <code>AscW()</code> instead of plain <code>Asc()</code>:</p> <pre><code>For i = 1 to Len(s) file.Write Utf8(AscW(Mid(s, i, 1))) Next </code></pre>
Jquery - cannot select the parent div <p>I hope this isn't a waste of time, however I have really been trying to figure this on out. Is it my syntax. I simply want to remove the parent div ".number-row" once the link with a class of ".remove-link" is clicked.</p> <p>Thanks in advance</p> <pre><code>&lt;script&gt; $(document).ready(function(){ $(".remove-link").click(function() { $(this).parent(".number-row").hide(); }) }) &lt;/script&gt; </code></pre> <hr> <pre><code>&lt;div class="number-row" &gt; &lt;div class="number-column"&gt; &lt;div class="label-row"&gt; Select Country: &lt;/div&gt; &lt;div class="input-row"&gt; &lt;select&gt; &lt;option&gt;1&lt;/option&gt; &lt;option&gt;2&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="label-row"&gt; Select Toll Free or City: &lt;/div&gt; &lt;div class="input-row"&gt; &lt;select&gt; &lt;option&gt;1&lt;/option&gt; &lt;option&gt;2&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="label-row"&gt; Select Your Number: &lt;/div&gt; &lt;div class="input-row"&gt; &lt;select&gt; &lt;option&gt;1&lt;/option&gt; &lt;option&gt;2&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="number-column"&gt; &lt;div class="label-row"&gt; Select Country: &lt;/div&gt; &lt;div class="input-row"&gt; &lt;select&gt; &lt;option&gt;1&lt;/option&gt; &lt;option&gt;2&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="label-row"&gt; Enter Number to Forward to: &lt;/div&gt; &lt;div class="input-row"&gt; &lt;input type="text" name="forward_number" id="forward_number" /&gt; &lt;/div&gt; &lt;div class="number-row-options"&gt; &lt;a class="save-link" href="#"&gt;Save&lt;/a&gt; &lt;a class="remove-link" href="#"&gt;Remove&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
<p>Try <a href="http://docs.jquery.com/Traversing/parents" rel="nofollow">parents()</a> instead of <a href="http://docs.jquery.com/Traversing/parent" rel="nofollow">parent()</a>:</p> <pre><code>$(document).ready(function(){ $(".remove-link").click(function() { $(this).parents(".number-row").eq(0).hide(); }) }) </code></pre>
Trying to figure out how to set off an event when the enter key is pressed in a TextBox <p>The code I'm playing with is:</p> <pre><code>open System open System.Windows.Forms open System.Drawing let tehform = new Form(Text = "STOP!", Width = 200, Height = 200) let awe = new TextBox(Left = 1, Top = 30, Width = 100) let stuff _ _ = MessageBox.Show(awe.Text) |&gt; ignore let handler = new EventHandler(stuff) let yeah = new Button(Text = "", Left = 20, Top = 60, Width = 80) yeah.Click.AddHandler(handler) let ms = new MenuStrip() let file = new ToolStripDropDownButton("File") let ddi = file.DropDownItems.Add("Hi") ddi.Click.AddHandler(handler) |&gt; ignore ms.Items.Add(file) |&gt; ignore let dc c = (c :&gt; Control) tehform.Controls.AddRange([| dc yeah; dc ms; dc awe |]) </code></pre> <p>I thought, by looking at the library, I could use awe.OnEnter.AddHandler(handler) but that didn't work either. Thanks for the help!</p>
<p>OnEnter fires when the TextBox gets focus. Use the OnKeyDown event and check the Keys property of the event args.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown(VS.80).aspx" rel="nofollow">Here's the MSDN documentation</a>.</p>
Will Server.Transfer work across AppDomains/Web Applications? <p>If you have two applications residing on the same server, can you use Server.Transfer to load a page in a different AppDomain/Application?</p> <p>My guess is no, because Server.Transfer() copies HttpContext.Items, among other things. To copy this data between AppDomains, would cause threading and memory sharing concerns a in a world were thread isolation is strictly enforced. </p> <p>Thoughts?</p>
<p>Nope, it's not possible.</p> <p><code>Server.Transfer</code> and <code>Server.Execute</code> cannot be used in these scenarios.</p> <p>It does not, however, copy the <code>HttpContext.Items</code>. It's not copied. The same <code>HttpContext</code> is reused.</p>
Using ActiveRecord/NHibernate, can I Delete and Refresh without a Flush? <p>I have the following Unit Test method:</p> <pre><code>void TestOrderItemDelete() { using (new SessionScope()) { var order = Order.FindById(1234); var originalItemCount = order.OrderItems.Count; Assert.IsTrue(originalCount &gt; 0); var itemToDelete = order.OrderItems[0]; itemToDelete.DeleteAndFlush(); // itemToDelete.Delete(); order.Refresh(); Assert.AreEqual(originalCount - 1, order.OrderItems.Count); } } </code></pre> <p>As you can see from the comment after the DeleteAndFlush command, I had to change it from a simple Delete to get the Unit test to pass. Why is this? The same is not true for my other unit test for adding an OrderItem. This works just fine:</p> <pre><code>void TestOrderItemAdd() { using (new SessionScope()) { var order = Order.FindById(1234); var originalItemCount = order.OrderItems.Count; var itemToAdd = new OrderItem(); itemToAdd.Order = order; itemToAdd.Create(); // Notice, this is not CreateAndFlush order.Refresh(); Assert.AreEqual(originalCount + 1, order.OrderItems.Count); } } </code></pre> <p>All of this came up when I started using Lazy Instantiation of the Order.OrderItems relationship mapping, and had to add the using(new SessionScope) block around the test.</p> <p>Any ideas?</p>
<p>This is difficult to troubleshoot without knowing the contents of your mappings, but one possibility is that you have the ID property of the OrderItem mapped using an identity field (or sequence, etc.) in the DB. If this is the case, NHibernate must make a trip to the database in order to generate the ID field, so the OrderItem is inserted immediately. This is not true of a delete, so the SQL delete statement isn't executed until session flush.</p>
How to bring files in a filesystem in/out MySQL DB? <p>The application that I am working on generates files dynamically with use. This makes backup and syncronization between staging,development and production a real big challenge. One way that we might get smooth solution (if feasable) is to have a script that at the moment of backing up the database can backup the dynamically generated files inside the database and in restore time can bring those file out of the database and in the filesystem again.</p> <p>I am wondering if there are any available (pay or free) application that could be use as scripts to make this happen. </p> <p>Basically if I have</p> <pre><code>/usr/share/appname/server/dynamicdir /usr/share/appname/server/otherdir/etc/resource.file </code></pre> <p>Then taking the examples above and with the script put them on the mysql database.</p> <p>Please let me know if you need more information.</p>
<p>Do you mean that the application is storing a files as blobs in the MySQL database, and/or creating lots of temporary tables? Or that you just want temporary files - themselves unrelated to a database - to be stored in MySQL as a backup?</p> <p>I'm not sure that trying to use MySQL as an net-new intermediary for backups of files is a good idea. If the app already uses it, thats one thing, if not, MySQL isn't the right tool here.</p> <p>Anyway. If you are interested in capturing a filesystem at point-in-time, the answer is to utilize <a href="http://tldp.org/HOWTO/LVM-HOWTO/snapshots_backup.html" rel="nofollow">LVM snapshots</a>. You would likely have to rebuild your server to get your filesystems onto LVM, and have enough free storage there for as many snapshots as you think you'd need.</p> <p>I would recommend having a new mount point just for this apps temporary files. If your MySQL tables are using InnoDB, a simple script to run mysqldump --single-transaction in the background, and then the lvm snapshot process, you could get these synced up to less then a second.</p>
Is there a Windows command shell that will display Unicode characters? <p>Assuming I have fonts installed which have the appropriate glyphs in them, is there a command shell for Windows XP that will display Unicode characters? At a minimum, two things that should display Unicode correctly:</p> <ul> <li>Directory listings. I don't care what I have to type (dir, ls, get-childitem, etc.), so long as files with Unicode characters in their names appear with the right glyphs, not the unprintable character box.</li> <li>Text file content listings. Again, doesn't matter to me if it's 'less', 'more', 'cat', 'dog', etc., so long as the characters are printed. I recognize that this is more complicated because of character encoding of the file, so if I have to specify that on the command line that's fine with me.</li> </ul> <p>Here's what I've tried so far:</p> <ul> <li>cmd.exe</li> <li>Windows PowerShell; including the multilingual version.</li> <li>Cygwin bash</li> </ul> <p>No luck. I even tried installing <a href="http://blogs.msdn.com/powershell/archive/2006/10/16/Windows-PowerShell-Font-Customization.aspx">custom fonts for cmd/PowerShell</a>. PowerShell and cmd.exe seem to be Unicode-aware in the sense that I can copy/paste the non-printable box out of there and it will paste into other apps with the correct characters. Cygwin (?) seems to convert to the ? character and that comes through in the copy/paste.</p> <p>Any ideas?</p>
<p>To do this with <em>cmd.exe</em>, you'll need to use the console properties dialog to switch to a Unicode TrueType font.</p> <p>Then use these commands:</p> <pre><code> CHCP 65001 DIR &gt; UTF8.TXT TYPE UTF8.TXT </code></pre> <p>Commands:</p> <ul> <li>Switch console to UTF-8 (65001)</li> <li>Redirect output of DIR to <em>UTF8.TXT</em></li> <li>Dump UTF-8 to console</li> </ul> <p>The characters will still need to be supported by the font to display properly on the console.</p> <p><a href="http://illegalargumentexception.blogspot.com/2009/04/i18n-unicode-at-windows-command-prompt.html">I18N: Unicode at the Windows command prompt (C++; .Net; Java)</a></p>
Avoiding Inheritance Madness <p>So, I have an API that I need to implement in to an existing framework. This API manages interactions with an external server. I've been charged with coming up with a way to create an easily repeatable "pattern," so that if people are working on new projects in the given framework they have a simple solution for integrating the API. </p> <p>My first idea was to create a class for your "main" class of the framework to extend that, would provide all the virtual functions necessary to interact with the API. However, my boss vetoed this, since the existing framework is "inheritence heavy" and he wants to avoid adding to the madness. I obviously can't incapsulate my API, because that is what the API itself is supposed to be doing, and doing so might hide functionality. </p> <p>Short of asking futures developers to copy and paste my example, what do I do? </p>
<p>If your boss is hostile to inheritance, try aggregation. (<em>Has-a</em> relationships rather than inheritance's <em>is-a</em> relationship.) Assuming you interface with the API in question via an object, maybe you can just keep that object in a property of your framework 'main' class, so you'd interact with it like <code>main-&gt;whateverapi-&gt;doWhatever()</code>. If the API isn't object-implemented or you need to load a lot of functionality specific to your environment onto it, that points toward making your own class that goes into that role and relates to the third party API however it needs to. Yeah, this basically means you're building an API to the API. Aggregation allows you to avoid the masking-functionality problem, though; even if you do have to do an intermediary layer, you can expose the original API as <code>main-&gt;yourobject-&gt;originalapi</code> and not have to worry about inheritance mucking things up.</p>
Is this legal? (GPL Software / Licensing Issues) <p>I work for a software / design firm and I recently found out that our "in house" CMS is actually <a href="http://modxcms.com/">MODx</a> that has been re-skinned by one of our designers. MODx is licensed under the <a href="http://www.gnu.org/licenses/gpl-2.0.html">GPL Ver 2.</a>. I would like to know if it is ethical / legal to be selling this to clients. </p> <p>We also offer another package that is actually <a href="http://sourceforge.net/projects/zencart/">ZenCart</a>, is this legal as well?</p> <p>I thought that software for commercial applications needed to be LGPL, are these applications being used "commercially"? We are certainly selling them to clients, while acting like they were developed in house...</p> <p>I'd love to hear your thought / clarifications on this topic, I for one find it at least unethical. What do you think?</p>
<p>Don't act on any legal advice you read on a forum like StackOverflow -- including mine. :-)</p> <p>Here's a <a href="http://en.wikipedia.org/wiki/GPL#Terms_and_conditions">passage</a> about GPL from Wikipedia (emphasis mine):</p> <blockquote> <p>The terms and conditions of the GPL are available to anybody receiving a copy of the work that has a GPL applied to it ("the licensee"). Any licensee who adheres to the terms and conditions is given permission to modify the work, as well as to copy and redistribute the work or any derivative version. The licensee is <strong>allowed to charge a fee for this service,</strong> or do this free of charge. This latter point distinguishes the GPL from software licenses that prohibit commercial redistribution. The FSF argues that free software should not place restrictions on commercial use, and the GPL explicitly states that GPL works <strong>may be sold at any price.</strong></p> </blockquote> <p>However, if your company is distributing the software under another license not compatible with GPL, then they're violating their license.</p> <p><a href="http://sourceforge.net/projects/zencart/">ZenCart</a> is also licensed under GPL, so the same restrictions apply.</p>
In Ruby, how does one get their IP octet without going through DNS? <p>I can, on some of my systems, get my IP address (192.68.m.n format) by doing this:</p> <pre><code>addr = IPSocket::getAddress(Socket.gethostname()) </code></pre> <p>...the trouble is that this only works if the name the local machine uses for itself is the name the DNS server associates with it.</p> <p>How *&amp;#( hard can it be for ruby to just return its primary interface's IP address? I have to do this in a platform-independant way or I'd just call ifconfig or ipconfig and parse it.</p>
<p>See <a href="http://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails">this question</a>. Also <code>see Socket.getaddrinfo()</code></p>
What do you consider before refactoring code? <p>I've got an application that just shipped. Since I wrote it, I've learned about amfphp and propel. Both would be 'nice' to be used in the application but I can't say that it would be required at this point.</p> <p>What types of things do you consider before you refactor code?</p>
<p>Have unit tests to check the code after refactoring. </p>
How do I write ints out to a text file with the low bits on the right side (Bigendian) <p>By default the BinaryWriter class writes int values with the low bits on the left (e.g. (int)6 becomes 06 00 00 00 when the resulting file is viewed in a hex editor). I need the low bits on the right (e.g. 00 00 00 06). </p> <p>How do I achieve this?</p> <p>EDIT: Thanks strager for giving me the name for what I was looking for. I've edited the title and tags to make it easier to find.</p>
<p>Jon Skeet has an EndianBitConverter <a href="http://www.pobox.com/~skeet/csharp/miscutil/" rel="nofollow">here</a> that should do the job. Just use big/little endian as desired. Alternatively, just shift the data a few times ;-p</p> <pre><code> int i = 6; byte[] raw = new byte[4] { (byte)(i &gt;&gt; 24), (byte)(i &gt;&gt; 16), (byte)(i &gt;&gt; 8), (byte)(i)}; </code></pre>
Can you nest html forms? <p>Is it possible to nest html forms like this</p> <pre><code>&lt;form name="mainForm"&gt; &lt;form name="subForm"&gt; &lt;/form&gt; &lt;/form&gt; </code></pre> <p>so that both forms work? My friend is having problems with this, a part of the <code>subForm</code> works, while another part of it does not.</p>
<p>In a word, no. You can have several forms in a page but they should not be nested.</p> <p>From the <a href="https://www.w3.org/TR/html5/forms.html#the-form-element">html5 working draft</a>:</p> <blockquote> <p><strong>4.10.3 The <code>form</code> element</strong></p> <p><strong>Content model:</strong></p> <p>Flow content, but with no form element descendants.</p> </blockquote>
Returning Array Fragments <p>I need to get array fragments from an array. I'm sick of using Array.Copy(). new ArraySegment(..).Array returns the original [full] array. The one below is what I came up with but I feel it's pretty lame. Is there a better way to do this?</p> <p><code></p> <pre><code>class Program { static void Main(string[] args) { var arr = new ArraySegment&lt;byte&gt;(new byte[5] { 5, 4, 3, 2, 1 }, 0, 2).ArrayFragment(); for (int i = 0; i &lt; arr.Length; i++) Console.WriteLine(i); Console.Read(); } } static class Extensions { public static T[] ArrayFragment&lt;T&gt;(this ArraySegment&lt;T&gt; segment) { var arr = new T[segment.Count]; Array.Copy(segment.Array, segment.Offset, arr, 0, segment.Count); return arr; } } </code></pre> <p></code></p> <p>Thanks in advance.</p> <p>Update: The above was just an example.<br /> I have a method: byte [] CalculateXXX(byte [] key, byte [] message); I do array manipulations inside this method. I want to return portion of an array. ArraySegment does not implement IEnumerable and it does NOT return an array with just the segment new ArraySegment(arr...).Array returns the complete original array.</p> <p><code></p> <p>var rval = new byte[4]; //new ArraySegment(finalOutputBuffer, 0, 4).SegmentedArray(); Array.Copy(finalOutputBuffer, 0, rval, 0, 4);</p> <p></code></p> <p>I find I had to do the above to return a array fragment. Was just wondering if there's a better way of returning fragments of an array [as new array].</p>
<p>Vyas, I am <em>truly</em> sorry for having posted this useless pile of <code>****</code>. It's been ages since I've actually used <code>ArraySegment</code> and I simply assumed that it implemented a (more or less) consistent interface. Someone (Jon?) please tell me which drugs were used during the implementation of this useless struct.</p> <p>Finally, to make a long story short, the best solution is probably to implement your own version of <code>ArraySegment</code>, only doing it right.</p> <p><del>I don't understand your problem with using <code>ArraySegment</code>. There's no additional overhead involved here, if that's what you mean, since no copying of the original data is done. Rather, <code>ArraySegment</code> offers a lightweight view on the data.</p> <p>Th make this work, change your (return) type from <code>T[]</code> to <code>IEnumerable&lt;T&gt;</code>, or, if you need indexed access, to <code>IList&lt;T&gt;</code>. Generally prefer using interface types in method signatures, and completely avoid array types. The rationale is very simple: it makes problems such as yours go away and makes the interface more flexible and future-proof. It also provides better information hiding since it hides parts of the implementation which aren't relevant for the consumer of this method.</del></p>
How do I handle Security between two Grails apps? <p>If I have two separate Grails apps running on the same app server (Tomcat/Glassfish), how do I allow the user to log into the first app then have him authenticated for the second app so he's not prompted when he goes to that app?</p>
<p>IMO the best way to go for it is to implement a federated login server. For example <a href="http://www.ja-sig.org/products/cas/" rel="nofollow">CAS</a> (Central Authentication Service) which is a Web Single Sign-On solution. This would also allow to integrate application running on different app servers/machines.</p>
Fade in each element - one after another <p>I am trying to find a way to load a JSON page to display my content, which I currently have. But I am trying to fade in each element one after another? Is anyone familiar with a way to do that?</p> <p>Fade in each element with a slight delay?</p> <p>Here is an example of my code, I am using the jquery framework.</p> <p>CODE: <a href="http://pastie.org/343896">http://pastie.org/343896</a></p>
<p>Let's say you have an array of span elements:</p> <pre><code>$("span").each(function(index) { $(this).delay(400*index).fadeIn(300); }); </code></pre> <p><em>(quick note: I think you need jQuery 1.4 or higher to use the .delay method)</em></p> <p>This would basically wait a set amount of time and fade each element in. This works because you're multiplying the time to wait by the index of the element. The delays would look something like this when iterating through the array:</p> <ul> <li>Delay 400 * 0 (no delay, just fadeIn, which is what we want for the very first element)</li> <li>Delay 400 * 1</li> <li>Delay 400 * 2</li> <li>Delay 400 * 3</li> </ul> <p>This makes a nice "one after the other" fadeIn effect. It could also be used with slideDown. Hope this helps!</p>
How to get the path to the current template in Joomla 1.5? <p>I'm writing a component and would like to insert images from the template folder.</p> <p>How do you get the correct path to the template folder?</p>
<p>IIRC, the $mainframe global object is eventually going away. Here is a way to do it through the framework:</p> <pre><code>$app = JFactory::getApplication(); $templateDir = JURI::base() . 'templates/' . $app-&gt;getTemplate(); </code></pre>
How do you use the Apache "ScriptInterpreterSource Registry-Strict" directive? <p>i run Apache web server on windows in order to work on some Perl CGI scripts. in production these scripts run on a linux box, and in the source code repository they all have shebangs like: <code>#!/usr/bin/perl</code>, but on my windows machine the shebangs would be <code>#!c:\perl\bin\perl.exe</code>, so i have a conflict with the source code base.</p> <p>enter the Apache <em>ScriptInterpreterSource</em> directive. </p> <p>i've been trying to make it work, based on what i can google. but so far no luck. i have:</p> <ol> <li><p>added these things to the appropriate directive AllowOverride None<br /> Options Indexes FollowSymLinks ExecCGI Order allow,deny Allow from all ScriptInterpreterSource Registry-Strict</p></li> <li><p>added: AddHandler cgi-script .cgi </p></li> <li><p>edited my registry and added a new String to </p></li> </ol> <blockquote> <pre><code>HKEY_CLASSES_ROOT\.cgi\Shell\ExecCGI\Command=C:\Perl\bin\perl.exe </code></pre> </blockquote> <p>now, i know that CGIs work on this server as long as they have the right shebang. </p> <p>but when i try to access a CGI without a shebang the apache log spits out: </p> <blockquote> <p>No Exec CGI Verb found for files of type '.cgi'</p> </blockquote> <p>any thoughts, insights, or even wild-ass guesses would be appreciated. </p> <p>thanks.</p>
<p>It sounds like the ScriptInterpreterSource line is being ignored. If it's set to Registry or Registry-Strict, it should ignore the shebang lines and use the registry <strong>only</strong>.</p> <p>Also, the <a href="http://httpd.apache.org/docs/2.2/mod/core.html#scriptinterpretersource">Apache 2.2 docs</a> have a slightly different location for the registry key:</p> <pre><code>HKEY_CLASSES_ROOT\.cgi\Shell\ExecCGI\Command\(Default) =&gt; C:\Perl\bin\perl.exe -wT </code></pre>
Dired copy asynchronously <p>Is there a way to modify/tell dired to copy files asynchronously? If you mark multiple files in dired and then use 'C' to copy them, emacs locks up until every file is copied. I instead want this copy to be started, and for me to continue editing as it goes on in the background. Is there a way to get this behaviour?</p> <p>EDIT: Actually, C calls 'dired-do-copy' in dired-aux, not in dired itself. Sorry for any confusion.</p>
<p>I think emacs is mostly limited to a single thread - so this may not be directly possible through standard dired commands such as 'C' copy. </p> <p>However, there is a dired command "<a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Shell-Commands-in-Dired.html" rel="nofollow">dired-do-shell-command</a>" which calls out to a shell to do the work in the background. If you select the files you want to copy and then use key '!' (this runs dired-do-shell-command) then type 'cp ? [destination]' (possibly can use 'copy' if you are on windows). I haven't tested this - so see help on "dired-do-shell-command" for full details.</p>
Deploy ClickOnce application using HttpWebRequest <p>I'm trying to launch my ClickOnce application using C# code with HttpWebRequest class. The application can be deployed fine using IE. But when doing the deployment with my code, it seems only the .application file is downloaded to client.</p> <p>My code is as below.</p> <pre><code> HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create("http://localhost/test/test.application"); getRequest.Method = "GET"; getRequest.Timeout = 500000; //default is 100 seconds HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse(); string loginUrl = getResponse.ResponseUri.AbsoluteUri; StreamReader responseReader = new StreamReader(getResponse.GetResponseStream()); string responseData = responseReader.ReadToEnd(); responseReader.Close(); </code></pre> <p>Is there anything I'm doing wrong with my code?</p> <p>Thanks! - Bruce</p>
<p>I believe that there's something special that IE does when it sees a .application file. That's why ClickOnce deploys didn't work from FireFox until .NET 3.5 SP1 added a handler for it. So what you're seeing would be the correct behaviour - your app is purely pulling down the file as a stream of bytes - it doesn't know what to do with it.</p> <p>If you want to programatically launch the application, I'd suggest this instead:</p> <pre><code>System.Diagnostics.Process.Start("http://localhost/test/test.application"); </code></pre> <p><strong>Update</strong></p> <p>There's a bit more information about the whole ClickOnce/FireFox thing <a href="http://blogs.msdn.com/saurabh/archive/2006/03/02/541988.aspx" rel="nofollow">here</a>. Apparently a MIME-type handler is installed for IE which recognizes the application/-ms-application type and runs the file with the ClickOnce installer. It may be worth checking out some of the old FireFox add-ons that enabled this prior to .NET 3.5 SP1 and see what they did to launch the .application file programatically.</p>
How to get SSL+mod_rewrite+Zend Framework MVC working together? <p>So, I got ZF MVC site and want to force SSL connection on everything under my /checkout/ I tried using mod_rewrite for that, so my .htaccess would look like this:</p> <pre><code>RewriteEngine on RewriteRule (\/checkout.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R] RewriteRule !\.(js|ico|gif|jpg|png|css|swf|xml|avi|flv|mov|mp3|wav)$ index.php [L] </code></pre> <p>Sure enough, it does kick in SSL, but second rule, that's ZF specific and redirects everything to index.php sorta erases the protocol specification.</p> <p>Unfortunately my level of proficiency with mod_rewrite is stupendously terrible. Maybe someone could help me out to solve this? </p>
<p>Tim Lytle's answer is mostly there.</p> <p>I'd change it be a little more strict in checking HTTPS and the flags need a delimiter.</p> <pre><code>RewriteCond %{HTTPS} !^on$ RewriteRule ^/checkout/? https://%{HTTP_HOST}%{REQUEST_URI} [R,L] RewriteRule !\.(js|ico|gif|jpg|png|css|swf|xml|avi|flv|mov|mp3|wav)$ index.php [L] </code></pre>
How can I get the number of pages in a PDF file in Perl? <p>Is there any Perl script to read multiple PDF files and get the number of pages in it?</p> <p>By using PDFlib or pdftet.</p>
<p>How about just using Perl with the PDF::API2?</p> <pre><code>#!/usr/bin/perl use PDF::API2; foreach $doc (@ARGV) { $pdf = PDF::API2-&gt;open($doc); $pages = $pdf-&gt;pages; $totalpages += $pages; print "$doc contains $pages pages\n"; } print "Total pages of pdf pages = $totalpages\n"; </code></pre>
How to customize date format when creating excel cells through javascript (activexobject)? <p>I'm trying to convert an HTML table to Excel in Javascript using new <code>ActiveXObject("Excel.application")</code>. Bascially I loop through table cells and insert the value to the corresponding cell in excel:</p> <pre><code>//for each table cell oSheet.Cells(x,y).value = cell.innerText; </code></pre> <p>The problem is that when the cell is in date format of 'dd-mm-yyyy' (e.g. 10-09-2008), excel would read as 'mm-dd-yyyy' (i.e. 09 Oct 2008). I tried to specify <code>NumberFormat</code> like:</p> <pre><code>oSheet.Cells(x,y).NumberFormat = 'dd-mm-yyyy'; </code></pre> <p>But it has no effect. It seems that this only affect how excel <strong>display the value, not parse</strong>. My only solution now is to swap the date like:</p> <pre><code>var txt = cell.innerText; if(/^(\d\d)-(\d\d)-\d\d\d\d$/.test(txt)) txt = txt.replace(/^(\d\d)-(\d\d)/,'$2-$1'); </code></pre> <p>But I'm worrying that it is not generic and a differnt machine setting would fail this.</p> <p>Is there a way to specific how excel <strong>parse</strong> the input value?</p>
<p>In Vbscript, we use to resolve this by</p> <pre><code> If IsDate ( Cell.Value ) Then Cell.Value = DateValue ( Cell.Value ) End If </code></pre> <p>Maybe, In java script also you need to play with same approach.</p>
Programatically execute a SPAN's Class from DOM Element? <p>This is a .NET program, and I am accessing the <code>HTMLElements</code> individually. There are pieces of markup that have a "More..." / "Less..." in a SPAN tag, that when Clicked will show more/less of the preceding content, </p> <p>A code snippet:</p> <pre class="lang-html prettyprint-override"><code>&lt;dd&gt; Product Manager, Business Analysis &amp; Web Design Manager, Global Portals at Dun &amp; Bradstreet &lt;span class="toggle-show-more"&gt; less...&lt;/span&gt; &lt;/dd&gt; </code></pre> <p>The "less.." is click-able, which then invokes something to display less text. I would like to do the same from an HtmlElement programatically.</p> <p>And, some Command window output from Visual Studio: </p> <p>OuterHtml: "</p> <pre class="lang-html prettyprint-override"><code>&lt;DD collapsed="False"&gt;Product Manager, Business Analysis &amp;amp; Web Design Manager, Global Portals at Dun &amp;amp; Bradstreet " OuterText: "Product Manager, Business Analysis &amp; Web Design Manager, Global Portals at Dun &amp; Bradstreet " </code></pre> <p>I have tried: <code>elem.RaiseEvent("onlick")</code> and toggling the "collapsed" attribute.</p>
<p>How about adding an onclick to the span that disappears the dd? Something like:</p> <pre><code>onclick="this.parentNode.style.display='none'" </code></pre>
How to set selected index of dropdown to 0 when text of textbox is changed? <p>I am using a dropdown to populate a textbox. But if preferred value is not present in dropdown then user directaly enter value in that textbox. </p> <p>If user selects value from dropdown first and then he don't want that value and he types another text in that textbox then at this time the dropdown should be set to index 0 as user is typing another value.</p> <p>I used textchanged event of textbox but it is not working. Can anyone tell me how to write javascript for this? Thanks in advance.</p>
<p>This should work for you:</p> <pre><code>function ResetDropDown(id) { document.getElementById(id).selectedIndex = 0; } function ResetTextBox(id) { document.getElementById(id).value = ''; } &lt;select id="MyDropDown" onchange="ResetTextBox('MyTextBox');"&gt; &lt;option value="0"&gt;0&lt;/option&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt; &lt;input id="MyTextBox" type="text" onkeypress="ResetDropDown('MyDropDown');"/&gt; </code></pre>
How to force a redraw of my application's entry in the taskbar? <p>I have a Windows form application written in C#. I update the title of the form frequently, but there's a substantial lag between the title changing and the title dislayed in the taskbar being updated. </p> <p>What's a clean way to force an update / redraw of the task bar's entry for my program? Failing that, how can I force a redraw of the entire task bar?</p> <p>Elaboration: It turns out that the delay in updating the taskbar is fixed at about 100ms, however this seems to be a delay based on when the Form.Text was last modified. If you modify the text faster then that - say, every 10ms, the taskbar is not updated until the Form.Text has been left unchanged for at least ~100ms.</p> <p>OS: Vista 32.</p>
<p>Did you try to call Form.Refresh() after updating the title?</p> <p>Edit:</p> <p>If you are doing the title updates in a loop you might have to do something along the line of:</p> <pre><code> this.Invalidate(); this.Update(); Application.DoEvents(); </code></pre>
How do I respond to mouse clicks on sprites in PyGame? <p>What is the canonical way of making your sprites respond to mouse clicks in PyGame ? </p> <p>Here's something simple, in my event loop:</p> <pre><code>for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() [...] elif ( event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]): for sprite in sprites: sprite.mouse_click(pygame.mouse.get_pos()) </code></pre> <p>Some questions about it:</p> <ol> <li>Is this the best way of responding to mouse clicks ? </li> <li>What if the mouse stays pressed on the sprite for some time ? How do I make a single event out of it ?</li> <li>Is this a reasonable way to notify all my sprites of the click ?</li> </ol> <p>Thanks in advance</p>
<p>I usually give my clickable objects a click function, like in your example. I put all of those objects in a list, for easy iteration when the click functions are to be called.</p> <p>when checking for which mousebutton you press, use the button property of the event.</p> <pre><code>import pygame from pygame.locals import * #This lets you use pygame's constants directly. for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: #Better to seperate to a new if statement aswell, since there's more buttons that can be clicked and makes for cleaner code. if event.button == 1: for object in clickableObjectsList: object.clickCheck(event.pos) </code></pre> <p>I would say this is the recommended way of doing it. The click only registers once, so it wont tell your sprite if the user is "dragging" with a button. That can easily be done with a boolean that is set to true with the MOUSEBUTTONDOWN event, and false with the MOUSEBUTTONUP. The have "draggable" objects iterated for activating their functions... and so on.</p> <p>However, if you don't want to use an event handler, you can let an update function check for input with:</p> <pre><code>pygame.mouse.get_pos() pygame.mouse.get_pressed(). </code></pre> <p>This is a bad idea for larger projects, since it can create hard to find bugs. Better just keeping events in one place. Smaller games, like simple arcade games might make more sense using the probing style though.</p>
Server session <p>if I open a connection to the server from firefox browser, and then I open a new tab within the same instance of browser to make a connection to the server, is it considered one session to server or considered as two diff sessions?</p> <p>Thanks</p>
<p>It's the same session (you can easily test this out yourself).</p>
Speeding up text output on Windows, for a console <p>We have an application that has one or more text console windows that all essentially represent serial ports (text input and output, character by character). These windows have turned into a major performance problem in the way they are currently code... we manage to spend a very significant chunk of time in them.</p> <p>The current code is structured by having the window living its own little life, and the main application thread driving it across "SendMessage()" calls. This message-passing seems to be the cause of incredible overhead. Basically, having a detour through the OS feels to be the wrong thing to do.</p> <p>Note that we do draw text lines as a whole where appropriate, so that easy optimization is already done. </p> <p>I am not an expert in Windows coding, so I need to ask the community if there is some other architecture to drive the display of text in a window than sending messages like this? It seems pretty heavyweight.</p> <p>Note that this is in C++ or plain C, as the main application is a portable C/C++/some other languages program that also runs on Linux and Solaris.</p> <p>We did some more investigations, seems that half of the overhead is preparing and sending each message using SendMessage, and the other half is the actual screen drawing. The SendMessage is done between functions in the same file...</p> <p>So I guess all the advice given below is correct:</p> <ul> <li>Look for how much things are redrawn</li> <li>Draw things directly </li> <li>Chunk drawing operations in time, to not send every character to the screen, aiming for 10 to 20 Hz update rate of the serial console.</li> </ul> <p>Can you accept ALL answers?</p>
<p>You should try profiling properly, but in lieu of that I would stop worrying about the SendMessage, which almost certainly not your problem, and think about the redrawing of the window itself.</p> <p>You describe these are 'text console windows', but then say you have multiple of them - are they actually Windows Consoles? Or are they something your application is drawing?</p> <p>If the latter, then I would be looking at measuring my paint code, and whether I'm invalidating too much of a window on each update.</p>
How to connect to a Oracle Database from Web Services Published on IIS <p>The situation is this:<br /> 1. Oracle database 10g on one server. Configured to accept connections.<br /> 2. Web service on different server (IIS), connecting to the database. This doesn't work.<br /> 3. Same web services running on the VS 2005 web server, work without a problem and can connect to the database. </p> <p>The problem: Do not know what is the issue with web services published on IIS in respect to connect to Oracle 10g when the same services, running on VS 2005 web server work without the problem.</p> <p>Error returned: Oracleclient connection timedout.</p>
<p>So the database is on machine A and the web server that cannot connect is on machine B.</p> <p>Where is the web server that can connect? If it is not on machine B, then what are the differences in network location/configuration between these two machines?</p> <p>On machine B, can you telnet to the Oracle server on Oracle's listener port?</p>
How to use PhotoLibrary without jailbreak <p>This is nice thing you have done. Could you please explain: How to use PhotoLibrary's CameraController without jailbreak. Actually I 've downloaded class-dump and tried dumping PhotoLibrary but did not work out well. It is giving: </p> <pre><code>/* * Generated by class-dump 3.1.2. * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2007 by Steve Nygard. */ </code></pre> <p>This file does not contain any Objective-C runtime information.</p> <p>So, I wanted to know how to dump it and use it in xcode.</p>
<p>a) You can't use PhotoLibrary directly because it's not part of the iPhone SDK. That's presumably what you mean by "without jailbreak"</p> <p>b) Who's Mark and what has he done?</p>
RegEx and matching codes right to left <p>Stuggling a little bit with the RegEx, I've got 4 codes in a string</p> <p>CODE4:CODE3:CODE2:CODE1</p> <p>each code is optional apart from CODE1</p> <p>So I could have ab:bc:de:fg</p> <p>or</p> <p>bc::fg</p> <p>of </p> <p>ab:::fg</p> <p>In each case of the above CODE1 = fg dnd for the dear life of me I can't work out the RegEX</p> <p>Would be easy to do as a standard string parse, but unforunatly because of buisness objects in needs to be done via regex :-( and return via a vb.net RegEX.matche,groups("Code1") fg (I hope that makes sense)</p> <p>Thanks in advance for any help</p> <p>Ended up with a bit of RegEx that does the job, bit messy but it works</p> <pre><code>(^(?&lt;code1&gt;[\w]*)$)|(^(?&lt;code2&gt;[\w]*):(?&lt;code1&gt;[\w]*)$)|(^(?&lt;code3&gt;[\w]*):(?&lt;code2&gt;[\w]*):(?&lt;code1&gt;[\w]*)$)|(^(?&lt;code4&gt;[\w]*):(?&lt;code3&gt;[\w]*):(?&lt;code2&gt;[\w]*):(?&lt;code1&gt;[\w]*)$) </code></pre> <p>Ta all</p>
<p>There's no need to use a regular expression here.</p> <p>I don't know what language you're using, but split the string on ':' and you'll have an array of codes.</p> <p>If you really just want to validate whether a string is valid for this then</p> <pre><code>/(\w*:){0,3}\w+/ </code></pre> <p>matches your description and the few examples you've given.</p>
Linq2Sql: Manage DataContext <p>In the following code doesn't work as </p> <pre><code>public void Foo() { CompanyDataContext db = new CompanyDataContext(); Client client = (select c from db.Clients ....).Single(); Bar(client); } public void Bar(Client client) { CompanyDataContext db = new CompanyDataContext(); db.Client.Attach(client); client.SomeValue = "foo"; db.SubmitChanges(); } </code></pre> <p>This doens't work, I get error msg. "An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported."</p> <p>How do you work with DataContexts throughout an application so you don't need to pass around a reference? </p> <p>What</p>
<p>They really mean it with 'This is not supported.'. Attaching to an object fetched from another data context is not implemented. </p> <p>There are a number of workarounds to the problem, the recommended way is by serializing objects, however this is not easy nor a clean approach.</p> <p>The most simple approach I found is to use a readonly DataContext for fetching objects like this:</p> <pre><code> MyDataContext dataContext = new MyDataContext() { DeferredLoadingEnabled = false, ObjectTrackingEnabled = false }; </code></pre> <p>The objects obtained from this context can be attached to another context but only applies to some scenarios.</p>
Pixel level 2D Graphics in Silverlight <p>I am trying to port a WebForms app to Silverlight, this application is using the GDI Graphics class to draw polygons to a in-memory bitmap, it will then do pixel by pixel comparisons so I need access to the pixel buffer.</p> <p>Example:</p> <pre> Graphics g = Graphics.FromImage(bmp); g.FillClosedCurve(brush, points, FillMode.Winding); </pre> <p>I have done some serious googling trying to figure out how to draw polygons and then be able to access the pixel buffer of the canvas surface. My findings indicate that this is not possible with the WPF silverlight graphics, so I need to use a custom graphics library but have only found some 3D libraries. Is there a simple 2D library for silverlight or should I just go a head and write a polygon render algorithm myself? </p>
<p>If you write a polygon rendering algorithm for Silverlight, it would have to be all managed code, I haven't seen any examples of this, but if you write one let me know, I've been looking for something like the for XNA. </p> <p>Silverlight 3 should be adding some of the things you need to make this a lot easier like rendering to a texture and accessing a bitmap at the pixel level.</p>
Python: single instance of program <p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
<p>The following code should do the job, it is cross-platform and runs on Python 2.4-3.2. I tested it on Windows, OS X and Linux.</p> <pre><code>from tendo import singleton me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running </code></pre> <p>The latest code version is available <a href="https://github.com/pycontribs/tendo/blob/master/tendo/singleton.py">singleton.py</a>. Please <a href="https://github.com/pycontribs/tendo/issues">file bugs here</a>.</p> <p>You can install tend using one of the following methods:</p> <ul> <li><code>easy_install tendo</code></li> <li><code>pip install tendo</code></li> <li>manually by getting it from <a href="http://pypi.python.org/pypi/tendo">http://pypi.python.org/pypi/tendo</a></li> </ul>
Network interface settings in embedded Windows XP <p>How can we get the network interface name (i.e. the one that appears in the "Network connections" dialog) given the device description (i.e. the string that appears in the "Device Properties -> Connect using:" textbox)?</p> <p>We must do it in pure C/C++ language, or through some of the standard command line tools (e.g. netsh, ipconfig...), or a combination of both.</p> <p>We CAN'T use the .NET API, because of deployment problems (the application must run on an XP embedded without .NET Framework).</p> <p>The SDK API GetIfTable and GetIfEntry seem promising, but on our system all the MIB_IFROW fields are filled correctly, except the "wszName" one, that remains uninitialized.</p>
<p>I was able to do this via the registry. Using GetAdaptersInfo(), which gives an IP_ADAPTER_INFO output, take the AdapterName string. This should be a GUID for the adapter. For (ipv4 at least), under HKLM\SYSTEM\CurrentControlSet\Control\Network{4D36E972-E325-11CE-BFC1-08002BE10318}\{*INSERT GUID HERE*}\Connection, the value <em>Name</em> should contain the "friendly" network name.</p>
Session not reinitialized after timeout? <p>I have this classic ASP site which has been working fine until we updated it. It was just a site-update, meaning .asp files which ran fine in our test enviroment, no service packs or patches. I can not reproduce the error at all on a test-site on the same server.</p> <p>The system it's running on is IIS6 on Server 2003.</p> <p>Somehow, it has now started to behave weird when a user revisit the site with an old session-cookie, which makes the site not running Session_OnStart() again. </p> <p>Since the session is long gone, it leaves me with an empty Session()-scope, which breaks a lot of code on the site.</p> <p>I have never seen this behaviour before, since I would assume that visiting a site with an old session-cookie would retrigger Session_OnStart?</p>
<p>It seems like our upgrade, which was a cache-functionality that stored data in the Application-scope somehow broke the session-handling.</p> <p>Even though the information regarding memory-limits for the Application- and Session-scope always says that it's resource-dependant, somehow using a lot of memory in the Application-scope breaks something. </p> <p>We're talking about around 100-200MB of data, when I store it in files instead the issue seems to go away silently. Leaving this answer for future references in similar cases.</p>
Team Foundation Server Source Control Structure <p>I have been working on standardizing the source control structure for our Team Foundation Server rollout for the new year. I have started by using the <a href="http://www.codeplex.com/BranchingGuidance">Microsoft Team Foundation Server Branching Guidance</a> documentation available on CodePlex.</p> <p>I was hoping to get some feedback and answers to a few of the specific questions I have about the proposed structure. When it comes to structuring source control in TFS, I have learned that there are so many "standards" to choose from that there is not really a standard.</p> <p>First, I will outline and describe the decisions and usage.</p> <pre><code>$/ {Team Project}/ {Subproject}/ Development/ Trunk/ Source/ Tests/ Sandcastle/ TeamBuildTypes/ {Build Name}/ Branches/ {Branch Name}/ Source/ Tests/ Sandcastle/ TeamBuildTypes/ {Build Name}/ Integration/ Source/ Tests/ Sandcastle/ TeamBuildTypes/ {Build Name}/ Production/ Releases/ {Release Version}/ Source/ Tests/ Sandcastle/ TeamBuildTypes/ {Build Name}/ Branches/ {Branch Name}/ Source/ Tests/ Sandcastle/ TeamBuildTypes/ {Build Name}/ </code></pre> <p>The general logic is that a Team Project can contain either a single logical project (where there would be no <code>{Subproject}</code> entry) or multiple related projects in the form of a product or tool suite. The three major containers are called <code>Development</code>, <code>Integration</code>, and <code>Production</code>.</p> <p>Within the <code>Development</code> container's Trunk, there are provisions for both the projects which make up the product in the <code>Source</code> folder, with corresponding unit tests available in the <code>Tests</code> folder. A majority of minor development would occur in the trunk, with branching available through the <code>Trunk</code> folder's sibling <code>Branches</code> folder, which acts as a branching container. One or more solution files would live within the <code>Trunk</code>, allowing for branches at that level to capture the solution, source, and unit tests.</p> <p>The <code>Integration</code> container, often called "main" in non-TFS implementation, is solely used to integrate Changesets from <code>Development</code> to create a stable and testable build. It is initially created as a branch from the <code>Development</code> container once a testable product has been attained. The builds from this container will be used for our testing environment and load testing environment. We choose to include load testing with testable builds so that we can monitor for changes in performance, being able to rapidly isolate Changesets that may have contributed to any irregularities.</p> <p><code>Production</code> is used to produce pre-production and production quality builds. It is initially created as a branch from the <code>Integration</code> container once a stable build has been recommended for release. Within the <code>Releases</code> folder, a "branch by release" structure is followed, providing snapshotting and isolation in a single place. (For example, when <code>Release 1.1</code> is ready for a pre-production build, the stable <code>Integration</code> container is branched into a new <code>Release 1.1</code> folder in the <code>Production/Releases</code> structure. Subsequent RCs and RTWs/RTMs are promoted into this folder, as well.) A branching structure is also present, as seen in the <code>Branches</code> container. This allows for "hotfixes", usually a revision marker (Major.Minor.Revision). The branch is created from the current release and merged back into the new revision marker - like <code>Release 1.1.1</code>. The Changeset would be reverse integrated to the <code>Development</code> container's <code>Trunk</code> upon acceptance.</p> <p>We feel that this structure is a fair balance between robustness and complexity. But there are a few nagging questions that I can not logically fit into the model. They are:</p> <p><strong>Team Build</strong> - The <code>Development</code> and <code>Integration</code> containers will initially start out as being nightly builds, eventually moving to Continuous Integration (CI). The Production container will be manually built.</p> <ul> <li><p><del>Where should the build definitions live?</del> <strong>Edit - Based upon a couple of responses, the TeamBuildTypes folder has been moved to the trunk and branched to the appropriate containers. This does, however, lead to a new question (follows).</strong></p></li> <li><p>By having the TeamBuildTypes folder in their appropriate containers, does that mean that all build definitions will be reproduced between the appropriate folders? For example, having a build definition for development quality builds, as well as testable builds, etc. all living in all TeamBuildType folders throughout the structure.</p></li> </ul> <p><strong>Documentation Generation</strong> - We use Sandcastle to generate documentation. Specifically, we also use <a href="http://www.codeplex.com/SHFB">Sandcastle Help File Builder</a> to manage the output. This produces a project file in a format specific to SFHB.</p> <ul> <li><p>Should generated documentation be stored in the source control structure?</p></li> <li><p>Should documentation be generated for each container, or does it only posses value for pre-production and production quality builds?</p></li> <li><p>To preserve fast local build times, should documentation creation be owned by a build definition?</p></li> <li><p><del>Where should the SHFB-specific files live? My initial inkling is to put it as a peer to the <code>Source</code> and <code>Tests</code> folders.</del> <strong><em>I agree with the recommondations that it be a peer to <code>Source</code> and <code>Tests</code>. Diagram changed to reflect this change.</em></strong></p></li> </ul> <p><strong>Third Party Binaries</strong></p> <ul> <li><p>Should binaries (controls, libraries, etc.) be stored in source control?</p></li> <li><p>If so, should it be it's own Team Project?</p></li> </ul> <p><strong>General Documentation</strong> - Non-generated documentation, such as requirements, design documents, test plans, etc. are not going to be reflected by a folder in the source control structure. After some research and discussion with my developers and peers, using the built-in Documents folder in Team Explorer provides more benefit, since it mirrors the structure within the Team Project Portal and some (business) users do not need the additional complexity of learning the source control aspect of TFS.</p> <p><hr /></p> <p>I will update the structure as I get answers to the questions to provide a clearer picture. I also welcome any other comments related to potential changes. If I have any other questions, I will make sure to modify this post.</p> <p><strong>Edits:</strong></p> <ul> <li><p><strong>Clarification. <code>Source</code> and <code>Tests</code> folders do live under the <code>Integration</code> container, as well.</strong></p></li> <li><p><strong>Both Micah and Josh brought up great points regarding third party binaries. Question added regarding the issue.</strong></p></li> <li><p><strong>Documentation generation can be slow. Question added regarding whether documentation creation should be owned by a specific Team Build Type.</strong></p></li> <li><p><strong>Added resolution related to non-generated documentation, such as requirements, design documents, test plans, etc.</strong></p></li> <li><p><strong>Added resolution related to TeamBuildTypes folder for build defintions.</strong></p></li> <li><p><strong>Based upon various feedback, moved the TeamBuildTypes folder to the trunk / branch levels.</strong></p></li> </ul>
<p>I like your idea of putting the Sandcastle files as a peer to Source and Tests, I would add a documentation folder, that would then contain the sandcastle files, and optionally the actual documentation.</p> <p>There are definetly differences of opinions and I'm sure I will be downvoted for this (since I have been before). I would put the generated documentation in TFS for a couple of reasons:</p> <ol> <li>Your going to want your documentation with each release, and using TFS is an easy aproach to ensure your documentation stays in the correct place.</li> <li>Using TFS to store it means everyone will know where to go get the documentation.</li> </ol> <p>One thing I don't see which I always struggle with is where to third party dependancies, it might be that they belong down under the source so they are with each project although if you wanted to share them accross projects you could add a new top level node.</p> <h1>Edit</h1> <p>For my binaries I usually end up with</p> <p>$/ThirdParty/Company/Product/Version/Src(optional)</p> <p>So for example I have </p> <p>$/ThirdParty/ Microsoft/ EntLib/ 3.1 4.0 ComponentArt/ WebUI/ 2008.1/ Src</p> <p>I like to add the source, I've had to patch CA's source which I hate to do but when a third party doesn't fix the bug you have to resort to this.</p>
ASP.NET MVC localization best practice? <p>I need help with the best practice to localize asp mvc apps, I saw Oxite having a base method named Localize in the BaseController, but is the Localization a task for the view or the Controller? Or should I use resx files / or use db tables?</p>
<p>Create your own Html helper and use it like <code>&lt;%= Html.Resource("Name") %&gt;</code> </p> <p>Details are in <a href="http://blog.eworldui.net/post/2008/05/ASPNET-MVC---Localization.aspx">blog</a> post.</p>
Reverting CSS style of <input type=submit button to its default style <p>I'm using a bookmarklet that inserts a script tag into the current web page.</p> <p>This script has some UI and an "<code>input type=submit....</code>" tag in it.</p> <p>Web page A has chosen not to style "<code>input type=submit..</code>" tags whereas web page B has styled them.</p> <p>This results in the bookmarklet displaying differently styled submit buttons based on the underlying page's style.</p> <p>I want the submit buttons to be styled identically on all web pages in <strong>its default manner</strong>.</p> <p>One solution is to set the CSS style for the submit button within my script so it shows up identically on all pages. (This is what I have done for all other tags).</p> <p>My question is: </p> <ol> <li>How do I set the CSS style for the submit button so it displays in a 'default manner' or ? </li> <li>Can one remove existing styling, and, if so, how for the button so that it displays in the 'default manner'?</li> </ol> <p>In other words, how can I have the submit buttons within the UI of my bookmarklet be displayed in the 'default manner' regardless of whether the underlying web page has chosen to style it or not?</p> <blockquote> <p>Note: By 'default manner' I mean the way the submit button is displayed when no styling is added to it. For example the 'Google search' or 'I'm feeling lucky' buttons on <a href="http://www.google.com" rel="nofollow">http://www.google.com</a>.</p> </blockquote>
<p>Taken from <a href="https://developer.mozilla.org/en/Common_CSS_Questions">Mozilla Developer Center</a></p> <blockquote> <p><strong>Restoring the default property value</strong> Because CSS does not provide a "default" keyword, the only way to restore the default value of a property is to explicitly re-declare that property. Thus, particular care should be taken when writing style rules using selectors (e.g., selectors by tag name, such as p) that you may want to override with more specific rules (such as those using id or class selectors), because the original default value cannot be automatically restored. Because of the cascading nature of CSS, it is good practice to define style rules as specifically as possible to prevent styling elements that were not intended to be styled.</p> </blockquote> <p>The only way you have is to set your own class on the button that is very explicit in its css rules: i.e </p> <pre><code>background-color:grey !important; </code></pre> <p>instead of </p> <pre><code>background:grey; </code></pre>
How can I read an XML file into a buffer in C? <p>I want to read an XML file into a <code>char *buffer</code> using C.</p> <p>What is the best way to do this?</p> <p>How should I get started?</p>
<p>Is reading the contents of the file into a single, simple buffer <em>really</em> what you want to do? XML files are generally there to be parsed, and you can do this with a library like <a href="http://xmlsoft.org/" rel="nofollow">libxml2</a>, just to give one example (but notably, is implemented in C).</p>
VSTO: Can't create workbooks <p>When I try to create a Excel or Word workbook project in VS, I get the message: </p> <blockquote> <p>A compatible version of Microsoft Office is not installed on this computer. You must install the version of Office that is compatible with your project. In addition, repair the version of the Visual Studio Tools for Office runtime that is appropriate for your project by running the installation program and selecting the Repair option. The runtime is available at the Microsoft Download Center.</p> </blockquote> <p>I have VS 2008 and Office 2003 Professional SP 3 installed. I did a full install of Office, and it looks like the Interop DLLs are in the GAC. I am creating an Office 2003 project. I tried the steps from <a href="http://stackoverflow.com/questions/274653/vsto-problem-cannot-create-visual-studio-excel-workbook-project">http://stackoverflow.com/questions/274653/vsto-problem-cannot-create-visual-studio-excel-workbook-project</a>. I repaired VS 2008 from the disk after installing Office 2003 Pro. I had Office 2003 Standard installed earlier, but I removed it before installing Office 2003 Pro. I am able to create add-ins. Any ideas? </p>
<p>Office 2k3 Standard is not compatible with VSTO; upgrading from 2k3 standard has likely left something in your registry. </p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/3f12200d-f685-4bc9-bff0-d380067f515a" rel="nofollow">This thread</a> suggests that even moving to 2k7 doesn't give compatibility in this case! How about creating a new user profile?</p>
Which JDBC jar should I use with java 1.5.0_16 and PostgreSQL 8.3.5? <p>Which JDBC jar should I use with java 1.5.0_16 and PostgreSQL 8.3.5?</p>
<p>Are you having an issue with the standard postgresql JDBC driver? I'm not using it right now, but I have in the past and it worked fine: <a href="http://jdbc.postgresql.org/" rel="nofollow">http://jdbc.postgresql.org/</a></p>
Ruby (Shoes) - Wait for function to return value <p>I have a function that presents the user a combo-box.</p> <pre><code>def select_interface(interfaces) list_box :items =&gt; interfaces do |list| interface = list.text end ### ideally should wait until interface has a value then: ### return interface end </code></pre> <p>The rest of the program depends on the selection from this combo-box.</p> <p>I would like to find a way to make ruby wait for the input from the combo-box and then carry executing the rest of the code.</p> <p>There is a similar function in <a href="http://shoooes.net" rel="nofollow">shoes</a> called <strong><a href="http://help.shoooes.net/Built-in.html#ask" rel="nofollow">ask</a></strong> that will wait for the input of the user.</p> <pre><code>interface = ask("write your interface here") </code></pre> <p>How can I implement this "wait until the variable has a value" function in Ruby/shoes?</p>
<p>It took me a while to understand your question :) I started writing a long answer about the entire theory of GUI applications. But you already have everything you need. The block that <a href="http://help.shoooes.net/ListBox.html" rel="nofollow">list_box</a> takes is really its change method. You're telling it what to do when it gets changed. Just defer the rest of the program to run when you get a value you want. </p> <pre><code>Shoes.app do interfaces = ["blah", "blah1", "blah2"] # proc is also called lambda @run_rest_of_application = proc do if @interface == "blah" do_blah # etc end @list_box = list_box(:items =&gt; interfaces) do |list| @interface = list.text @run_rest_of_application.call @list_box.hide # Maybe you only wanted this one time? end end </code></pre> <p>This is the basic idea behind all GUI applications: build the initial application then wait for "events", which will create new states for you respond to. In ruby-gnome2, for example, you would use a callback function/block with a <a href="http://ruby-gnome2.sourceforge.jp/hiki.cgi?Gtk%3A%3AComboBox" rel="nofollow">Gtk::ComboBox</a> that would change the state of your application. Something like this:</p> <pre><code># Let's say you're in a method in a class @interface = nil @combobox.signal_connect("changed") do |widget| @interface = widget.selection.selected rebuild_using_interface end </code></pre> <p>Even outside of a toolkit you can get a "free" events system using Ruby's <a href="http://www.ruby-doc.org/stdlib/libdoc/observer/rdoc/index.html" rel="nofollow">Observer module</a>. Hope this helped.</p>
How Do You Set a Textblock to Autosize to the Width of a TreeView? <p>I have a <code>TextBlock</code> that I need to autosize to the width of a <code>TreeView</code>. The <code>TreeView</code> and the <code>TextBlock</code> are both contained in a <code>StackPanel</code>. The <code>StackPanel</code> is inside an <code>Expander</code>. The width of the <code>TreeView</code> should drive the width of the other objects and I need the height of the <code>TextBlock</code> to change to display the full text. All my efforts have resulted in the <code>TextBlock</code> driving the width. Thanks!</p> <pre><code> &lt;Expander IsEnabled="True" HorizontalAlignment="Right" Margin="0,8,8,53" x:Name="ExpanderBookMarks" Width="Auto" Foreground="#FF625B5B" ExpandDirection="Down" IsExpanded="True" Header="Bookmarks" Visibility="Hidden"&gt; &lt;StackPanel Name ="StackPanelBookmark" Orientation="Vertical" Width="{wpf:Binding Path=Width, ElementName=trvBookmarks, Mode=Default}"&gt; &lt;TreeView x:Name="trvBookmarks" ItemsSource="{Binding}" ItemTemplateSelector="{StaticResource BookmarkTemplateSelector}" Margin="0,0,0,0" TreeViewItem.Selected="HandleTreeViewItemClick" AllowDrop="True"/&gt; &lt;TextBlock x:Name="TextBlockBookmarkDiscription" TextWrapping="Wrap" Foreground="AntiqueWhite" Background="Transparent" Width="150"&gt; This is the discription area and needs to be very long because the end user can put 400 charectors in. &lt;/TextBlock&gt; &lt;/StackPanel&gt; &lt;!--End of Dougs Treeview--&gt; &lt;/Expander&gt; </code></pre>
<p>Try this:</p> <pre><code>&lt;TextBlock Width="{Binding ElementName=trvBookmarks,Path=ActualWidth}" ... /&gt; </code></pre>
Getting a JSLint warning concerning labels in Javascript <p>In my javascript I have this</p> <pre><code> loopDeLoop: while (foo !== bar) { switch (fubar) { case reallyFubar: if (anotherFoo == anotherBar) { break loopDeLoop; } break; default: break; } } </code></pre> <p>But JSLint says... lint warning: use of label</p> <p>Here's the notes from <a href="http://www.jslint.com/lint.html" rel="nofollow">JSLint</a> </p> <blockquote> <p>Labels<br /> JavaScript allows any statement to have a label, and labels have a separate name space. JSLint is more strict.</p> <p>JSLint expects labels only on statements that interact with break: switch, while, do, and for. JSLint expects that labels will be distinct from vars and parameters.</p> </blockquote> <p>How do I construct the above to get rid of the warning?</p> <p>Thanks,<br /> Greg</p>
<p>You are using the label correctly. </p> <p>JSLint is throwing a warning because labels in Javascript are horribly bad style, and JSLint wants you to know that.</p> <p>To reiterate, if you use labels at all, even correctly, JSLint will give that warning.</p> <p>Edit: Looks like you might be able to disable the label warning with a <code>-use_of_label</code> configuration directive.</p>
C/objC/C++/Java compilers <p>I downloaded NetBeans (for first time) to use Java and found that it can handle C/C++ etc too. </p> <p>Wanted to know following --</p> <p>01- Is there any better C++ tool (IDE) other than NetBeans and MS Visual Studio? Better means very mature and popular (and free).</p> <p>02- What is the difference between GNU Java and Sun Java compilers?</p> <p>02- Is there any other popular C/ObjC/C++ complier out which is free, mature and popular?</p> <p>Thank you for the reply.</p>
<ol> <li>I have not seen nor heard of an IDE which would be superior to Visual Studio. However "superiority" is a rather subjective thing, so some people might like other IDE's better. In terms of age and popularity, I think Visual Studio will also win over all others out there. <s>Perhaps only Delphi can come close to it.</s> OOps, missed the line about C++. Then I don't know.</li> <li>The author?</li> <li>GCC might be more popular than Microsoft's C compiler due to it being ported to so many platforms, many of which has it as the only C compiler. Also noteworthy are Borland's compiler and Intel's compiler. Although I don't know which of them are free (except GCC and Microsoft).</li> </ol>