input
stringlengths
51
42.3k
output
stringlengths
18
55k
Counting rows in SQL stament using grouping by incremnental variables <p>Table I'm trying to get analytical result from is voice calls record. Each call (one row) has duration in seconds (just int value, not datetime). I'm trying to get number of records grouped by 15 seconds spans like this:</p> <pre><code>+-------------------+ |Period | Count | +-------------------+ | 0-15 | 213421 | |15-30 | 231123 | |30-45 | 1234 | +-------------------+ </code></pre> <p>Starts of period is 0, end is 86400.</p> <p>I've tried some combinations with setting variables for start and end and then incrementing them by 15, but i'm not very successful, and i can't understand what is going wrong.</p> <p>Please help out. Thank you!</p>
<p>The following query fits your needs:</p> <pre><code>SELECT (duration - duration % 15), COUNT(*) FROM call GROUP BY (duration - duration % 15) ORDER BY 1; </code></pre> <p>You can also add some string formatting, in case you need the output exactly as you described it:</p> <pre><code>SELECT (duration - duration % 15)::text || '-' || (duration - duration % 15 + 15)::text, COUNT(*) FROM call GROUP BY (duration - duration % 15) ORDER BY 1; </code></pre>
Entity Framework: Ignore Columns <p>I have a database that I wish to build an EF model from, however I do not want to include certain columns from the database as the columns concerned are maintained exclusively on the server and should not be manipulated by any application.</p> <p>Both of the columns are DateTime (if this makes any difference), one of the columns is nullable and is maintained by a trigger on updates and the other is not nullable and set using a default value in the table definition.</p> <p>I guess I am looking for something like the "Server Generated" option in Linq2Sql; but I cannot find such an option.</p> <p>Can anybody tell me how to work around this?</p> <p>Caveat:</p> <p>I have been trying to introduce business object modelling at my place of work for some years and it has always been rejected because of the amount of additional code that has to be hand-cranked. EF is currently being seen as a viable solution because of the designer and code generation therefore any option that involves hand-cranking the XML will only turn the rest of my colleagues away from EF. I am therefore looking for something that can be done either using the designer or using code.</p> <p><strong>EDIT:</strong></p> <p>I guess that what I am looking for here is either...</p> <p>(a) a way to create the model without EF referencing the columns in the store (ssdl) and therefore not looking to manipulate it in any way (b) a way to programatically set the "StoreGeneratedPattern" attribute against the property when I create the ObjectContext (the easy answer is to manually manipulate this in the .ssdl, but this would then be overwritten if I refreshed the model from the database and I cannot go down the route where the .csdl, .msl &amp; .ssdl are hand-cranked).</p>
<p>Can you do this with the Entity Framework? Yes; it's easy. Can you do this with the Entity Framework designer? Unfortunately, that is much harder.</p> <p>The problem you're having is that the column exists in the storage schema (SSDL) in your EDMX. Removing the column with the GUI designer simply removes it from the client schema, not the mapping or the storage schema. However, it's simple enough to go into the EDMX and remove it. Having done that, you can also remove it from the mapping in the client schema portions of the EDMX, and the entity framework will longer complain that it is unmapped.</p> <p>Problem solved, right?</p> <p>Well, no. When you use the GUI designer to update the EDMX from the database, the storage schema is thrown away and re-generated. So your column will come back. As far as I know, there is no way to tell the GUI designer to never map a particular column. So you will have to re-do this every time you update with the GUI designer. Fortunately, the EDMX is XML, so you can do this with a XML transform, LINQ, or the XML tool of your choice.</p>
Why is p2p web hosting not widely used? <p>We can see the growth of systems using peer to peer principles. But there is an area where peer to peer is not (yet) widely used: web hosting.</p> <p>Several projects are already launched, but there is no big solution which would permit users to use and to contribute to a peer to peer webhosting.</p> <p>I don't mean not-open projects (like Google Web Hosting, which use Google ressources, not users'), but open projects, where each user contribute to the hosting of the global web hosting by letting its ressources (cpu, bandwith) be available.</p> <p>I can think of several assets of such systems:</p> <ul> <li>automatic load balancing</li> <li>better locality</li> <li>no storage limits</li> <li>free</li> </ul> <p>So, why such a system is not yet widely used ?</p> <p><strong>EDIT:</strong> I think that the "97.2%, plz seed!!" problem occurs because all users do not seed all the files. But if a system where all users equally contribute to all the content is built, this problem does not occur anymore. Peer to peer storage systems (like Wuala) are reliable, thanks to that.</p> <p>The problem of proprietary code is pertinent, as well of the fact that an user might not know which content (possibly "bad") he is hosting. Thanks for your answers.</p> <p>I add another problem: the latency wich may be higher than with a dedicated server.</p> <p><strong>EDIT 2:</strong> The confidentiality of code and data can be achieved by encryption. For example, with Wuala, all files are encrypted, and i think there is no known security breach in this system (but i might be wrong).</p> <p>It's true that seeders would not have many benefits, or few. But it would prevent people from beeing dependent of web hosting companies. And such a decentralized way to host websites is closer of the original idea of the internet, i think.</p>
<p>This is what <a href="http://freenetproject.org/">Freenet</a> basically is,</p> <blockquote> <p>Freenet is free software which lets you publish and obtain information on the Internet without fear of censorship. To achieve this freedom, the network is entirely decentralized and publishers and consumers of information are anonymous. Without anonymity there can never be true freedom of speech, and without decentralization the network will be vulnerable to attack.</p> <p>[...]</p> <p>Users contribute to the network by giving bandwidth and a portion of their hard drive (called the "data store") for storing files. Unlike other peer-to-peer file sharing networks, Freenet does not let the user control what is stored in the data store. Instead, files are kept or deleted depending on how popular they are, with the least popular being discarded to make way for newer or more popular content. Files in the data store are encrypted to reduce the likelihood of prosecution by persons wishing to censor Freenet content.</p> </blockquote> <p>The biggest problem is that it's slow. Both in transfer speed and (mainly) latency.. Even if you can get lots of people with decent upload throughput, it'll still never be as quick a dedicated servers or two.. The speed is fine for what Freenet is (publishing data without fear of censorship), but not for hosting your website..</p> <p>A bigger problem is the content has to be static files, which rules out it's use for a majority of high-traffic websites.. To serve dynamic data each peer would have to execute code (scary), and would probably have to retrieve data from a database (which would be another big delay, again because of the latency)</p> <p>I think "cloud computing" is about as close to P2P web-hosting as we'll see for the time being..</p>
SQLSERVER Management Objects in c++ Programming <p>How to use SQLSERVER SMO in C++(CPP) to list all the servers availabel and find databases installed using VS2003/VS2005 IDE.</p> <p>And i need some clarification in</p> <p>1)Does Vs2003 Have support for SQLSMO?? 2)Is any additional files(reference) needed to work with SMO in VS2003? if yes what r those?</p> <p>Thanks in Advance...</p>
<p>SMO (SQL Server Management Objects) was released with SQL Server 2005, and requires .NET 2.0 at least. VS 2003 only supports .NET 1.x.</p> <p>In .NET 1.x, you'll have to revert to SQL-DMO - a COM based set of components for managing SQL Server database objects.</p> <p>Marc</p>
Is there a CEIL version of MySQL's DIV operator? <p>With MySQL </p> <p><code>a DIV b</code> </p> <p>is much faster than </p> <p><code>FLOOR(a / b)</code>. </p> <p>But I need to round up so I'm using,</p> <p><code>CEIL(a / b)</code></p> <p>It seems strange that there wouldn't be a ceiling version of DIV, but I can't find it. Is there anything undocumented hidden away somewhere? Or any other non floating point way to do this?</p>
<p>Alternative:</p> <p>(a + b - 1) DIV b</p>
Is it possible to customize the DisplayMember of a DataBound ComboBox? <h1>Solution</h1> <p>This is what I came up with:</p> <pre><code>Public Class IndexedDropDownItem Private _KeyCode, _Display As String Public Property KeyCode() As String Get Return _KeyCode End Get Set(ByVal value As String) _KeyCode = value End Set End Property Public Property Display() As String Get Return _Display End Get Set(ByVal value As String) _Display = value End Set End Property Sub New(ByVal KeyIndex As String, ByVal ItemDisplay As String) KeyCode = KeyIndex Display = ItemDisplay End Sub Public Overrides Function ToString() As String Return String.Format("{0} - {1}", KeyCode, Display) End Function End Class </code></pre> <p>Implementation:</p> <pre><code>With myDropDown Dim oItem As IndexedDropDownItem = Nothing For Each dr As Data.DataRow In oTemp.Rows oItem = New IndexedDropDownItem(dr.Item("key_code"), _ dr.Item("descript")) .Items.Add(oItem) oItem = Nothing Next End With </code></pre> <p>Manipulation:</p> <pre><code>Dim _KeyCode, _Display As String With CType(dataPathComboBox.SelectedItem, IndexedDropDownItem) _KeyCode = .KeyCode _Display = .Display End With </code></pre> <p>I hope this will help someone out!</p> <p><hr /></p> <p>I have a ComboBox that is populated from a DataTable:</p> <pre><code>With myComboBox .DataSource = myDataTable .DisplayMember = "descript" .ValueMember = "key_code" End With </code></pre> <p>I want to be able to have the DisplayMember show "key_code - descript", while retaining the value I have set.</p> <p>Is this even possible? Thanks</p>
<p>Since you are using a datatable you would need to create a new column that computes the value.</p> <p>I personally have moved to using objects to do my databinding and with it in my class I simply add another public property "ListDisplayText" that does the formatting for me.</p>
C++ functions accepting both pointers and references <p>I am writing a library in C++ and have some functions that work with modules. An example would look like this:</p> <pre><code>void connect(Module *a, Module *b); </code></pre> <p>The problem is, that it would be sometimes handy if the function accepted also references (some of the Modules may be allocated on the stack and some on the heap and all the &amp;s and *s get boring and messy soon).</p> <p>Now I have inlined function that takes references, turns them into pointers and calls the original function.</p> <pre><code>inline void connect(Module &amp;a, Module &amp;b){ connect(&amp;a, &amp;b); } </code></pre> <p>I don't like this solution much, because for a few more functions it makes a lot of code to write, read, compile, ...</p> <p>Another thing that was thinking about is adding <code>Module::operator Module *()</code> that would hust return <code>this</code>.</p> <p>What are your thoughts on this? Isn't there any potential for epic failure that I missed?</p> <p>Thanks.</p>
<p>Why not just call the function with</p> <pre><code>connect(&amp;a, &amp;b); </code></pre> <p>like in your inline function, whenever you have to call it with references? This makes it very clear that the function takes pointers, and that <code>a</code> and <code>b</code> are not pointers. You only have to type two more characters.</p>
Can't perform Create, Update or Delete operations on Table because it has no primary key <p>I've been trying to insert row in the table having an identity column RequestID (which is primary key as well)</p> <pre><code> HelpdeskLog logEntry = new HelpdeskLog { RequestBody = message.Body }; if (attachment != null) logEntry.Attachments = Helper.StreamToByteArray(attachment.ContentStream); Database.HelpdeskLogs.InsertOnSubmit(logEntry); </code></pre> <p>But my code inevitably throws following error</p> <blockquote> <p>Can't perform Create, Update or Delete operations on Table because it has no primary key.</p> </blockquote> <p>despite primary key column exists indeed</p> <p>That's what I tried to do:</p> <ol> <li>To look in debugger the value of identity column being inserted in object model. It is 0</li> <li>To insert manually (with SQL) fake values into table - works fine, identity values generated as expected</li> <li>To assure if SQLMetal has generated table map correctly . All OK, primary key attribute is generated properly</li> </ol> <p>Nevertheless, neither of approaches helped. What's the trick, does anybody know?</p>
<p>I've also had this problem come up in my C# code, and realized I'd forgotten the IsPrimaryKey designation:</p> <pre><code> [Table (Name = "MySessionEntries" )] public class SessionEntry { [Column(IsPrimaryKey=true)] // &lt;---- like this public Guid SessionId { get; set; } [Column] public Guid UserId { get; set; } [Column] public DateTime Created { get; set; } [Column] public DateTime LastAccess { get; set; } } </code></pre> <p>this is needed even if your database table (<em>MySessionEntries</em>, in this case) already has a primary key defined, since Linq doesn't automagically find that fact out unless you've used the linq2sql tools to pull your database definitions into visual studio.</p>
How to Remove an Item from the Office Orb Menu in Outlook <p>Folks,</p> <p>I've been working on ribbon development in Office 2007, but I'm running into an issue that's driving me a bit nuts. I want to remove the "Permissions" option from the Orb menu of a new mail message in Outlook 2007. I am not having any luck. I'm using VS2008 and VSTO 3. Any suggestions?</p> <p>Thanks in advance,</p> <p>Rex</p>
<p>ahh, it turns out I was modifying the XML in the wrong part of the schema. The correct modification would look something like:</p> <pre><code>&lt;officeMenu&gt; &lt;splitButton idMso="PermissionRestrictMenu" visible="false"/&gt; &lt;/officeMenu&gt; &lt;tabs&gt; </code></pre>
ASP.NET MVC Views don't see any classes after massive refactoring <p>My project went through a name change, which led to using ReSharper to change the name of namespaces throughout the solution. Everything compiles just fine, but my ASP.NET MVC views are no longer seeing any inherited classes. I've changed the namespace imports in web.config and everything, and I'm certain that the classes exist. They work if I refer to the fully-qualified class name (Name.Space.ClassName).</p> <p>Why is this happening and how can I fix it?</p> <p>EDIT: More detail:</p> <p>Before refactoring, I had custom view page, master page, and user control classes:</p> <blockquote> <p>SalesWeb.Mvc.Views.SalesWebViewPage<br /> SalesWeb.Mvc.Views.SalesWebMasterPage<br /> SalesWeb.Mvc.Views.SalesWebUserControl</p> </blockquote> <p>After refactoring:</p> <blockquote> <p>Wasabi.SalesPortal.Mvc.Views.SalesPortalViewPage<br /> Wasabi.SalesPortal.Mvc.Views.SalesPortalMasterPage<br /> Wasabi.SalesPortal.Mvc.Views.SalesPortalUserControl</p> </blockquote> <p>In web.config, before refactoring:</p> <pre><code>&lt;configuration&gt; &lt;system.web&gt; ... &lt;pages ...&gt; ... &lt;namespaces&gt; ... &lt;add namespace="SalesWeb.Mvc.Views" /&gt; &lt;/namespaces&gt; &lt;/pages&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>After:</p> <pre><code>&lt;configuration&gt; &lt;system.web&gt; ... &lt;pages ...&gt; ... &lt;namespaces&gt; ... &lt;add namespace="Wasabi.SalesPortal.Mvc.Views" /&gt; &lt;/namespaces&gt; &lt;/pages&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>I've also changed the Inherits attribute on each of my views, master pages, and user controls. However, when attempting to visit the MVC application, it complains that <strong>SalesPortalMasterPage</strong> cannot be found, although I'm absolutely certain that it exists because I don't have any problems when referring to it as <strong>Wasabi.SalesPortal.Mvc.Views.SalesPortalMasterPage</strong>.</p>
<p>Try cleaning your bin directory and do a rebuild. Sometimes an older dll lingers in the bin folder and mess up your references/namespacing.</p>
How do I get the next item in a subset of an ordered table using linq? <p>I have two tables:</p> <pre><code>Topic ( TopicID: int, (primary key) TopicName: varchar ); Example ( ExampleID: int, (primary key) TopicID: int, (foreign key to Topic table) ExampleOrder: int, ExampleName: varchar ); </code></pre> <p>Using Linq, given an ExampleID, I want to get the next example in the same topic (with the same TopicID). Here's how it might be done in sql:</p> <pre><code>DECLARE @ExampleOrder int; DECLARE @TopicID int; SELECT @ExampleOrder=ExampleOrder, @TopicID=TopicID FROM Example WHERE ExampleID=@ExampleID; SELECT TOP 1 ExampleID FROM Example WHERE TopicID=@TopicID AND ExampleOrder&gt;@ExampleOrder ORDER BY ExampleOrder </code></pre> <p>Is there a simple way to do this in Linq? I know I can do this with two Linq queries, but I'm trying to get it done without extra round trips to the database.</p>
<pre><code>int exampleID = 5; //now to write a query var query = from ex in db.Examples let prior = db.Examples.Where(ex2 =&gt; ex2.ExampleID == exampleID).First() where ex.TopicID == prior.TopicID &amp;&amp; ex.ExampleOrder &gt; prior.ExampleOrder order ex by ex.ExampleOrder descending select ex //ok, let's run the query - result will have 0 or 1 item in it. List&lt;Example&gt; result = query.Take(1).ToList(); </code></pre>
Restrict file access to authorized php users <p>I've inherited an application with a glaring security hole. </p> <p>It has session-based security, but file uploads (which are user specific) are not secured in any way and they are stored in the public file tree.</p> <p>Filenames do not follow any convention as such, making them hard to guess, but the data is sensitive and thus I need to implement a security measure to prevent unauthorized file access.</p> <p>Moving the location of the files is not really an option, so I'm looking at a htaccess solution to forward requests to a php handler script.</p> <p>Does anyone have experience in implementing this type of thing or any good alternative solutions? Specific examples of .htaccess syntax greatly appreciated, as I'm struggling in this area. </p>
<p>Don't really understand why moving them isn't an option, since pushing requests for them to a handler means it no longer matters where they're stored. But you're the man on the scene.</p> <p>.htaccess looks like:</p> <pre><code>RewriteEngine on RewriteRule path/to/where/these/files/live/(.*) /handlerscript.php/$1 </code></pre> <p>Then you pick up the remaining file path and name from <code>$_SERVER['PATH_INFO']</code>.</p>
Mutliple criteria for single field in symfony? <p>I'm trying to define multiple criteria for a single field in symfony, but every time I define a second criterion, it overwrites the previous one. Here is an example of my code:</p> <pre><code> # build query to fetch search results $c = new Criteria(); # set minimum price if($request-&gt;getPostParameter('price_from') &gt; 0) { $c-&gt;add(HomeModelPeer::PRICE, $request-&gt;getPostParameter('price_from'), Criteria::GREATER_EQUAL); } # set maximum price if($request-&gt;getPostParameter('price_to') &gt; 0) { $c-&gt;add(HomeModelPeer::PRICE, $request-&gt;getPostParameter('price_to'), Criteria::LESS_EQUAL); } </code></pre> <p>Is there a way to define more than one per field?</p>
<p>For the case where you have both limits, you need to do something like this:</p> <pre><code>$c = new Criteria(); $c2 = $c-&gt;getNewCriterion(HomeModelPeer::PRICE, $request-&gt;getPostParameter('price_from'), Criteria::GREATER_EQUAL); $c2-&gt;addAnd($c-&gt;getNewCriterion(HomeModelPeer::PRICE, $request-&gt;getPostParameter('price_to'), Criteria::LESS_EQUAL) ); $c-&gt;add($c2); </code></pre>
Problem with partial method C# 3.0 <p>Do you know the answer to following question?</p> <blockquote> <p>Let us say, it MyMethod() is declared as partial method in MyPartialClass in MyPartialClass.cs. I have also provided body of MyMethod() in MyPartialClass in MyPartialClass2.cs. I use a problem without answer“Magic” code generator which has actually generated MyPartialClass.cs, let us say based on some DB schema. Some innocent guy changes schema for good and then runs “Magic”. MyPartialClass.cs is re-generated but with MyMethod2() instead of MyMethod() declaration. Think of me. I am thinking that I have implemented MyMethod() which is used by “Magic” but in reality, “Magic” is using MyMethod2(). C# compiler does not tell me that I have partial method implemented without any declaration and my implementation is not used at all!</p> <p>Any solution?</p> </blockquote> <p>I think it is a problem without an answer.<p></p> <p><strong>EDIT</strong> I got an answer :-). I had a typo in my code and that is why compiler was not flagging error. Jon already has pointed that out. </p>
<p>You should get error CS0759. Test case:</p> <pre><code>partial class MyClass { partial void MyMethod() { Console.WriteLine("Ow"); } } partial class MyClass { partial void MyMethod2(); } </code></pre> <p>Compilation results:</p> <pre><code>Test.cs(6,18): error CS0759: No defining declaration found for implementing declaration of partial method 'MyClass.MyMethod()' </code></pre> <p>Does that not do what you want it to?</p>
What is the Windows Forms equivalent of the WPF's Keyboard class? <p>Question says it all - is there a class somewhere in Windows Forms that has the same functionality as the WPF <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.keyboard.aspx" rel="nofollow"><code>System.Windows.Input.Keyboard</code></a>? Or am I stuck always having to handle the keyboard events and keep my own state? (I'm specifically interested in a Forms analogue to <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.keyboard.iskeydown.aspx" rel="nofollow"><code>IsKeyDown</code></a>).</p> <p>Alternatively, is there a <strong>no-fuss</strong> way to use this WPF functionality in my Forms project (I'm not very familiar with WPF, but <a href="http://msdn.microsoft.com/en-us/library/ms742474%28VS.85%29.aspx" rel="nofollow"><strong>this</strong></a> looks fussy)?</p>
<p>I don't believe there is an equivalent for WinForms. The best I know of is the static ModifierKeys property on Control but that is almost certainly not what you are looking for. </p> <p>I believe you are stuck with handling the events and keeping your own state :(</p>
Get ProgID from .NET Assembly <p>I want to write a program to find all the com visible .NET classes, and their ProgIDs from a .NET assembly. What's the best way to do this?</p>
<p>This will get the ProgId rather than the ClassId, and also work if the whole assembly is marked visible:</p> <pre><code> Assembly assembly = Assembly.LoadFile("someassembly.dll"); bool defaultVisibility; object[] assemblyAttributes = assembly.GetCustomAttributes(typeof(ComVisibleAttribute),false); if (assemblyAttributes.Length == 0) defaultVisibility = false; else defaultVisibility = (assemblyAttributes[0] as ComVisibleAttribute).Value; foreach(Type type in assembly.GetTypes()) { bool isComVisible = defaultVisibility; object []attributes = type.GetCustomAttributes(typeof(ComVisibleAttribute),true); if (attributes.Length &gt; 0) isComVisible = (attributes[0] as ComVisibleAttribute).Value; if (isComVisible) { attributes = type.GetCustomAttributes(typeof(ProgIdAttribute),true); if (attributes.Length &gt;0) { Console.WriteLine(String.Format("Type {0} has ProgID {1}",type.Name,(attributes[0] as ProgIdAttribute).Value)); } } } </code></pre>
Querying the DNS service records to find the hostname and TCP/IP <p>In a paper about the <strong>Life Science Identifiers</strong> (see <a href="http://www.scfbm.org/content/3/1/2" rel="nofollow">LSID Tester, a tool for testing Life Science Identifier resolution services</a>), Dr Roderic DM Page wrote : </p> <p>Given the LSID urn:lsid**:ubio.org**:namebank:11815, querying the DNS for the SRV record for <em>_lsid._tcp</em>.<strong>ubio.org</strong> returns animalia.ubio.org:80 as the location of the ubio.org LSID service.</p> <p>I learned that I can link _lsid._tcp.ubio.org to animalia.ubio.org:80 using the <strong>host</strong> command on unix:</p> <pre><code>host -t srv _lsid._tcp.ubio.org _lsid._tcp.ubio.org has SRV record 1 0 80 ANIMALIA.ubio.org </code></pre> <p>How can I do this 'DNS' thing using the Java J2SE API (Without any external java library, I'd like a lightweight solution ) ?</p> <p>Thank you</p>
<p>The JNDI DNS provider can lookup SRV records. You need to do something like:</p> <pre><code>Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); env.put("java.naming.provider.url", "dns:"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes("_lsid._tcp.ubio.org", new String[] { "SRV" }); </code></pre> <p>The returned attributes are an enumeration of strings that look like "1 0 80 ANIMALIA.ubio.org". The space separated fields are in order:</p> <ol> <li>priority</li> <li>weight</li> <li>port</li> <li>server</li> </ol>
Is there an advantage of the operating system understanding the characteristics of how a thread may be used? <p>Is there an advantage of the operating system understanding the characteristics of how a thread may be used? For example, what if there were a way in Java when creating a new thread to indicate that it would be used for intensive CPU calculations vs will block for I/O. Wouldn't thread scheduling improve if this were a capability?</p>
<p>That's what OS processes do. The OS has sophisticated scheduling for the processes. The OS tracks I/O use and CPU use and dynamically adjusts priorities so that CPU-intensive processing doesn't interfere with I/O.</p> <p>If you want those features, use a proper OS process.</p>
Can we implement Row Lost Focus event for GridView <p>I have a Hierarchical gridview and I need implement the following functionality in the child gridview:</p> <ol> <li>Show all the rows in editable mode (this can be done)</li> <li>Save all data of each row on it's lost focus</li> </ol> <p>We can capture the mouse events but how do we track the row lost focus triggered by the Keyboard. Ex: when a row is in focus, hitting f6 will go directly to browser address bar which results in the row lost focus event.</p> <p>One mouse move across the rows will trigger all the validation and save logic for all the rows, this screen has hierarchical control and the child gridview has a minimum of 200 rows.</p> <p>Any thoughts on how to implement this?</p>
<p>You'd probably need to implement a postback / callback when the blur event fires for the row on the client-side. I'm not exactly sure which DOM elements support the blur event in every browser but you can do it. </p> <p>The GridEX control from Janus Systems can do it, but honestly, I'd really stay clear of doing things like Janus Systems do, so it's better you should find your own way.</p> <p><strong>EDIT:</strong> Try <a href="http://javascript.about.com/library/bltut29.htm" rel="nofollow">this</a>.</p>
How can I write Perl that doesn't look like C? <p>My co-workers complain that my Perl looks too much like C, which is natural since I program in C most of the time, and Perl just a bit. Here's my latest effort. I'm interest in Perl that is easy to understand. I'm a bit of a Perl critic, and have little tolerance for cryptic Perl. But with readability in mind, how could the following code be more Perlish?</p> <p>It's goal is to do a traffic analysis and find which IP addresses are within the ranges given in the file "ips". Here's my effort:</p> <pre><code>#!/usr/bin/perl -w # Process the files named in the arguments, which will contain lists of IP addresses, and see if # any of them are in the ranges spelled out in the local file "ip", which has contents of the # form start-dotted-quad-ip-address,end-dotted-quad-ip_address,stuff_to_be_ignored use English; open(IPS,"ips") or die "Can't open 'ips' $OS_ERROR"; # Increment a dotted-quad ip address # Ignore the fact that part1 could get erroneously large. sub increment { $ip = shift; my ($part_1, $part_2, $part_3, $part_4) = split (/\./, $ip); $part_4++; if ( $part_4 &gt; 255 ) { $part_4 = 0; ($part_3++); if ( $part_3 &gt; 255 ) { $part_3 = 0; ($part_2++); if ( $part_2 &gt; 255 ) { $part_2 = 0; ($part_1++); } } } return ("$part_1.$part_2.$part_3.$part_4"); } # Compare two dotted-quad ip addresses. sub is_less_than { $left = shift; $right = shift; my ($left_part_1, $left_part_2, $left_part_3, $left_part_4) = split (/\./, $left); my ($right_part_1, $right_part_2, $right_part_3, $right_part_4) = split (/\./, $right); if ($left_part_1 != $right_part_1 ) { return ($left_part_1 &lt; $right_part_1); } if ($left_part_2 != $right_part_2 ) { return ($left_part_2 &lt; $right_part_2); } if ($left_part_3 != $right_part_3 ) { return ($left_part_3 &lt; $right_part_3); } if ($left_part_4 != $right_part_4 ) { return ($left_part_4 &lt; $right_part_4); } return (false); # They're equal } my %addresses; # Parse all the ip addresses and record them in a hash. while (&lt;IPS&gt;) { my ($ip, $end_ip, $junk) = split /,/; while (is_less_than($ip, $end_ip) ) { $addresses{$ip}=1; $ip = increment($ip); } } # print IP addresses in any of the found ranges foreach (@ARGV) { open(TRAFFIC, $_) or die "Can't open $_ $OS_ERROR"; while (&lt;TRAFFIC&gt; ) { chomp; if (defined $addresses{$_}) { print "$_\n"; } } close (TRAFFIC); } </code></pre>
<p>From years of seeing Perl code written by C programmers, here's some generic advice:</p> <p>Use hashes. Use lists. USE HASHES! USE LISTS! Use list operations (map, grep, split, join), especially for small loops. Don't use fancy list algorithms; pop, splice, push, shift and unshift are cheaper. Don't use trees; hashes are cheaper. Hashes are cheap, make them, use them and throw them out! Use the iterator for loop, not the 3-arg one. Don't call things $var1, $var2, $var3; use a list instead. Don't call things $var_foo, $var_bar, $var_baz; use a hash instead. Use <code>$foo ||= "default"</code>. Don't use <code>$_</code> if you have to type it.</p> <p>Don't use prototypes, IT'S A TRAP!!</p> <p>Use regexes, not <code>substr()</code> or <code>index()</code>. Love regexes. Use the <code>/x</code> modifier to make them readable.</p> <p>Write <code>statement if $foo</code> when you want a block-less conditional. There's almost always a better way to write a nested condition: try recursion, try a loop, try a hash.</p> <p>Declare variables when you need them, not at the top of the subroutine. use strict. use warnings, and fix them all. use diagnostics. Write tests. Write POD.</p> <p>Use CPAN. Use CPAN! USE CPAN! Someone's probably already done it, better.</p> <p>Run <a href="http://search.cpan.org/dist/Perl-Critic/" rel="nofollow">perlcritic</a>. Run it with <code>--brutal</code> just for kicks. Run <a href="http://search.cpan.org/dist/Perl-Tidy" rel="nofollow">perltidy</a>. Think about why you do everything. Change your style.</p> <p>Use the time not spent fighting the language and debugging memory allocation to improve your code.</p> <p>Ask questions. Take style commentary on your code graciously. Go to a Perl Mongers meeting. Go onto perlmonks.org. Go to YAPC or a Perl Workshop. Your Perl knowledge will grow by leaps and bounds.</p>
C# or Java: Prepend strings with StringBuilder? <p>I know we can append strings using <code>StringBuilder</code>. Is there a way we can prepend strings (i.e. add strings in front of a string) using <code>StringBuilder</code> so we can keep the performance benefits that <code>StringBuilder</code> offers?</p>
<p>Using the <a href="http://msdn.microsoft.com/en-us/library/0xzfkkwa.aspx">Insert method</a> with the position parameter set to 0 would be the same as preappending.</p> <p>This goes for C#, but I am sure Java StringBuilder has a similar method.</p>
How do you automate the launching/debugging of large scale projects? <p><strong>Scenario:</strong></p> <p>There is a complex piece of software that is annoying to launch by hand. What I've done is to create a python script to launch the executable and attach <em>gdb</em> for debugging.</p> <p>The process launching script:</p> <ul> <li>ensures an environment variable is set.</li> <li>ensures a local build directory gets added to the environment's <code>LD_LIBRARY_PATH</code> variable.</li> <li>changes the current working directory to where the executable expects to be (not my design)</li> <li>launches the executable with a config file the only command line option </li> <li>pipes the output from the executable to a second logging process</li> <li>remembers PID of executable, then launches &amp; attaches gdb to running executable.</li> </ul> <p>The script works, with one caveat. <strong>ctrl-c doesn't interrupt the debugee and return control to gdb.</strong> So if I "continue" with no active breakpoints I can never stop the process again, it has to be killed/interrupted from another shell. BTW, running "kill -s SIGINT &lt;pid&gt;" where &lt;pid&gt; is the debuggee's pid does get me back to gdb's prompt... but it is really annoying to have to do things this way</p> <p>At first I thought Python was grabbing the SIGINT signal, but this doesn't seem to be the case as I set up signal handlers forward the signal to the debugee and that doesn't fix the problem.</p> <p>I've tried various configurations to the python script (calling os.spawn* instead of subprocess, etc.) It seems that any way I go about it, if python launched the child process, SIGINT (ctrl-c) signals DO NOT to get routed to gdb or the child process. </p> <p><strong>Current line of thinking</strong></p> <ul> <li>This might be related to needing a separate process group id for the debugee &amp; gdb...any credence to this? </li> <li>Possible bug with SELinux?</li> </ul> <p><strong>Info:</strong> </p> <ul> <li>gdb 6.8</li> <li>Python 2.5.2 (problem present with Python 2.6.1 as well)</li> <li>SELinux Environment (bug delivering signals to processes?)</li> </ul> <p><strong>Alternatives I've considered:</strong></p> <ul> <li>Setting up a .gdbinit file to do as much of what the script does, environment variables and current working directory are a problem with this approach. </li> <li>Launching executable and attaching gdb manually (yuck)</li> </ul> <p><strong>Question:</strong> How do you automate the launching/debugging of large scale projects?</p> <p><strong>Update:</strong> I've tried Nicholas Riley's examples below, on my Macintosh at home they all allow cntl-c to work to varrying degrees, on the production boxen (which I now to believe may be running SELinux) they don't... </p>
<p>Instead of forwarding the signal to the debuggee from Python, you could try just ignoring it. The following worked for me:</p> <pre><code>import signal signal.signal(signal.SIGINT, signal.SIG_IGN) import subprocess cat = subprocess.Popen(['cat']) subprocess.call(['gdb', '--pid=%d' % cat.pid]) </code></pre> <p>With this I was able to ^C repeatedly inside GDB and interrupt the debuggee without a problem, however I did see some weird behavior. </p> <p>Incidentally, I also had no problem when forwarding the signal to the target process.</p> <pre><code>import subprocess cat = subprocess.Popen(['cat']) import signal, os signal.signal(signal.SIGINT, lambda signum, frame: os.kill(cat.pid, signum)) subprocess.call(['gdb', '--pid=%d' % cat.pid]) </code></pre> <p>So, maybe something else is going on in your case? It might help if you posted some code that breaks.</p>
Which actionscript / flash framework has the best tools for simple animation <p>I'm converting some Flex down to an Actionscript project and need to get up to speed as quickly as possible on a lightweight framwork for doing basic animation.</p> <p>The components may have some very simple data access - such as reading a list of images, but nothing clever.</p> <p>What I really want is an equivalent of Flex's 'AnimateProperty' or 'Move'. Yes very simple! </p> <p>I just don't want to have to go too low level and start doing <code>x+=</code> in an <code>onEnterFrame()</code> event handler. I just want to replace timeline based animation with object oriented script.</p>
<p>I like <code>caurina</code> which is easy to use but able to handle really complex things. It can be found <a href="http://code.google.com/p/tweener/" rel="nofollow">here</a>. But the best is just to grap a few and test them yourself.</p>
How can I check if a resource bundle key does not exist using JSTL tags? <p>I have a resource file that will have some optional keys. If the optional resource key is not present, I set a default instead. It appears that there is no easy way to determine if a key exists in the resource bundle. So this is what I'm doing to get around it. </p> <pre><code>&lt;fmt:message var="title" key="login.reg.signup.${signupForm.regfrom}.title" /&gt; &lt;c:if test='${fn:startsWith(title, "??")}'&gt; &lt;fmt:message var="title" key="login.reg.signup.default.title" /&gt; &lt;/c:if&gt; </code></pre> <p>Is there a better way?</p>
<p>You could write your own JSP tag that does this, so you can then just do:</p> <pre><code>&lt;my:message var="title" key="${form}.title" default="default.title"/&gt; </code></pre> <p>The tag implementation could either be your current JSP syntax, or a Java class.</p>
Does GQL support commonly available SQL Style aggregation? <p>What I'm looking for a simple Aggregate Functions that are widely available in versions of SQL. </p> <p>Simple things like <code>Select Count(*) from table1</code> to the more complex.</p> <p>If these are available, is there some documentation you could point me to?</p> <p>Thanks - Giggy</p>
<p>The SQL aggregate functions are not available. What you want to do is follow patterns like the sharded counters example: <a href="http://code.google.com/appengine/articles/sharding_counters.html">http://code.google.com/appengine/articles/sharding_counters.html</a> which explain that instead of aggregating the values on queries, you want to keep the counters up to date when the values are inserted, updated, or deleted.</p> <p>The example takes the concept a bit further than just maintaining the aggregates in that it will explain how to make it so that you can update the counters under high load where you have a limited amount of opportunity to write to your counters - so the shards help you distribute the load over several instances.</p>
Is there any cure for the preprocessor blues? <p>I know that I can kick the the preprocessor to spit out output with the <code>-E</code> option in my particular circumstance. For generated code this preprocessor output is murderous. For example I have a 4gl application and Informix converts this into <strong>C</strong> which in turn gets spit out to a horrible ugly mess.</p> <p>What I want is an editor that will allow me to specify what preprocessor values are in effect and show me only the relevant code. I have something very basic working in Vim matching <code>#ifdef</code> and <code>#endif</code>, but the code is riddled with more advanced constructs such is <code>#ifndef</code>, <code>#if</code>, and <code>#else</code>. To make matters worse, the constructs are logically more complex, and I don't think my Vim scripting skills are adequate for me to get what I want out of it. For example:</p> <pre><code>#if DLEVEL &gt; 5 #define SIGNAL 1 #if STACKUSE == 1 #define STACK 200 #else #define STACK 100 #endif #else #define SIGNAL 0 #if STACKUSE == 1 #define STACK 100 #else #define STACK 50 #endif #endif #if DLEVEL == 0 #define STACK 0 #elif DLEVEL == 1 #define STACK 100 #elif DLEVEL &gt; 5 display( debugptr ); #else #define STACK 200 #endif </code></pre> <p>Includes defining an expression evaluator if I want to tackle it. This has to be a solved problem! If you have Vim suggestions or other ones please let me know.</p>
<p>The Eclipse <a href="http://www.eclipse.org/cdt/" rel="nofollow">CDT</a> editor does a pretty good job highlighting code based on the macros you declare to be active. You may want to check it out.<img src="http://i.stack.imgur.com/Egekv.png" alt="alt text"></p>
Customize/remove Django select box blank option <p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p> <pre><code>&lt;option value=""&gt;---------&lt;/option&gt; </code></pre> <p>What I'd like to know is:</p> <ol> <li>What is the cleanest way to remove this auto-generated option from the select box? </li> <li><p>What is the cleanest way to customize it so that it shows as:</p> <pre><code>&lt;option value=""&gt;Select Item&lt;/option&gt; </code></pre></li> </ol> <p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p> <p>Thanks for any help,</p> <p>Jeff</p> <p>Edit: I've configured the ForeignKey field as such: </p> <pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb) </code></pre> <p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
<p>Haven't tested this, but based on reading Django's code <a href="http://code.djangoproject.com/browser/django/trunk/django/forms/models.py#L680">here</a> and <a href="http://code.djangoproject.com/browser/django/trunk/django/forms/models.py#L710">here</a> I believe it should work:</p> <pre><code>class ThingForm(models.ModelForm): class Meta: model = Thing def __init__(self, *args, **kwargs): super(ThingForm, self).__init__(*args, **kwargs) self.fields['verb'].empty_label = None </code></pre> <p><strong>EDIT</strong>: This is <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield">documented</a>, though you wouldn't necessarily know to look for ModelChoiceField if you're working with an auto-generated ModelForm.</p> <p><strong>EDIT</strong>: As jlpp notes in his answer, this isn't complete - you have to re-assign the choices to the widgets after changing the empty_label attribute. Since that's a bit hacky, the other option that might be easier to understand is just overriding the entire ModelChoiceField:</p> <pre><code>class ThingForm(models.ModelForm): verb = ModelChoiceField(Verb.objects.all(), empty_label=None) class Meta: model = Thing </code></pre>
Cancel slow-loading external scripts <p>I am dynamically adding script tags to the DOM so I can download JSON data. Occasionally something goes wrong with a download, and the script fails to load properly.</p> <p>How do I tell the browser to give up on a script that has taken too long to load? I think this is important because the browser limits the number of open requests at one time, and I don't want to waste it with dead connections.</p> <p>I tried removing the script tag from the DOM, but that seems to have no effect.</p>
<p>I'm not sure that you can control how the browser loads a script once you've inserted it into the DOM.</p> <p>However, if you use an XMLHttpRequest to download the JSON data, you can call the <a href="https://developer.mozilla.org/en/XMLHttpRequest#abort%28%29" rel="nofollow"><code>abort</code></a> method if the request takes too long.</p> <p>Steve</p>
Is there a realtime apache/php console similar to webrick or mongrel with ruby on rails? <p>Is there a realtime apache/php console similar to webrick or mongrel with ruby on rails?</p> <p>I want to be able to monitor what the heck my server is doing.</p> <h2>edit:</h2> <p>but I don't want to grep the log</p> <p>Thanks!</p>
<p>I believe <a href="http://www.firephp.org/" rel="nofollow">FirePHP</a> might be somewhat equivalent to what your looking for. </p> <p><strong>Simple Example:</strong></p> <pre><code> &lt;?php FB::log('Log message'); FB::info('Info message'); FB::warn('Warn message'); FB::error('Error message'); ?&gt; </code></pre> <p><img src="http://www.firephp.org/images/Screenshots/SimpleConsole.png" alt="alt text" /></p> <p><a href="http://www.firephp.org/HQ/Use.htm" rel="nofollow">Read More</a></p>
Google App Engine: Intro to their Data Store API for people with SQL Background? <p>Does anyone have any good information aside from the Google App Engine docs provided by Google that gives a good overview for people with MS SQL background to porting their knowledge and using Google App Engine Data Store API effectively.</p> <p>For Example, if you have a self created Users Table and a Message Table</p> <p>Where there is a relationship between Users and Message (connected by the UserID), how would this structure be represented in Google App Engine?</p> <pre><code>SELECT * FROM Users INNER JOIN Message ON Users.ID = Message.UserID </code></pre>
<p>Here is a good link: One to Many Join using Google App Engine.</p> <p><a href="http://blog.arbingersys.com/2008/04/google-app-engine-one-to-many-join.html" rel="nofollow">http://blog.arbingersys.com/2008/04/google-app-engine-one-to-many-join.html</a></p> <p>Here is another good link: Many to Many Join using Google App Engine:</p> <p><a href="http://blog.arbingersys.com/2008/04/google-app-engine-many-to-many-join.html" rel="nofollow">http://blog.arbingersys.com/2008/04/google-app-engine-many-to-many-join.html</a></p> <p>Here is a good discussion regarding the above two links:</p> <p><a href="http://groups.google.com/group/google-appengine/browse_thread/thread/e9464ceb131c726f/6aeae1e390038592?pli=1" rel="nofollow">http://groups.google.com/group/google-appengine/browse_thread/thread/e9464ceb131c726f/6aeae1e390038592?pli=1</a></p> <p>Personally I find this comment in the discussion very informative about the Google App Engine Data Store:</p> <p><a href="http://groups.google.com/group/google-appengine/msg/ee3bd373bd31e2c7" rel="nofollow">http://groups.google.com/group/google-appengine/msg/ee3bd373bd31e2c7</a></p> <blockquote> <p>At scale you wind up doing a bunch of things that seem wrong, but that are required by the numbers we are running. Go watch the EBay talks. Or read the posts about how many database instances FaceBook is running.</p> <p>The simple truth is, what we learned about in uni was great for the business automation apps of small to medium enterprise applications, where the load was predictable, and there was money enough to buy the server required to handle the load of 50 people doing data entry into an accounts or business planning and control app....</p> </blockquote> <p>Searched around a bit more and came across this Google Doc Article:</p> <p><a href="http://code.google.com/appengine/articles/modeling.html" rel="nofollow">http://code.google.com/appengine/articles/modeling.html</a></p> <blockquote> <p>App Engine allows the creation of easy to use relationships between datastore entities which can represent real-world things and ideas. Use ReferenceProperty when you need to associate an arbitrary number of repeated types of information with a single entity. Use key-lists when you need to allow lots of different objects to share other instances between each other. You will find that these two approaches will provide you with most of what you need to create the model behind great applications.</p> </blockquote>
How to enter experience design work? <p>My main area of interest in the world of programming is enhancing the user experience. I’m currently enrolled in a Information Science and Technology degree program and intend to tackle the Human-Computer Interaction focus my university offers through this major.</p> <p>So to expand and actually ask a question; as a UX designer what programming skills should I focus on developing the most? What tools are used in the trade? What languages would be practical for a designer to know deeply? What is expected of me to both help users and programmers?</p> <p>I appreciate any advice greatly.</p>
<p>As a student, you can get lots of Microsoft software for free through their Bizspark program. You may want to checkout Expression Blend which is Microsoft's product for creating rich user interfaces in Silverlight.</p>
Rendering HTML inside a DataList <p>I have a formatted text that contains Bolded, italicsed, and other styles implemented inside the message. I have this message stored in a Database. Now I want to implement these tags into work inside the a field inside the DataList. How do I do it?</p> <p>&lt;%# Eval("message") %></p> <p>Doesn't work. It just shows up the tags as such. Any help?</p>
<p>If you mean that your "message" contains formatted HTML, you should simply HTMLDecode it after the DataBinder has evaluated the value of the "message" property. For example:</p> <pre><code>' "message" contains the string "&lt;b&gt;Hello World!&lt;/b&gt;" ' Within the DataList: &lt;ItemTemplate&gt; &lt;asp:Label ID="lbl1" runat="server" Text='&lt;%# Server.HtmlDecode(Eval("message").ToString()) %&gt;' /&gt; &lt;/ItemTemplate&gt; </code></pre>
Ext region property <p>I'm studying extjs now.</p> <pre><code>new Ext.Viewport({ layout: 'border', items: [{ region: 'north', html: '&lt;h1 class="x-panel-header"&gt;Page Title&lt;/h1&gt;', autoHeight: true, border: false, margins: '0 0 5 0' },... </code></pre> <p>i could not find 'region' property in the API.</p> <p>i checked viewport, component and other classes. i could not find it.</p>
<p>You are correct, the 'region' attribute is not a direct attribute of Viewport itself, but an attribute of the regions you are assigning to your Viewport.</p> <p>Each Viewport must contain at least two regions. These regions are defined as part of the Ext.layout.BorderLayout.Region class (<a href="http://extjs.com/deploy/dev/docs/?class=Ext.layout.BorderLayout.Region" rel="nofollow">http://extjs.com/deploy/dev/docs/?class=Ext.layout.BorderLayout.Region</a>). Basically, you can have 'north','east','south' and 'west' regions, in combination with a 'center' region. You can have all or those, or just one, as long as you also have your 'center' region. The 'center' region will automatically resize to take up whatever remaining space you do not define as part of your other regions.</p>
Is it possible to access the App Store Data for market analyzation? <p>I am wondering if the App Store provides an API that allows others to access the data like descriptions, prices, reviews, etc.?</p>
<p>The iTunes Store <em>is</em> the API.</p> <p>All pages in the iTunes Store are simply XML files rendered by iTunes. You can parse these files yourself and navigate around to your heart's content.</p> <p>Here's the URL for the front page:</p> <pre><code>http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/com.apple.jingle.app.store.DirectAction/storeFront </code></pre> <p>You might also want to see:</p> <ul> <li><a href="http://www.aaronsw.com/2002/itms/" rel="nofollow">http://www.aaronsw.com/2002/itms/</a></li> <li><a href="http://www.s-seven.net/itunes_xml" rel="nofollow">http://www.s-seven.net/itunes_xml</a></li> </ul>
library for server side (c/c++) xmlrpc <p>I want to implement support of the XMLRPC protocol for my server that is written in C and C++ and now looking for the most widely adopted xmlrpc library. License is not an issue, GPL would be fine. What would you suggest ? Is there any defacto standard xmlrpc C library for such a purpose ?</p>
<p>The de facto standard would imo be this one: <a href="http://xmlrpc-c.sourceforge.net/">http://xmlrpc-c.sourceforge.net/</a> and it supports both C and C++ and it even has its own embedded http daemon for servicing the http requests ...</p> <p>edit: and it's available under a BSD-style license, so it allows you to boldly go where GPL didn't allow you to go before ;)</p>
How can I make external code 'safe' to run? Just ban eval()? <p>I'd like to be able to allow community members to supply their own javascript code for others to use, because the users' imaginations are collectively far greater than anything I could think of.</p> <p>But this raises the inherent question of security, particularly when the purpose is to <em>allow</em> external code to run.</p> <p>So, can I just ban <code>eval()</code> from submissions and be done with it? Or are there other ways to evaluate code or cause mass panic in javascript? </p> <p>There are other things to disallow, but my main concern is that unless I can prevent strings being executed, whatever other filters I put in for specific methods can be circumvented. Doable, or do I have to resort to demanding the author supplies a web service interface?</p>
<blockquote> <p>Or are there other ways to evaluate code</p> </blockquote> <p>You can't filter out calls to <code>eval()</code> at a script-parsing level because JavaScript is a Turing-complete language in which it is possible to obfuscate calls. eg. see svinto's workaround. You could hide <code>window.eval</code> by overwriting it with a null value, but there are indeed other ways to evaluate code, including (just off the top of my head):</p> <ul> <li>new Function('code')()</li> <li>document.write('%3Cscript>code%3C/script>')</li> <li>document.createElement('script').appendChild(document.createTextNode('code'))</li> <li>window.setTimeout('code', 0);</li> <li>window.open(...).eval('code')</li> <li>location.href='javascript:code'</li> <li>in IE, style/node.setExpression('someproperty', 'code')</li> <li>in some browsers, node.onsomeevent= 'code';</li> <li>in older browsers, Object.prototype.eval('code')</li> </ul> <blockquote> <p>or cause mass panic in javascript? </p> </blockquote> <p>Well createElement('iframe').src='http​://evil.iframeexploitz.ru/aff=2345' is one of the worse attacks you can expect... but really, when a script has control, it can do anything a user can on your site. It can make them post “I'm a big old paedophile!” a thousand times on your forums and then delete their own account. For example.</p> <blockquote> <p>do I have to resort to demanding the author supplies a web service interface?</p> </blockquote> <p>Yes, or:</p> <ul> <li>do nothing and let users who want this functionality download GreaseMonkey</li> <li>vet every script submission yourself</li> <li>use your own (potentially JavaScript-like) mini-language over which you actually have control</li> </ul> <p>an example of the latter that may interest you is <a href="http://code.google.com/p/google-caja/">Google Caja</a>. I'm not entirely sure I'd trust it; it's a hard job and they've certainly had some security holes so far, but it's about the best there is if you really must take this approach.</p>
Extract cursor image in Java <p>I was wondering if there is a way to extract an Image object from a Cursor object in Java.</p> <p>A use for this would be for instance :</p> <pre><code>Image img = extractCursorImage(Cursor.getDefaultCursor()); </code></pre> <p>Which you then can draw on a toolbar button (that's the purpose I want it for).</p>
<p>The <a href="http://java.sun.com/javase/6/docs/api/java/awt/Cursor.html">Cursor</a> class is pretty abstract - all the important stuff is delegated to native code, so you can't just draw one onto at <a href="http://java.sun.com/javase/6/docs/api/java/awt/Graphics2D.html">graphics</a> context. There isn't an immediately obvious way of getting round the need to either predefine the icons or do it in native code.</p> <hr> <blockquote> <p>could you help me use that function you mentioned?</p> </blockquote> <p>Below is some code to draw built-in Windows cursors using the <a href="https://github.com/twall/jna/">JNA</a> library. If you can use JNA, you can avoid C++ compilers.</p> <p>I'm probably making too many native calls, but the cost is not significant for one-shot icon generation.</p> <p><img src="http://f.imagehost.org/0709/hand.png" alt="hand cursor drawn in Java" /></p> <p>Code to display a cursor as a Java image:</p> <pre><code>public class LoadCursor { public static void draw(BufferedImage image, int cursor, int diFlags) { int width = image.getWidth(); int height = image.getHeight(); User32 user32 = User32.INSTANCE; Gdi32 gdi32 = Gdi32.INSTANCE; Pointer hIcon = user32 .LoadCursorW(Pointer.NULL, cursor); Pointer hdc = gdi32.CreateCompatibleDC(Pointer.NULL); Pointer bitmap = gdi32.CreateCompatibleBitmap(hdc, width, height); gdi32.SelectObject(hdc, bitmap); user32.DrawIconEx(hdc, 0, 0, hIcon, width, height, 0, Pointer.NULL, diFlags); for (int x = 0; x &lt; width; x++) { for (int y = 0; y &lt; width; y++) { int rgb = gdi32.GetPixel(hdc, x, y); image.setRGB(x, y, rgb); } } gdi32.DeleteObject(bitmap); gdi32.DeleteDC(hdc); } public static void main(String[] args) { final int width = 128; final int height = 128; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); draw(image, User32.IDC_HAND, User32.DI_NORMAL); BufferedImage mask = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); draw(mask, User32.IDC_HAND, User32.DI_MASK); applyMask(image, mask); JLabel icon = new JLabel(); icon.setIcon(new ImageIcon(image)); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(icon); frame.pack(); frame.setVisible(true); } private static void applyMask(BufferedImage image, BufferedImage mask) { int width = image.getWidth(); int height = image.getHeight(); for (int x = 0; x &lt; width; x++) { for (int y = 0; y &lt; height; y++) { int masked = mask.getRGB(x, y); if ((masked &amp; 0x00FFFFFF) == 0) { int rgb = image.getRGB(x, y); rgb = 0xFF000000 | rgb; image.setRGB(x, y, rgb); } } } } } </code></pre> <p>User32.dll interface:</p> <pre><code>public interface User32 extends Library { public static User32 INSTANCE = (User32) Native .loadLibrary("User32", User32.class); /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_ARROW = 32512; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_IBEAM = 32513; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_WAIT = 32514; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_CROSS = 32515; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_UPARROW = 32516; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_SIZENWSE = 32642; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_SIZENESW = 32643; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_SIZEWE = 32644; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_SIZENS = 32645; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_SIZEALL = 32646; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_NO = 32648; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_HAND = 32649; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_APPSTARTING = 32650; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_HELP = 32651; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_ICON = 32641; /** @see #LoadCursorW(Pointer, int) */ public static final int IDC_SIZE = 32640; /** @see #DrawIconEx(Pointer, int, int, Pointer, int, int, int, Pointer, int) */ public static final int DI_COMPAT = 4; /** @see #DrawIconEx(Pointer, int, int, Pointer, int, int, int, Pointer, int) */ public static final int DI_DEFAULTSIZE = 8; /** @see #DrawIconEx(Pointer, int, int, Pointer, int, int, int, Pointer, int) */ public static final int DI_IMAGE = 2; /** @see #DrawIconEx(Pointer, int, int, Pointer, int, int, int, Pointer, int) */ public static final int DI_MASK = 1; /** @see #DrawIconEx(Pointer, int, int, Pointer, int, int, int, Pointer, int) */ public static final int DI_NORMAL = 3; /** @see #DrawIconEx(Pointer, int, int, Pointer, int, int, int, Pointer, int) */ public static final int DI_APPBANDING = 1; /** http://msdn.microsoft.com/en-us/library/ms648391(VS.85).aspx */ public Pointer LoadCursorW(Pointer hInstance, int lpCursorName); /** http://msdn.microsoft.com/en-us/library/ms648065(VS.85).aspx */ public boolean DrawIconEx(Pointer hdc, int xLeft, int yTop, Pointer hIcon, int cxWidth, int cyWidth, int istepIfAniCur, Pointer hbrFlickerFreeDraw, int diFlags); } </code></pre> <p>Gdi32.dll interface:</p> <pre><code>public interface Gdi32 extends Library { public static Gdi32 INSTANCE = (Gdi32) Native .loadLibrary("Gdi32", Gdi32.class); /** http://msdn.microsoft.com/en-us/library/dd183489(VS.85).aspx */ public Pointer CreateCompatibleDC(Pointer hdc); /** http://msdn.microsoft.com/en-us/library/dd183488(VS.85).aspx */ public Pointer CreateCompatibleBitmap(Pointer hdc, int nWidth, int nHeight); /** http://msdn.microsoft.com/en-us/library/dd162957(VS.85).aspx */ public Pointer SelectObject(Pointer hdc, Pointer hgdiobj); /** http://msdn.microsoft.com/en-us/library/dd145078(VS.85).aspx */ public int SetPixel(Pointer hdc, int X, int Y, int crColor); /** http://msdn.microsoft.com/en-us/library/dd144909(VS.85).aspx */ public int GetPixel(Pointer hdc, int nXPos, int nYPos); /** http://msdn.microsoft.com/en-us/library/dd183539(VS.85).aspx */ public boolean DeleteObject(Pointer hObject); /** http://msdn.microsoft.com/en-us/library/dd183533(VS.85).aspx */ public boolean DeleteDC(Pointer hdc); } </code></pre>
Read .NET configuration from database <p>The .NET 2.0 and up configuration system is quite powerful and extensible - as long as you don't want to change the fact it all comes from XML files in the filesystem.</p> <p>In my requirement, I cannot change files since my app runs in a managed environment outside my reach - but I could change the SQL Server database.</p> <p>So I am looking at storing configuration files or sections in a SQL table - but how can I tie the .NET 2.0 configuration system into this??</p> <p>Is there a way to write a "custom config provider" that will read its config sections not from a *.config file in the file system, but from a table in the SQL database??</p> <p>I've been looking at creating my own custom ConfigurationSection or ConfigurationElement, or even a custom Configuration per se - but it seems I always end up back at the point that I can extend the config-system in the filesystem as much as I like, but I can't make it read my XML fragments from a database table.....</p> <p>What am I missing? Has someone done this already and care to explain / share? </p> <p>Thanks! Marc</p> <p>PS: I also tried to just read the config XML into a string, and then deserializing it into the appropriate e.g. ServiceModelConfigSection - that doesn't work, unfortunately, because the ConfigSection base class somehow doesn't implement a method that is required for it to be XML serializable ........ (YIKES!!!)</p>
<p>There's an article here that talks about doing what you are talking about:</p> <blockquote> <p><a href="http://www.wrox.com/WileyCDA/Section/Redirecting-Configuration-with-a-Custom-Provider.id-291932.html" rel="nofollow">http://www.wrox.com/WileyCDA/Section/Redirecting-Configuration-with-a-Custom-Provider.id-291932.html</a></p> </blockquote> <p>In summary what they do is create a derived version of ProtectedConfigurationProvider, which is typically used to encrypt .config files. In the Decrypt method, instead of decrypting the configuration information, it's retrieved from a database.</p>
How to model diffrent views (roles) on a resource? <p>How can I model roles views restfully?</p> <p>Lets say I have a resource that can be viewed by a buyer or a seller (some content is shared between them on the resource, and some is unique to each one of them)</p> <p>Should i make them a seperate resource: /resource/1/buyer, /resource/1/seller</p> <p>or should i pass a format: /resource/1?viewer=seller</p>
<p>I wouldn't put it anywhere. Instead, I'd have the same URL display the applicable parts of the resource based on the authenticated user.</p> <p>User's roles are already decided upon when authenticating, makes no sense to require duplicating the data in the query. Imagine you have a complex user permission system. Would you then have the user duplicate their whole ACL in the URL? :/ This way the user doesn't even have to be aware of it's roles. </p> <p>If the views are fundamentally different (e.g. don't share any fields at all or fields have different semantics), then I'd create two resources (/auction/1/buyer-info, /auction/1/seller-info). But this likely isn't the case here.</p> <p>If there actually are multiple views of the same resource between which the <em>user can choose</em>, then I'd put the view in the query parameter (?view=simple), since it doesn't pertain to the resource itself, but actually is the "parameter of the query". But keep in mind that the query parameter here is "view", not "viewer" (like in your example), which IMO is an important difference.</p> <p>By following this three approaches, you can cache the resource and then strip the relevant data from it based on a) the current user and b) the view query parameter.</p>
detect browser font size <p>Is it possible to detect browser font size? Also is it possible to dedect new font size when user changes the font size from menu selection? Many thanks for everybody help. Best regards.</p>
<p>Well, it is possible, but my raven sitting on a crystal ball tells me not to tell you how, but to ask you what you want to achieve. Most likely, you want a webpage to look good no matter what the font-size is. For that, I recommend the <a href="http://www.w3.org/TR/CSS21/syndata.html#length-units">CSS units <code>em</code>, <code>ex</code> etc</a>.</p>
Why is it very slow for a Regex to finish a XML file of 3000 lines? <p>I noticed that it is very slow for a Regex to finish a XML file with 3000 lines [1]:</p> <pre><code>\(&lt;Annotation\(\s*\w\+="[^"]\{-}"\s\{-}\)*&gt;\)\@&lt;=\(\(&lt;\/Annotation\)\@!\_.\)\{-}"MATCH\_.\{-}\(&lt;\/Annotation&gt;\)\@= </code></pre> <p>I always thought that Regexes are efficient. Why does it take so long to finish the Regex? </p> <p><strong>[1]</strong> <a href="http://stackoverflow.com/questions/736376/how-can-i-repeatedly-match-from-a-until-b-in-vim">http://stackoverflow.com/questions/736376/how-can-i-repeatedly-match-from-a-until-b-in-vim</a></p>
<p>It depends on the regular expression itself if it is efficient or not. What it makes inefficient is backtracking. And to avoid this, the regular expression has to be as distinct as possible.</p> <p>Let’s take the regular expression <code>a.*b</code> as an example and apply it to the string <code>abcdef</code>. The algorithm will first match the literal <code>a</code> in <code>a.*b</code> to the <code>a</code> in <code>abcdef</code>. Next the expression <code>.*</code> will be processed. In the normal greedy mode, where multipliers are expanded to the maximum, it will match to the whole rest <code>bcdef</code> in <code>abdef</code>. Than the last literal <code>b</code> in <code>a.*b</code> will be processed. But as the end of the string is already reached and a mulpliplier is in use, the algorithm will try backtracking to match the whole pattern. The match of <code>.*</code> (<code>bcdef</code>) will be decreased by one character (<code>bcde</code>) and the algorithm tries to comply the rest of the pattern. But the <code>b</code> in <code>a.*b</code> doesn’t match the <code>f</code> in <code>abcdef</code>. So <code>.*</code> will be decreased by one more character until it matches the empty string (thus <code>.</code> is repeated zero times) and the <code>b</code> in <code>a.*b</code> matches the <code>b</code> in <code>abcdef</code>.</p> <p>As you can see, <code>a.*b</code> applied to <code>abdef</code> needs 6 backtracking approaches for <code>.*</code> until the whole regular expression matches. But if we alter the regular expression and make it distinct by using <code>a[^b]*b</code> instead, there is be no backtracking necessary and the regular expression can be matches within the first approach.</p> <p>And if you now consider using lazy modifiers instead, I’ve to tell you, that this rules apply to every modifier, both the greedy and lazy modifiers. The difference is instead of first expanding the match to the maximum and than doing backtracking by decreasing the match one character at a time (greedy), the lazy modifiers will first be expanded to the minimum match and than be increased one character at a time.</p>
How to release the unused capacity of a string <p>I am dealing with a lot of strings in my program. These string data don't change through out the whole life time after they being read into my program.</p> <p>But since the C++ string reserves capacity, they waste a lot of space that won't be used for sure. I tried to release those spaces, but it didn't work.</p> <p>The following is the simple code that I tried:</p> <pre><code>string temp = "1234567890123456"; string str; cout &lt;&lt; str.capacity() &lt;&lt; endl; str.reserve(16); cout &lt;&lt; str.capacity() &lt;&lt; endl; // capacity is 31 on my computer str += temp; cout &lt;&lt; str.capacity() &lt;&lt; endl; str.reserve(16); cout &lt;&lt; str.capacity() &lt;&lt; endl; // can't release. The capacity is still 31. </code></pre> <p>(The compiler is Visual C++)</p> <p>How could I release it?</p>
<p>When you call <code>reserve</code>, you're making a <em>request</em> to change the capacity. Implementations will only guarantee that a number equal to or greater than this amount is reserved. <strong>Therefore, a request to <em>shrink</em> capacity may be safely ignored by a particular implementation.</strong></p> <p>However, I encourage you to consider whether this isn't premature optimization. Are you sure that you're really making so many strings that it's a memory bottleneck for you? Are you sure that it's actually memory that's the bottleneck?</p> <p>From the documentation for <code>reserve</code>:</p> <blockquote> <p>This can expand or shrink the size of the storage space in the string, although notice that the resulting capacity after a call to this function is not necessarily equal to <code>res_arg</code> but can be either equal or greater than <code>res_arg</code>, therefore shrinking requests may or may not produce an actual reduction of the allocated space in a particular library implementation. In any case, it never trims the string content (for that purposes, see resize or clear, which modify the content).</p> </blockquote>
C++: Debugging memory leaks in reference counting system <p>I've got a number of reference counted classes in some of my applications, and also in dlls those applications use, all inheriting from and implementing a IRefCounted interface.</p> <p>In order to help with finding the source of these memory leaks I want each application to maintain a list of all these refrence counted classes in existance.</p> <p>The problem is the managing of instances of these lists such that their useage does not effect the usage of my classes (eg I don't need to pass a pointer to a list around all the time, instead somehow attaching it to the process).</p> <p>-Theres a good chance several of these applications may be running at once, and using the same dll. Each application needs its own object list, and all the dlls etc loaded by that application need to use that list (but rember that one dll may be loaded by multiple applications...).<br /> -The list must be destroyed after every other global and static variable in application, so the objects left in the list when its destructed are ones that truley were not correctly releashed.</p> <p>I then will simply add a breakpoint to the list's destructor so I can look through any unallocated objects in the debugger.</p>
<p><del>I'm guessing you're using COM.</del> You'll probably need to find some way of having a <a href="http://www.ddj.com/cpp/184402026" rel="nofollow">weak pointer</a> so that the registry of instantiated objects doesn't prevent them from being destructed.</p> <p>If you can modify all the classes, you could inject a static member to keep track of all instances and have the destructor of an instance remove itself from the static member. For example, you could use a base class or utility class like the following:</p> <pre><code>class InstanceRegistry { protected: InstanceRegistry() { registry.insert(this); } ~InstanceRegistry() { registry.remove(this); } private: static SomeContainerType&lt;InstanceRegistry*&gt; registry; }; </code></pre> <p>Extra work would need to be done if you want a different registry for different types of classes, etc.</p>
Variable Dumping in C++ <p>Is it possible to do a 'dump' on complex structures or even arrays in C++, in order to visually be able to check out what they've got inside them?</p> <p>I'm thinking of something similar to print_r() or var_dump() in PHP.</p> <p>Cheers, -Fin</p>
<p>The short answer is: no, unless you manually write such a routine yourself.</p> <p>Which is often not a bad idea, but it has the usual problems of getting out of sync with the class if you are adding/changing members often. This is unavoidable because C++ lacks any form of introspection into <code>struct</code>s.</p> <p>If you decide to go that way, the best thing to do is to write an overload for <code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, MyClass const&amp;)</code>, which will enable your class to be printed to any IOStreams output stream.</p>
How to create an active link in RSS? <p>In RSS, for example if I wanna add a link for the channel: Part of the RSS code:</p> <pre><code>&lt;link&gt; &lt;a href="http://www.nytimes.com/2009/04/10/technology/internet/10google.html?ref=technology"/&gt; &lt;/link&gt; </code></pre> <p>And now here is the XSL code:</p> <pre><code> &lt;span&gt; &lt;xsl:value-of select="channel/link"/&gt;&lt;/span&gt; </code></pre> <p>The problem here is that when I preview the code, the link is not actually be active in the browser (means that it is still look like normal text and cannot click on it on the browser)</p> <p>Would you please help me how to make a link in RSS code so that it could be finally be active in the browser? Thank you</p>
<p>I would use </p> <pre><code>&lt;link&gt;http://www.nytimes.com/2009/04/10/technology/internet/10google.html?ref=technology&lt;/link&gt; </code></pre> <p>Then in the XSLT, create an <code>a</code> tag and set the <code>href</code> attribute to that value. I don't know XSLT that well, but this might be possible or something to hash away at:</p> <pre><code>&lt;span&gt; &lt;a&gt; &lt;xsl:attribute name="href"&gt; &lt;xsl:value-of select="channel/link"/&gt; &lt;/xsl:attribute&gt; Some text &lt;/a&gt; &lt;/span&gt; </code></pre>
Usage of ORMs like NHibernate when there are many associations - performance concerns <p>I have created an application (a web-based application) which now has a large number of associations. Simply put, an Account:</p> <ul> <li>has many Users</li> <li>has Settings</li> <li>has many Projects</li> </ul> <p>Similarly a Project:</p> <ul> <li>has many Items</li> </ul> <p>A User:</p> <ul> <li>has many Tasks</li> </ul> <p>And so on, with loads more associations. Nothing particularly unusual about that I hope. I chose to use NHibernate to give me a nice set of persistent classes with mappers defining all of the associations.</p> <p>But is this approach right? On every request to the application the Account is loaded (because it is needed) and this then requests a large amount of data from the DB that is not required. Lazy loading is an option, but I don't know if my initial approach couldn't be better. All I want at that stage is the Account and associated Settings so should the mapping reflect this? Trouble is I want things like all the Projects for an Account at other points so I need the mappers to reflect all of the associations.</p> <p>My concern is that lazy-loading may just be compensating for a bad initial architecture on my part. I am well aware that this may just be a result of my as-yet poor knowledge of the inner workings of NHibernate. As a result I'd be grateful for any suggestions on good practice.</p>
<p>It is generally good practise with NHibernate to enable lazy loading for most associations and objects by default unless you know you're always going to need the associated data. Then you can switch to eager loading selectively just for items where that is more efficient when you come to the optimisation stage.</p>
Random behavior differences between C# and Java: the seed <p>I have a Random into a class which aims to generate random sequences in different contexts: this is the result of a porting from Java code. In the Java version everything works fine since the java.lang.Random class has the method setSeed, which permits the change of the seed value dynamically.</p> <pre><code>Random rnd = new Random(); ... rnd.nextInt(); ... rnd.setSeed(seedValue); </code></pre> <p>This generates a consistent result, since each time the seed value is set, the result is random.</p> <p>Unfortunately in C# the behavior is much different, since the Random class needs the seed to be set at construction:</p> <pre><code>Random rnd = new Random(seedValue); ... rnd.Next(); ... </code></pre> <p>So I have to build a new Random instance each time with the given seed, which in some spare cases generates the same value of a previous call.</p> <p>Is it a way to set the seed of a Random instance in C# dynamically, without losing the consistency of the instance globally?</p> <p>Thank you very much!</p>
<p>Typically I create a single instance of Random for my application and after setting the seed on instantiation can rely on each call to Next giving me a new random number. The trick is to make sure the seed is as random as possible. The use of Random in a C# app is a good example of where a Singleton is a good fit.</p> <p>There are a variety of ways to get differing strengths of randomness in your seed and there are some good SO questions dealing with that.</p> <p>The example below is the approach I use.</p> <pre><code>m_randomURL = "https://www.random.org/cgi-bin/randnum?num=1&amp;min=1&amp;max=1000000000"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(m_randomURL); StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream()); Random rand = new Random(Convert.ToInt32(stIn.ReadToEnd())); </code></pre> <p>random.org uses atmospheric noise to generate the randomness and is apparently used for lotteries and such.</p>
What is the difference between debug.write and Trace.write? <p>What is the difference between <strong>debug.write</strong> and <strong>Trace.write</strong>? When should each be used?</p>
<p>In the typical release build configuration, the <code>Debug</code> class is disabled and does nothing. <code>Trace</code>, however, can still be used in the release. You would typically use <code>Debug.Write</code> for stuff you only need when debugging and which is too verbose for production.</p> <p>Here's a good article on <code>Debug, Trace</code> etc: <a href="http://www.codeproject.com/KB/trace/debugtreatise.aspx">http://www.codeproject.com/KB/trace/debugtreatise.aspx</a></p> <p>However, I'm more inclined to use logging libraries like <strong>log4net</strong> which can be reconfigured on the fly. So you can still turn on full logging in production if you're investigating problems with your application.</p>
Does anyone know how sites are generating the Apple App Store updated apps feeds? <p>A lot of sites have rss feeds for updated and new apps on the Apple iPhone App Store. However, Apple's rss feed generator only shows feeds for the top 100 free/paid apps. So how can I generate my own database of new/updated apps in the same fashion as all these folks are? What magic feed are they accessing?</p>
<p>Apple have an <a href="http://itunes.apple.com/rss/generator/" rel="nofollow">RSS generator for iTunes</a>.</p> <blockquote> <p>Provide the information requested below, then click Generate to view the feed URL. These feeds automatically update to reflect iTunes' top charts and new content, so you'll always be up to date with the latest in the iTunes Store.</p> </blockquote> <p>e.g. Top 10 apps is <code>http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topfreeapplications/sf=143441/limit=10/xml</code></p>
iPhone AdMob ad <p>I have the following two questions, I tried googling these, but didn't find any luck. Please help me.</p> <ol> <li><p>I have integrated AdMob ad to my iphone application. when the admob view is clicked, safari gets opened, and if there is any error in loading the ad, it displays an error message saying "safari cannot open the page because too many redirects occurred" there is a ok button in the error pop up, when ok button is clicked only the error popup is closed and control is not coming back to the application. How do we make it come back to the application? </p></li> <li><p>How to add auto-close functionality to the adMob ad?</p></li> </ol>
<p>(1) Once control is transfered to safari, iPhone OS starts shutting your app down. Control will not transfer back to your app - the user will need to close safari and restart your application. </p> <p>The only way to display web content in an iPhone app without your app closing is by embedding the web browser inside your application. However, I expect your ad network insist that their adverts open in safari to ensure that the content isn't tampered with.</p> <p>(2) Likewise, there's no way to get back to your app once safari started loading. I suggest you focus on fixing whatever is wrong with the implementation of the ad code.</p>
questions related to DTD and schema: finding the missing words <p>This question are part of a quiz. I've finished already but some questions were answered incorrectly. However, the teacher don't upload the solution for those questions. Would you please help me for the solution of such questions? I need to know exactly the answer in order to start revise for the final exam</p> <p>This question related to DTD and schema:</p> <p>1) Identify the missing word. _____ is used as a pointer to a notation that makes an association between a name and a special type of content.</p> <p>Selected Answer (Incorrect): ADATA </p> <p>2) An example of syntax for an _____ declaration would be &lt;ATTLIST MEMO (CON|PUB) "PUB" ></p> <p>Selected Answer (Incorrect): attribute type</p> <p>3) Identify the missing word. (1)_____ entities are also known as (2)_____ entities.</p> <p>Selected Answer (Incorrect): (1)parsed, (2)text </p> <p>4) Which of the following is an advantage of XML Schema over DTDs?</p> <p>Selected Answer (Incorrect): It is often simpler to express constraints using XML Schema.</p>
<p>Was this multiple choice? What were the other choices?</p> <p>For 1 and 2 I can guess:</p> <p>1) NDATA (NDataDecl)</p> <p>2) attribute-list</p> <p>(What kind of exam needs you to know horrible old cruft like Notations, huh? Yuck!)</p>
How to hide datasource passwords in in Tomcat JMX Beans <p>Tomcat exposes a good wealth of information about its internals via JMX. You can see data source, connector usage, thread pools, you name it. </p> <p>However, it also exposes the password of the JDBC datasource (Catalina->DataSource->javax.sql.DataSource->...). Is there any way to hide this information from being published ? </p> <p>We've found a way to manage the exposed JMX information via modifying the mbeans-descriptors.xml files contained within the jar files of the Tomcat distribution, however, we're looking for a way to do this without modifying the distribution. </p> <p>So, how can we hide the password field of a JDBC connection in Tomcat exposed JMX beans ? </p> <p>Regards, Bulent Erdemir</p>
<p>Just restrict access at JMX level to ones who are authorized.</p>
When to join name and when not to? <p>Most languages give guidelines to separate different words of a name by underscores (python, C etc.) or by camel-casing (Java). However the problem is when to consider the names as separate. The options are:</p> <p>1) Do it at every instance when separate words from the English dictionary occur e.g. create_gui(), recv_msg(), createGui(), recvMsg() etc.</p> <p>2) Use some intuition to decide when to do this and when not to do this e.g. recvmsg() is OK, but its better to have create_gui() .</p> <p>What is this intuition?</p> <p>The question looks trivial. But it presents a problem which is common and takes at least 5 seconds for each instance whenever it appears.</p>
<p>I always do your option 1, and as far as I can tell, all modern frameworks do.</p> <p>One thing that comes to mind that just sticks names together is the standard C library. But its function names are often pretty cryptic anyway.</p>
Ensuring methods are only ever executed by the main thread <p>I have an objective-c class whose methods I only ever want to be called from the main thread.</p> <p>I could achieve this by adding something like this to each selector:</p> <pre><code>- (void) exampleSelector: (id) param { if (![NSThread isMainThread]) { [self peformSelectorOnMainThread:@selector(exampleSelector:) withObject:param waitUntilDone:YES]; return; } // Do stuff it's not safe to do outside the main thread } </code></pre> <p>However it seems a bit of a pain to add this to every single selector. Is there any way I can automatically intercept all calls to objects of this class, check what thread it's in, and use performSelectorOnMainThread if it's not the main thread?</p>
<p>Hmm. I'm not sure if it's possible to do this; I can't think of a way to do so. What I would be inclined to do instead is to replace the object with a proxy. The proxy will be responsible for forwarding invocations to the object in the correct thread.</p> <pre><code>@interface Forwarder : NSObject { id recipient; } - (Forwarder *)initWithRecipient:(id)inRecipient; @end @implementation Forwarder - (Forwarder *)initWithRecipient:(id)inRecipient { [inRecipient retain]; recipient = inRecipient; return self; } - (void)dealloc { [recipient release]; [super dealloc]; } - (void)forwardInvocation:(NSInvocation *)anInvocation { if ([recipient respondsToSelector: [anInvocation selector]]) { if (![NSThread isMainThread]) { // Note: only works with methods that take one argument. Should add // error handling for other methods id argument; [invocation getArgument: &amp;argument atIndex: 2]; [recipient performSelectorOnMainThread: [anInvocation selector] withObject: argument waitUntilDone: YES]; } else { [anInvocation invokeWithTarget:recipient]; } } else { [super forwardInvocation:anInvocation]; } } - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { if ([recipient respondsToSelector: aSelector]) return [recipient methodSignatureForSelector: aSelector]; else return [super methodSignatureForSelector: aSelector]; } @end </code></pre>
RegExp: How to extract usernames out of Tweets (twitter.com)? <p>I have the following example tweet:</p> <p>RT @user1: who are @thing and @user2?</p> <p>I only want to have <em>user1</em>, <em>thing</em> and <em>user2</em>.</p> <p>What regular expression can I use to extract those three names?</p> <p>PS: A username must only contain letters, numbers and underscores.</p>
<p>Tested:</p> <pre><code>/@([a-z0-9_]+)/i </code></pre> <p><hr /></p> <p>In Ruby (irb):</p> <pre><code>&gt;&gt; "RT @user1: who are @thing and @user2?".scan(/@([a-z0-9_]+)/i) =&gt; [["user1"], ["thing"], ["user2"]] </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.findall("@([a-z0-9_]+)", "RT @user1: who are @thing and @user2?", re.I) ['user1', 'thing', 'user2'] </code></pre> <p>In PHP:</p> <pre><code>&lt;?PHP $matches = array(); preg_match_all( "/@([a-z0-9_]+)/i", "RT @user1: who are @thing and @user2?", $matches); print_r($matches[1]); ?&gt; Array ( [0] =&gt; user1 [1] =&gt; thing [2] =&gt; user2 ) </code></pre>
What's the best way to enable/disable some controls amongst multiple controls under various different condition? <p>I am new to professional programming, I am writing C# but I think this isn't exactly C# specific. Anyway, I want to ask what's the best way to enable/disable some controls amongst multiple controls under various different condition?</p> <p>Let's say, there is a GUI with some rows, each represent a person. There are also some buttons, representing some actions, say, "Stand, Sit, Walk, Jump, Eat, Watch TV, Wake, Sleep" and there are some conditions, like if someone is sitting he can eat and watch tv(i.e. enable those button) but can't jump(disable it), if someone is standing he cant sleep........ and so on. Also, the state change is not solely based on an button click. Like, he might just wake up himself after some time or, say, finished eating. </p> <p>It seems that the most naive way is to write the .Enabled = true/false; code for n states X m buttons times, and check it for every user or non user triggered state change. Is there some better/faster/less-error-prone way to do that?</p> <p>Also, what are this sort of thing called? I don't know a proper term in English to describe it well and so I can't google it myself.... Please help. Thank you very much.</p>
<p>I would bind the <code>Enabled</code> properties to <code>Can*</code> (<code>CanWalk</code>, <code>CanJump</code>, etc.) properties of the class, implement <code>INotifyPropertyChanged</code>, and check each potentially affected property when the object's state changes.</p> <p>The advantage of this method is the Person class and the UI don't need to know anything about each other. Also, implementing <code>INotifyPropertyChanged</code> eliminates superfluous polling of the class's properties after every state change.</p> <p>If you don't want to use complex databinding, you can still listen for the <code>PropertyChanged</code> events and update the UI manually.</p> <p>For example:</p> <pre><code>partial class Person : INotifyPropertyChanged { bool _IsSleeping, _IsSitting; public bool IsSleeping { get { return _IsSleeping; } set { if(_IsSleeping != value) { _IsSleeping = value; OnIsSleepingChanged(); } } } public bool IsSitting { get { return _IsSitting; } set { if(_IsSitting != value) { _IsSitting = value; OnIsSittingChanged(); } } } protected virtual void OnIsSleepingChanged() { NotifyPropertyChanged("IsSleeping"); CheckCanJumpChanged(); } protected virtual void OnIsSittingChanged() { NotifyPropertyChanged("IsSitting"); CheckCanJumpChanged(); } bool CanJump_Old; public bool CanJump { get { return !(IsSleeping || IsSitting); } } void CheckCanJumpChanged() { if(CanJump != CanJump_Old) { CanJump_Old = CanJump; NotifyPropertyChanged("CanJump"); } } //INotifyPropertyChanged helper method private void NotifyPropertyChanged(String prop) { var hand = PropertyChanged; if (hand != null) hand(this, new PropertyChangedEventArgs(prop)); } } </code></pre>
SQLAlchemy many-to-many orphan deletion <p>I'm trying to use SQLAlchemy to implement a basic users-groups model where users can have multiple groups and groups can have multiple users.</p> <p>When a group becomes empty, I want the group to be deleted, (along with other things associated with the group. Fortunately, SQLAlchemy's cascade works fine with these more simple situations).</p> <p>The problem is that cascade='all, delete-orphan' doesn't do exactly what I want; instead of deleting the group when the group becomes empty, it deletes the group when <em>any</em> member leaves the group.</p> <p>Adding triggers to the database works fine for deleting a group when it becomes empty, except that triggers seem to bypass SQLAlchemy's cascade processing so things associated with the group don't get deleted.</p> <p>What is the best way to delete a group when all of its members leave and have this deletion cascade to related entities.</p> <p>I understand that I could do this manually by finding every place in my code where a user can leave a group and then doing the same thing as the trigger however, I'm afraid that I would miss places in the code (and I'm lazy).</p>
<p>The way I've generally handled this is to have a function on your user or group called leave_group. When you want a user to leave a group, you call that function, and you can add any side effects you want into there. In the long term, this makes it easier to add more and more side effects. (For example when you want to check that someone is allowed to leave a group).</p>
Why does the empty string not match as Seq.empty? <p><strong>EDIT: This was an old bug long since fixed in Scala 2.8 and later</strong></p> <p>During some experimentation around question <a href="http://stackoverflow.com/questions/740563/pattern-matching-a-string-as-seqchar">Pattern matching a String as Seq[Char]</a>, I ran across another weird matching phenomenon. Consider the following code that treats a string as a sequence of characters:</p> <pre><code>def %%&amp;#(input: String) : String = { val uha : Seq[Char] = input uha match { case Seq() =&gt; "Empty" case Seq(first @ _, 'o', 'o') =&gt; "Bar" case _ =&gt; "Oh" } } </code></pre> <p>Calling input on the empty String <code>""</code> correctly yields <code>"Empty"</code>.</p> <p>However, if I rewrite the first match clause as </p> <pre><code>case Seq.empty =&gt; "Empty" </code></pre> <p>the matching of <code>""</code> fails and matches the default clause instead.</p> <p>Walking through the Scala library source code (which you shouldn't have to do in an ideal world :-) ) I believe that both <code>Seq()</code> and <code>Seq.empty</code> will result in <code>RandomAccessSeq.empty</code>. Apparently, this does not concur with the phenomenon described above because only <code>Seq()</code> matches the empty String. </p> <p>UPDATE: Upon some further experimentation this question can be narrowed down to the following: </p> <pre><code>val list = List() &gt;&gt;&gt; list2: List[Nothing] = List() val emptySeq = Seq.empty list == emptySeq &gt;&gt;&gt; res1: Boolean = false </code></pre> <p>This basically means that an empty <code>Seq</code> does not automatically equal <code>Seq.empty</code> . So when matching against a constant (as opposed to using an extractor as suggested by starblue) this unequality leads to the failing match. The same is true when interpreting the empty <code>String</code> as a sequence.</p>
<p>This appears to be a bug in the library. Do you want to file the bug or shall I?</p> <pre><code>scala&gt; Seq.empty match {case Seq() =&gt; "yup"; case _ =&gt; "nope"} res0: java.lang.String = yup scala&gt; Seq() match {case Seq.empty =&gt; "yup"; case _ =&gt; "nope"} res1: java.lang.String = yup scala&gt; ("" : Seq[Char]) match {case Seq() =&gt; "yup"; case _ =&gt; "nope"} res2: java.lang.String = yup scala&gt; ("" : Seq[Char]) match {case Seq.empty =&gt; "yup"; case _ =&gt; "nope"} res3: java.lang.String = nope </code></pre>
ABC Virtual OStream Insertion Operator <p>Consider the following snippet:</p> <pre><code>struct ObjectInterface { virtual ~ObjectInterface() {} virtual void Print(std::ostream&amp; target) const = 0; }; struct Foo : ObjectInterface { virtual void Print(std::ostream&amp; target) const { target &lt;&lt; "Foo"; } }; struct Bar : ObjectInterface { virtual void Print(std::ostream&amp; target) const { target &lt;&lt; "Bar"; } }; </code></pre> <p>Is there any way to change <code>Print</code> in <code>ObjectInterface</code> to the standard "<code>std::ostream&amp; operator&lt;&lt;</code>"-type of output? I can't make it work.</p> <p>EDIT: I'm basically trying to figure out if I can make <code>friend</code> work with <code>virtual</code>.</p>
<p>You need a free function:</p> <pre><code>ostream &amp; operator &lt;&lt; ( ostream &amp; os, const ObjectInterface &amp; oi ) { oi.Print( os ); return os; } </code></pre>
Is it possible to delete both ends of a large file without copying? <p>I would like to know if it is possible, using Windows and c++, to take a large video file (several gigabytes in length) and delete the first and last few hundred megabytes of it “in-place”.</p> <p>The traditional approach of copying the useful data to a new file often takes upwards of 20 minutes of seemingly needless copying.</p> <p>Is there anything clever that can be done low-level with the disk to make this happen? </p>
<p>Sure, it's possible in theory. But if your filesystem is NTFS, be prepared to spend <em>a few months</em> learning about all the data structures that you'll need to update. (All of which are officially undocumented BTW.)</p> <p>Also, you'll need to either</p> <ol> <li>Somehow unmount the volume and make your changes then; or</li> <li>Learn how to write a kernel filesystem driver, buy a license from MS, develop the driver and use it to make changes to a live filesystem.</li> </ol> <p>It's a bit easier if your filesystem is something simpler like FAT32. But either way: in short, it <em>might</em> be possible, but even if it is it'll take years out of your life. My advice: don't bother.</p> <p>Instead, <strong>look at other ways you could solve the problem</strong>: e.g. by using an <a href="http://www.avisynth.org/" rel="nofollow">avisynth</a> script to serve just the frames from the region you are interested in.</p>
parse an XML with SimpleXML which has multiple namespaces <p>I have this ugly XML which has alot of namespaces on it, when I try to load it with simpleXML if i indicate the first namespace I'd get an xml object ,but following tags with other namespaces would not make it to the object. </p> <p>How can I parse this XML ?</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soap-env:Header&gt; &lt;eb:MessageHeader xmlns:eb="http://www.ebxml.org/namespaces/messageHeader" eb:version="1.0" soap-env:mustUnderstand="1"&gt; &lt;eb:From&gt; &lt;eb:PartyId eb:type="URI"&gt;wscompany.com&lt;/eb:PartyId&gt; &lt;/eb:From&gt; &lt;eb:To&gt; &lt;eb:PartyId eb:type="URI"&gt;mysite.com&lt;/eb:PartyId&gt; &lt;/eb:To&gt; &lt;eb:CPAId&gt;something&lt;/eb:CPAId&gt; &lt;eb:ConversationId&gt;moredata.com&lt;/eb:ConversationId&gt; &lt;eb:Service eb:type="compXML"&gt;theservice&lt;/eb:Service&gt; &lt;eb:Action&gt;theaction&lt;/eb:Action&gt; &lt;eb:MessageData&gt; &lt;eb:MessageId&gt;a certain messageid&lt;/eb:MessageId&gt; &lt;eb:Timestamp&gt;2009-04-11T18:43:58&lt;/eb:Timestamp&gt; &lt;eb:RefToMessageId&gt;mid:areference&lt;/eb:RefToMessageId&gt; &lt;/eb:MessageData&gt; &lt;/eb:MessageHeader&gt; &lt;wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/12/secext"&gt; &lt;wsse:BinarySecurityToken valueType="String" EncodingType="wsse:Base64Binary"&gt;an impresive binary security toekn&lt;/wsse:BinarySecurityToken&gt; &lt;/wsse:Security&gt; &lt;/soap-env:Header&gt; &lt;soap-env:Body&gt; &lt;SessionCreateRS xmlns="http://www.opentravel.org/OTA/2002/11" version="1" status="Approved"&gt; &lt;ConversationId&gt;the goodbye token&lt;/ConversationId&gt; &lt;/SessionCreateRS&gt; &lt;/soap-env:Body&gt; &lt;/soap-env:Envelope&gt; </code></pre> <p>im trying to parse it with the following code</p> <pre><code>&lt;?php $xml = simplexml_load_string($res,NULL,NULL,"http://schemas.xmlsoap.org/soap/envelope/"); ?&gt; </code></pre> <p>but the $xml object would only contain the following</p> <pre><code>SimpleXMLElement Object ( [Header] =&gt; SimpleXMLElement Object ( ) [Body] =&gt; SimpleXMLElement Object ( ) ) </code></pre>
<p>I think you need to register the namespacing and access with XPath. Something like the following should get you going (I haven't the facility to test this).</p> <pre><code>$xml = simplexml_load_string($res, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/"); $xml-&gt;registerXPathNamespace('soap-env', 'http://schemas.xmlsoap.org/soap/envelope/'); $xml-&gt;registerXPathNamespace('eb', 'http://www.ebxml.org/namespaces/messageHeader'); $xml-&gt;registerXPathNamespace('wsse', 'http://schemas.xmlsoap.org/ws/2002/12/secext'); </code></pre> <p>Then you can do something like:</p> <pre><code>foreach($xml-&gt;xpath('//eb:MessageHeader') as $header) { var_export($header-&gt;xpath('//eb:CPAId')); // Should output 'something'. } </code></pre> <p>You may not need to register the namespacing, thinking about it, as they are alredy present in the XML. Not sure on this though, would need to test.</p> <p>Hope this helps.</p>
help requires in winavr <p>i am trying to send ---.hex file to my siemens C55 throught serial port but while doing do i am getting an error </p> <blockquote> <p>"make.exe" program avrdude -p atmega8 -P com2 -c stk200 -U flash:w:gsm_remote.hex avrdude: port name "com2" is neither lpt1/2/3 nor valid number avrdude: can't open device "com2"</p> </blockquote> <p>avrdude: failed to open parallel port "com2"</p> <p>make.exe: *** [program] Error 1</p> <p>please guide me what should i do the source code is also avaliable at <a href="http://www.4shared.com/file/88235332/4b2370f8/080324-11.html" rel="nofollow">http://www.4shared.com/file/88235332/4b2370f8/080324-11.html</a></p>
<p>I'm not sure how to set the avrdude port on windows (it's described somewhere in the documentation), but I think you're making a bigger mistake here. Siemens C55 (mobile phone, right?) does not run on atmega. It uses Infineon C16X (most probably) like all the siemens phones from 5X/6X series. I don't think this code will work on siemens hardware.</p> <p>Also Siemens C55 doesn't include the stk200 interface - if you need a flasher for it, look for more information on <a href="http://forum.gsmhosting.com/vbb/" rel="nofollow">http://forum.gsmhosting.com/vbb/</a></p>
How do I set the ASP.NET version for a Virtual Directory using IIS Manager 7.0? <p>In the old version of IIS Manager, I could just right-click on a VD, hit properties, and then in the ASP.NET tab pick the version of ASP.NET I wanted to run. Does anyone know if that is still possible? I am running a localhost instance of IIS on my Vista box and I am not used to the new UI that IIS 7 comes with.</p>
<p>You need to change the application pool - the ASP.NET version is set at the application pool level.</p> <p>Left click the virtual directory in IIS manager, then on the far right of the screen click on 'advanced settings' The application pool is at the top of the list there.</p> <p>If you need to, you can add a new application pool by right clicking the 'application pools' icon in the left pane and selected 'Add Application Pool'</p>
python write string directly to tarfile <p>Is there a way to write a string directly to a tarfile? From <a href="http://docs.python.org/library/tarfile.html">http://docs.python.org/library/tarfile.html</a> it looks like only files already written to the file system can be added.</p>
<p>I would say it's possible, by playing with TarInfo e TarFile.addfile passing a StringIO as a fileobject. </p> <p>Very rough, but works</p> <pre><code>import tarfile import StringIO tar = tarfile.TarFile("test.tar","w") string = StringIO.StringIO() string.write("hello") string.seek(0) info = tarfile.TarInfo(name="foo") info.size=len(string.buf) tar.addfile(tarinfo=info, fileobj=string) tar.close() </code></pre>
Javascript - load events for embed elements <p>If I do an online onload event for embed objects, that seems to work but I can't seem to get the load event working through addEventListener. Is this expected?</p>
<p>Probably, but it may be browser dependent.</p> <p>windows and images and iframes define their load events with addEventListener and attachEvent, but other load events are browser specific.</p> <p>A script or link element's onload doesn't attach in IE, for instance.</p>
Why is \%(\) faster than \(\) in Vim? <p>I am confused by the docs:</p> <blockquote> <p><code>\%(\)</code> A pattern enclosed by escaped parentheses. <code>*/\%(\)* */\%(*</code> <code>*E53*</code> Just like <code>\(\)</code>, but without counting it as a sub-expression. This allows using more groups and it's a little bit faster.</p> </blockquote> <p>Can someone explain the reason for the difference? Is it because of backtracking or something else?</p>
<p>The 'a little bit faster' comment is accurate in that there is a little less bookkeeping to be done, but the emphasis is on 'little bit' rather than 'faster'. Basically, normally, the material matched by <code>\(pattern\)</code> has to be kept so that you can use <code>\3</code> (for the appropriate number) to refer to it in the replacement. The <code>%</code> notation means that <code>vim</code> does not have to keep track of the match - so it is doing a little less work.</p> <p><hr></p> <p>@SimpleQuestions asks:</p> <blockquote> <p>What do you mean by "keep track of the match"? How does it affect speed?</p> </blockquote> <p>You can use escaped parentheses to 'capture' parts of the matched pattern. For example, suppose we're playing with simple C function declarations - no pointers to functions or other sources of parentheses - then we might have a substitute command such as the following:</p> <pre><code>s@\&lt;\([a-zA-Z_][a-zA-Z_0-9]*\)(\([^)]*\))@xyz_\1(int nargs) /* \2 */@ </code></pre> <p>Given an input line such as:</p> <pre><code>int simple_function(int a, char *b, double c) </code></pre> <p>The output will be:</p> <pre><code>int xyz_simple_function(int nargs) /* int a, char *b, double c */ </code></pre> <p>(Why might you want to do that? I'm imagining that I need to wrap the C function <code>simple_function</code> so that it can be called from a language compiled to C that uses a different interface convention - it is based on Informix 4GL, to be precise. I'm using it to get an example - not because you really need to know why it was a good change to make.)</p> <p>Now, in the example, the <code>\1</code> and <code>\2</code> in the replacement text refer to the captured parts of the regular expression - the function name (a sequence of alphanumerics starting with an alphabetic character - counting underscore as 'alphabetic') and the function argument list (everything between the parentheses, but not including the parentheses).</p> <p>If I'd used the <code>\%(....\)</code> notation around the function identifier, then <code>\1</code> would refer to the argument list and there would be no <code>\2</code>. Because <code>vim</code> would not have to keep track of one of the two captured parts of the regular expression, it has marginally less bookkeeping to do than if it had to keep track of two captured parts. But, as I said, the difference is tiny; you could probably never measure it in practice. That's why the manual says 'it allows more groups'; if you needed to group parts of your regular expression but didn't need to refer to them again, then you could work with longer regular expressions. However, by the time you have more than 9 remembered (captured) parts to the regular expression, your brain is usually doing gyrations and your fingers will make mistakes anyway - so the effort is not usually worth it. But that is, I think, the argument for using the <code>\%(...\)</code> notation. It matches the Perl (PCRE) notation '<code>(?:...)</code>' for a non-capturing regular expression.</p>
C#: How can i change the text of a label thats in form1 from another class? <p>im trying to change the text of a label from a class but have been unsuccessful.</p> <p>what i have is that im updating a variable in the class using get{} and set{}. i understand that i need to put or do something within set{} to get it to send the update value from the class back into the form1 class so that it can update the label.</p> <p>could anyone tell me how i could accomplish this? or if there is a way to update the label from within the class, that would be even better.</p> <p>i hope this makes sense and thanks in advance.</p>
<p>You might want to consider using delegates or events and having your classes raise events back to the form, that way your classes will have no knowledge of your form.</p> <p><strong>EXAMPLE</strong></p> <pre><code>class SomeClass { public delegate void UpdateLabel(string value); public event UpdateLabel OnLabelUpdate; public void Process() { if (OnLabelUpdate != null) { OnLabelUpdate("hello"); } } } public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void UpdateLabelButton_Click(object sender, EventArgs e) { SomeClass updater = new SomeClass(); updater.OnLabelUpdate += new SomeClass.UpdateLabel(updater_OnLabelUpdate); updater.Process(); } void updater_OnLabelUpdate(string value) { this.LabelToUpdateLabel.Text = value; } } </code></pre>
Help storing an intrusive_ptr of a template class in a std::map <p>I have a small template class of type Locker contained within a boost::intrusive_ptr that I want to store inside a std::map:</p> <pre><code>template &lt;typename T&gt; bool LockerManager&lt;T&gt;:: AddData(const std::string&amp; id, T* pData) { boost::intrusive_ptr&lt;Locker&lt;T&gt; &gt; lPtr(Locker&lt;T&gt;(pData)); // Line 359 - compiles mMap.insert(make_pair(id, lPtr)); // Line 361 - gives error } </code></pre> <p>Locker is just a container class; its constructor looks like:</p> <pre><code>template &lt;typename T&gt; Locker&lt;T&gt;:: Locker(T* pData) : IntrusivePtrCountable(), mpData(pData), mThreadId(0), mDataRefCount(0) {} </code></pre> <p>In my test of this class, I am trying to do the following:</p> <pre><code>class Clayton { public: static int count; Clayton() { mNumber = count++;} void GetNumber() { cerr&lt;&lt;"My number is: "&lt;&lt;mNumber&lt;&lt;endl; } private: int mNumber; }; int Clayton::count = 0; class ClaytonManager { public: bool AddData(const std::string&amp; id, Clayton* pData) { return mManager.AddData(id, pData); } private: LockerManager&lt;Clayton&gt; mManager; }; </code></pre> <p>I get the following compile error:</p> <pre><code>Compiling LockerManagerTest.cpp : /usr/local/lib/gcc/i686-pc-linux-gnu/3.4.6/../../../../include/c++/3.4.6/bits/stl_pair.h: In constructor `std::pair&lt;_T1, _T2&gt;::pair(const std::pair&lt;_U1, _U2&gt;&amp;) [with _U1 = std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;, _U2 = boost::intrusive_ptr&lt;Locker&lt;Clayton&gt; &gt; (*)(Locker&lt;Clayton&gt;), _T1 = const std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;, _T2 = boost::intrusive_ptr&lt;Locker&lt;Clayton&gt; &gt;]': ../Utilities/include/LockerManager.h:361: instantiated from `bool LockerManager&lt;T&gt;::AddData(const std::string&amp;, T*) [with T = Clayton]' src/LockerManagerTest.cpp:35: instantiated from here /usr/local/lib/gcc/i686-pc-linux-gnu/3.4.6/../../../../include/c++/3.4.6/bits/stl_pair.h:90: error: no matching function for call to `boost::intrusive_ptr&lt;Locker&lt;Clayton&gt; &gt;::intrusive_ptr(boost::intrusive_ptr&lt;Locker&lt;Clayton&gt; &gt; (* const&amp;)(Locker&lt;Clayton&gt;))' /usr/local/boost-1.36.0/include/boost-1_36/boost/intrusive_ptr.hpp:94: note: candidates are: boost::intrusive_ptr&lt;T&gt;::intrusive_ptr(const boost::intrusive_ptr&lt;T&gt;&amp;) [with T = Locker&lt;Clayton&gt;] /usr/local/boost-1.36.0/include/boost-1_36/boost/intrusive_ptr.hpp:70: note: boost::intrusive_ptr&lt;T&gt;::intrusive_ptr(T*, bool) [with T = Locker&lt;Clayton&gt;] /usr/local/boost-1.36.0/include/boost-1_36/boost/intrusive_ptr.hpp:66: note: boost::intrusive_ptr&lt;T&gt;::intrusive_ptr() [with T = Locker&lt;Clayton&gt;] Command exited with non-zero status 1 0:05.40 </code></pre> <p>Please help</p>
<p>The compiler is doing its best to be helpful here. You need to define a method with the following signature:</p> <pre><code>boost::intrusive_ptr&lt;Locker&lt;Clayton&gt; &gt;::intrusive_ptr( boost::intrusive_ptr&lt;Locker&lt;Clayton&gt; &gt; (* const&amp;)(Locker&lt;Clayton&gt;) ): </code></pre> <p>You need to define a copy constructor for types that you store in a std::map, that's what this error message is trying to convey. You should also implement the &lt; operator so that the following is true:</p> <pre><code>- ( x &lt; x ) == false - if ( x &lt; y ), then !( y &lt; x ) - if ( x == y ), then ( x &lt; y ) == ( y &lt; x ) == false - if ( x &lt; y ) and ( y &lt; z ), then ( x &lt; z ) </code></pre> <p>For many of the built-in types C++ will provide these for you, which is why some people don't know what you have to do to store custom objects in std::map and other STL containers.</p>
Writing effective XSLT <p><strong>What are the principles and patterns that go into writing effective XSLT?</strong></p> <p>When I say "effective" I mean that it is</p> <ol> <li>Well-structured and readable</li> <li>Simple, concise</li> <li>Efficient (i.e. has good performance)</li> </ol> <p>In short, I'm looking for the best practices for XSLT.</p> <p>I've already seen <a href="http://stackoverflow.com/questions/434976/how-do-i-profile-and-optimize-an-xslt">the question regarding efficiency</a>, but efficient code loses its value if you can't understand what it's doing. </p>
<h1>I. Elegant XSLT code</h1> <p><br /> <strong>One can often find examples of beautiful XSLT code, especially when XSLT is used as a functional programming language</strong>. </p> <p>For examples see <a href="http://www.idealliance.org/papers/extreme/proceedings/xslfo-pdf/2006/Novatchev01/EML2006Novatchev01.pdf"><strong>this article</strong></a> on <a href="http://fxsl.sf.net"><strong>FXSL 2.0</strong></a> -- the Functional Programming library for XSLT 2.0.</p> <p>As an FP language XSLT is also a <em><a href="http://en.wikipedia.org/wiki/Declarative%5Fprogramming"><strong>declarative language</strong></a></em>. This, among other things means that one declares, specifies existing relationships. </p> <p>Such <strong>a definition often does not need any additional code to produce a result -- it itself is its own implementation, or an executable definition or executable specification</strong>.</p> <p><strong>Here is a small example</strong>.</p> <p><strong>This XPath 2.0 expression defines</strong> the "<em>Maximum <a href="http://en.wikipedia.org/wiki/Prime%5Ffactor">Prime Factor</a> of a natural number</em>":</p> <pre><code>if(f:isPrime($pNum)) then $pNum else for $vEnd in xs:integer(floor(f:sqrt($pNum, 0.1E0))), $vDiv1 in (2 to $vEnd)[$pNum mod . = 0][1], $vDiv2 in $pNum idiv $vDiv1 return max((f:maxPrimeFactor($vDiv1),f:maxPrimeFactor($vDiv2))) </code></pre> <p><strong>To pronounce it in English</strong>, the maximum prime factor of a number <strong><code>pNum</code></strong> is the number itself, if <strong><code>pNum</code></strong> is prime, otherwise if <strong><code>vDiv1</code></strong> and <strong><code>vDiv2</code></strong> are two factors of <strong><code>pNum</code></strong>, then the maximum prime factor of <strong><code>pNum</code></strong> is the bigger of the maximum prime factors of <strong><code>vDiv1</code></strong> and <strong><code>vDiv2</code></strong>.</p> <p><strong>How do we use this to actually calculate</strong> the Maximum Prime Factor in XSLT? <strong>We simply wrap up the definition above</strong> in an <code>&lt;xsl:function&gt;</code> and ... get the result!</p> <pre><code> &lt;xsl:function name="f:maxPrimeFactor" as="xs:integer"&gt; &lt;xsl:param name="pNum" as="xs:integer"/&gt; &lt;xsl:sequence select= "if(f:isPrime($pNum)) then $pNum else for $vEnd in xs:integer(floor(f:sqrt($pNum, 0.1E0))), $vDiv1 in (2 to $vEnd)[$pNum mod . = 0][1], $vDiv2 in $pNum idiv $vDiv1 return max((f:maxPrimeFactor($vDiv1),f:maxPrimeFactor($vDiv2))) "/&gt; &lt;/xsl:function&gt; </code></pre> <p><strong>We can, then, <a href="http://stackoverflow.com/questions/439814#445858">calculate the MPF for any natural number</a></strong>, for example:</p> <p><code>f:maxPrimeFactor(600851475143)</code> = 6857 </p> <p>As for efficiency, well, <strong>this transformation takes just 0.109 sec</strong>.</p> <p><strong>Other examples of both ellegant and efficient XSLT code</strong>:</p> <ul> <li><a href="http://www.tbray.org/ongoing/"><strong>Tim Bray</strong></a>'s <a href="http://www.tbray.org/ongoing/When/200x/2007/09/20/Wide-Finder"><strong>Wide Finder</strong></a>, as solved <a href="http://dnovatchev.spaces.live.com/Blog/cns!44B0A32C2CCF7488!385.entry"><strong>here</strong></a>.</li> <li><a href="http://dnovatchev.spaces.live.com/blog/cns!44B0A32C2CCF7488!341.entry"><strong>Cascade</strong></a> <a href="http://dnovatchev.spaces.live.com/blog/cns!44B0A32C2CCF7488!342.entry"><strong>deletions</strong></a></li> <li><a href="http://dnovatchev.spaces.live.com/blog/cns!44B0A32C2CCF7488!384.entry"><strong>Transitive closure</strong></a></li> <li><a href="http://dnovatchev.spaces.live.com/blog/cns!44B0A32C2CCF7488!357.entry"><s
Assigning random colors per session, for chat <p>I have an AJAX chat system that I'm working on and so far I have it working. One thing I want to do is have it so when the user name is displayed on screen, it is a unique color (like in an AIM window). How would I generate a random color to assign to the user's name for the particular session they are logged in for?</p> <p>The color would have to be something that is darker as it on white background and as they are generated, they can't be too similar to the colors that other current users have been assigned.</p> <p><strong>EDIT</strong> Thanks, I guess a predefined list would be the easiest way. If I have this list in a config file and I assign a color when the user logs in, how should I go about making sure that no two logged in users have the same color?</p>
<p>I think you're going to be better off randomly picking from a list of pregenerated colors that meet your requirements (dark enough, different enough from each other) than trying to generate colors on the fly.</p> <p><em>Edited to add:</em></p> <p>As far as keeping more than one user from having the same color, one thing I've seen systems do is to just assign colors locally on the users machine using Javascript. Usually it's not that important that different users see the same colors for other people. I don't care if the colors on my screen are the same as they are on some other user's screen, as long as all the colors on my screen are unique. In fact it may be desirable for each user's own text to be distinct (their's is black, everyone else's is colored, for instance).</p>
Multi-Dimensional Array ( C++ ) <p>I'm trying to store a pointer in an array.</p> <p>My pointer to a pointer is class object is:</p> <pre><code>classType **ClassObject; </code></pre> <p>So i know i can allocate it by using the new operator like this:</p> <pre><code>ClassObject = new *classType[ 100 ] = {}; </code></pre> <p>I'm reading a text file, with punctuation and here is what i have so far:</p> <pre><code>// included libraries // main function // defined varaibles classType **ClassObject; // global object const int NELEMENTS = 100; // global index wrdCount = 1; // start this at 1 for the 1st word while ( !inFile.eof() ) { getline( inFile, str, '\n' ); // read all data into a string varaible str = removePunct(str); // User Defined Function to remove all punctuation. for ( unsigned x = 0; x &lt; str.length(); x++ ) { if ( str[x] == ' ' ) { wrdCount++; // Incrementing at each space ClassObject[x] = new *classType[x]; // What i want to do here is allocate space for each word read from the file. } } } // this function just replaces all punctionation with a space string removePunct(string &amp;str) { for ( unsigned x = 0; x &lt; str.length(); x++ ) if ( ispunct( str[x] ) ) str[x] = ' '; return str; } // Thats about it. </code></pre> <p>I guess my questions are:</p> <ul> <li>Have I allocated space for each word in the file?</li> <li>How would i store a pointer in the ClassObject array within my while/for loop?</li> </ul>
<p>If you are using C++ use the <a href="http://www.boost.org/doc/libs/1%5F38%5F0/libs/multi%5Farray/doc/user.html" rel="nofollow">Boost Multidimensional Array Library</a></p>
NSApplicaton delegate - applicationDidFinishLaunching <p>I have declared a delegate for my cocoa application here :</p> <p>MyAppDelegate.h</p> <pre><code>@interface MyAppDelegate : NSApplication { } - (void) applicationDidFinishLaunching:(NSNotification*) notice ; @end </code></pre> <p>MyAppDelegate.m</p> <pre><code>@implementation MyAppDelegate - (void) applicationDidFinishLaunching:(NSNotification*) notice { NSLog(@"inside appdidfinishlaunching") ; } @end </code></pre> <p>I have linked the delegate outlet of File Owner to this object in IB.</p> <p>Yet, this method is not getting called. I don't see any log messages from it.</p> <p>Can you please suggest what is wrong ?</p>
<p>Your application delegate is not an application itself. It should inherit from NSObject, not NSApplication.</p> <h3>Why that matters</h3> <p>NSApplication is a singleton. Its <code>init</code> method always returns the first instance of NSApplication or any subclass, throwing away any subsequent objects you (or the nib loader) may be calling <code>init</code> on.</p> <p>So you ended up setting your application object as its own delegate. The object you intended to make the delegate died in the second call to <code>init</code>, and the application object took its place.</p> <p>Changing the application object to be an instance of your subclass would also have worked, but you'd still have the application as its own delegate, which is unclean and possibly dangerous (NSApplication may privately implement some of its delegate methods itself, as they're just notification handler methods). The only correct solution is to make your app delegate class not inherit from NSApplication.</p>
Django: Adding additional properties to Model Class Object <p>This is using Google App Engine. I am not sure if this is applicable to just normal Django development or if Google App Engine will play a part. If it does, would you let me know so I can update the description of this problem.</p> <pre><code>class MessageModel(db.Model): to_user_id = db.IntegerProperty() to_user = db.StringProperty(multiline=False) message = db.StringProperty(multiline=False) date_created = db.DateTimeProperty(auto_now_add=True) </code></pre> <p>Now when I do a query a get a list of "MessageModel" and send it to the template.html to bind against, I would like to include a few more properties such as the "since_date_created" to output how long ago since the last output, potentially play around with the message property and add other parameters that will help with the layout such as "highlight" , "background-color" etc...</p> <p>The only way I thought of is to loop through the initial Query Object and create a new list where I would add the property values and then append it back to a list.</p> <pre><code> for msg in messagesSQL: msg.lalaland = "test" msg.since_created_time = 321932 msglist.append(msg) </code></pre> <p>Then instead of passing the template.html messagesSQL, I will now pass it msglist.</p>
<p>You should still be able to send it messagesSQL to the template after you've added elements to it via the for loop. Python allows that sort of thing.</p> <p>Something else that might make sense in some cases would be to give your MessageModel methods. For instance, if you have a </p> <pre><code>def since_date_created(self): '''Compute the time since creation time based on self.date_created.''' </code></pre> <p>Then (assuming you have "messagesSQL" in the template), you can use the function as</p> <pre><code>{% for msg in messagesSQL %} {{ msg.since_date_created }} {% endfor %} </code></pre> <p>Basically, you can call any method in the model as long as you it needs no arguments passed to it.</p>
Unit testing Scala <p>I just recently started learning the Scala language and would like to do it in <a href="http://en.wikipedia.org/wiki/Test-driven%5Fdevelopment">TDD</a>-way. Could you share your experiences on the unit testing frameworks there are for Scala and the pros/cons of them.</p> <p>I'm using IntelliJ IDEA for Scala development, so it would be nice to be able to run the tests with IDE-support.</p>
<p>Have you looked at <a href="http://www.artima.com/scalatest/" rel="nofollow">ScalaTest</a> ?</p> <p>I've not used it, but it comes from Bill Venners and co at Artima, and consequently I suspect it'll do the job. It doesn't appear to have IDE integration, however.</p> <p><a href="http://www.theserverside.com/blogs/thread.tss?thread_id=48085" rel="nofollow">This blog entry</a> is a little old, but suggests that TestNG is the best option for testing Scala. TestNG will certainly have IDE integrations.</p> <p>EDIT: I've just realised that I wrote this answer in 2009, and the world has moved on (!). I am currently using ScalaTest, the IDE integration works fine, and I can strongly recommend it. In particular the <a href="http://www.scalatest.org/user_guide/using_matchers" rel="nofollow">matcher DSL</a> works very nicely</p>
How does splint know my function isn't used in another file? <p>Splint gives me the following warning:</p> <pre><code>encrypt.c:4:8: Function exported but not used outside encrypt: flip A declaration is exported, but not used outside this module. Declaration can use static qualifier. (Use -exportlocal to inhibit warning) encrypt.c:10:1: Definition of flip </code></pre> <p>Since I called splint only on this file how does it know that?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int flip( int a) { int b; b = a; b ^= 0x000C; return b; } int blah(int argc, char *argv[]) { FILE *fp = NULL, *fpOut=NULL; int ch; ch = 20; flip(20); return (ERROR_SUCCESS); } </code></pre> <p>I even got rid of main so that it could not figure out that the file is complete in any way. I am totally stumped!</p>
<p>You might find that if you included a header that declared <code>flip()</code> - as you should, of course - then <code>splint</code> would not complain. You should also declare <code>blah()</code> in the header as well.</p> <p>I'm not wholly convinced that this is the explanation because <code>blah()</code> is not used at all (though it uses <code>flip()</code>) and you don't mention <code>splint</code> complaining about that.</p> <p>However, it is a good practice to make every function (in C) <code>static</code> until you can demonstrate that it is needed outside its source file, and then you ensure that there is a header that declares the function, and that header is used in the file that defines the function and in every file that uses the function.</p> <p>In C++, the 'every function should be <code>static</code>' advice becomes 'every function should be defined in the anonymous namespace'.</p>
What is the difference between Microsoft AJAX and AJAX Pro? <p>What is the difference between Microsoft AJAx and AJAX Pro?</p> <p>Also, for what should I use AJAX Pro?</p>
<p>Microsoft AJAX is Microsoft's Ajax library that contains ready to use server controls. </p> <p>AJAX Pro is a free AJAX library, that enables you to implement your Ajax calls manually. It's a little bit difficult to use then Microsoft's controls. But you have more control on the data and html elements with this library. </p> <p>With AJAX Pro, you define AjaxMethods, and call them in client-side. with callback methods you get the return value and implement your logic. Whole serializable .NET objects converted successfully to javascript objects.</p> <p>In Ajax Pro when you make an ajax call, only the method you defined is called. In Microsoft Ajax, whole page life-cycle called instead. Because of this, you can not change properties of controls on page with Ajax Pro. You should do it manually by callback functions in javascript. But in Microsoft AJAX, you have ability to change control's properties in Ajax methods.</p> <p>My suggestion, if you have knowledge of Javascript and HTML, try Ajax Pro or JQuery for AJAX. But if you're a newbie, begin with Microsoft Ajax. </p>
Repository Pattern - POCOs or IQueryable? <p>I'm new to the Repository Pattern and after doing a lot of reading on the web I have a rough understanding of what is going on, but there seems to be a conflict of ideas.</p> <p>One is what the IRepository should return.</p> <p>I would like to deal in ONLY Pocos so I would have an IRepository implementation for every aggregate root, like so:</p> <pre><code>public class OrangeRepository: IOrangeRepository { public Orange GetOrange(IOrangeCriteria criteria); } </code></pre> <p>where IOrangeCriteria takes a number of arguments specific to finding an Orange.</p> <p>The other thing I have is a number of data back-ends - this is why I got into this pattern in the first place. I imagine I will have an implementation for each, e.g</p> <p>OrangeRepositoryOracle, OrangeRepositorySQL, OrangeRepositoryMock etc</p> <p>I would like to keep it open so that I could use EF or NHibernate - again if my IOrangeRepository deals in POCOs then I would encapsulate this within the Repository itself, by implementing a OrangeRepositoryNHibernate etc.</p> <p>Am I on the right lines? </p> <p>Thanks</p> <p>EDIT: Thanks for the feedback, I don't have anyone else to bounce these ideas off at the moment so it is appreciated!</p>
<p>Yes, your version is the safest / most compatible one. You can still use it with about any resources, not only data access ones, but with web services, files, whatever.</p> <p>Note that with the IQueryable version you still get to work based on your POCOs classes, but you are tied to the IQueryable. Also consider that you could be having code that uses the IQueryable and then turns out it you hit a case where one of the repository's ORM doesn't handle it well.</p>
How to interrupt server Connection in C# <p>one my application features is tod download files from our ftp server. And of course this feature reqiures to cancel this operation (Cancel Downloading).</p> <p>Now, my Download Function is as follows:</p> <pre><code>try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + uri + "/" + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.UsePassive = true; response = (FtpWebResponse)reqFTP.GetResponse(); ftpStream = response.GetResponseStream(); _isItOutputStream = true; string dataLengthString = response.Headers["Content-Length"]; int dataLength = 0; if (dataLengthString != null) { dataLength = Convert.ToInt32(dataLengthString); } long cl = response.ContentLength; int bufferSize = 4048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create); bool first = true; while (readCount &gt; 0) { outputStream.Write(buffer, 0, readCount); _actualDownloaded += readCount; if (this.InvokeRequired) { ProgressBarDel _progressDel = new ProgressBarDel(ProgressBar); this.Invoke(_progressDel, new object[] { _actualDownloaded, first }); } first = false; readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); _isItOutputStream = false; return true; } catch (Exception ee) { _downloadException = ee.Message; if (ftpStream != null &amp;&amp; outputStream!=null ) if (ftpStream.CanRead &amp;&amp; outputStream.CanWrite) { ftpStream.Close(); outputStream.Close(); } if (response != null) response.Close(); return false; } </code></pre> <p>Now as you can see in Catch Block you can see that i'm trying to interrupt this connection when the user clicks on Cancel button.</p> <ul> <li>Canceling Operation Scenario:</li> </ul> <p>1) Cancel button was clicked.</p> <p>2) Call Function "DoSomeWorx()"</p> <p>3) in "DoSomeWorx()" do:</p> <pre><code>if (_isItOutputStream)// where here i'm trying to check if it's downloading { ftpStream.Close(); outputStream.Close(); response.Close(); } if (_startCopy)// check if copying to phone { IsCancelled(); } _btnDownload2PhoneThread.Abort(); // actually this operation does what i did before but for some resoans it does this but it takes time... _btnDownload2PhoneThread.Join(); </code></pre> <p>The Problem is when I reach any of the following statments <code>(ftpStream.Close();outputStream.Close();response.Close();)</code></p> <p>it throws an exception "File unavailable(e.g file is busy)"</p> <p>and this exception affects on re-downloading operation where it sees the file busy.</p> <p>so how to avoid this exception?</p>
<p>I'm assuming that you have a form of some sort, so your performing the download on a thread.</p> <p>What your probably better off doing is checking a "cancel" flag inside your while loop.</p> <p>eg.</p> <pre><code>while(readcount &gt; 0 &amp;&amp; !cancel) { ... } </code></pre> <p>Then let your method gracefully cancel out. </p> <p>Secondly you should use a using statement on your streams. That means that if you throw an exception, the finally block will guarantee that your stream gets disposed (which incidentally is why you would be receiving file busy, as the stream hasn't yet had it's destructor run, even though your method has completed)</p>
Need help converting VB.NET 08 code to PHP - Getting direct link from MediaFire.com <p>I was looking for a way to get a direct link from mediafire's file hosting service. By default, when a user visits a download link, he will be presented with a download page where he has to wait for the download to be processed and then a link will appear. This link will appear in the div id 'download_link'.</p> <p>I googled and found a VB.NET 2008 solution to this, but I need the code in PHP Here is the VB.NET 2008 solution: <a href="http://www.vbforums.com/showthread.php?t=556681" rel="nofollow">http://www.vbforums.com/showthread.php?t=556681</a></p> <p>Any help is greatly appreciated.</p> <p>Cheers</p>
<p>This VB.NET code relies on access to the client DOM through the WebBrowser .NET control. You could port this to PHP by:</p> <ul> <li>Using the cURL functions to get the HTML</li> <li>Loading them into an HTML parser to find the correct link</li> <li>Redirecting the user with <code>Header('Location: '.download_link)</code></li> </ul> <p>I think it would be better to recommend to your users the <a href="http://skipscreen.com/" rel="nofollow">SkipScreen</a> Firefox extension, though. A client solution will always be easier.</p>
How to start creating a selection script , "inspect like what firebug do"? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/742210/does-anyone-know-a-dom-inspector-javascript-library-or-plugin">Does anyone know a DOM inspector javascript library or plugin?</a> </p> </blockquote> <p>I want to create a small tool on webproject which will let the user select tags on the page and i will save selections in an array for future use, so what i need is something near the functionality of firebug.<br/><br/> From where i can start? any good articles or tools can make things easier?</p>
<p>Could you do something like add a jquery function which does stuff on hovering and clicking on things you want to inspect?</p> <p>e.g</p> <pre><code>$('div, p, img').hover(function(){ // stuff to do on hover like highlight the object $(this).addClass('hover'); }, function(){ $(this).removeClass('hover'); }); $('div, p, img').click(function(){ yourSpecialClickFunction(); }); </code></pre> <p>Maybe you would have something somewhere which doesn't make the above do anything until an inspect button is clicked perhaps.</p>
Why am I getting "Undefined index" from my PHP? <p>When I run this code:</p> <pre><code>&lt;?php if (preg_match('/^[a-z0-9]+$/', $_GET['p'])) { $page = realpath("includes/$_GET[p].php"); if ($page) { include $page; } } ?&gt; </code></pre> <p>I get this error:</p> <blockquote> <p>Notice: Undefined index: p in index.php on line 3</p> </blockquote>
<p>The error message says that there is no array item with the key <code>p</code>. If you cannot guarantee that a variable (or array item) does exist, you should first check it with the <a href="http://docs.php.net/isset" rel="nofollow"><code>isset</code> function</a>:</p> <pre><code>if (isset($_GET['p']) &amp;&amp; preg_match('/^[a-z0-9]+$/', $_GET['p'])) { $page = realpath("includes/$_GET[p].php"); if ($page) { include $page; } } </code></pre>
Getting the time elapsed (Objective-c) <p>I need to get time that elapsed between two events: for example between appearance of UIView and between user's first reaction.</p>
<pre><code>NSDate *start = [NSDate date]; // do stuff... NSTimeInterval timeInterval = [start timeIntervalSinceNow]; </code></pre> <p><code>timeInterval</code> is the difference between start and now, in seconds, with sub-millisecond precision.</p>
How many ways there are to declare variables in facelets? <p>I noticed that c:set does not work well used inside "include of include of include", as important notice facelets documentation does't recommend it too.</p> <p>Now I am using ui:param inside ui:include, but it is a bit dispersive when no attached notes about params comes with the include, is there something other way to declare "global vars"?</p>
<p>This is really a matter of trying to fit old JSP programming into the JSF framework. You should be using backing beans to hold your data.</p> <p>If you try to hard-code data directly into your xhtml file, you are defeating the purpose of JSF's MVC framework. If you have a specific example of what you are trying to do, I could give you a specific recommendation.</p>
Binary Trees question. Checking for similar shape <p>Hi I'm stuck doing this, not sure how to go about it.</p> <p>If I have two binary trees, how would I check if the have the same shape? Data in the nodes doesn't matter, just if the tree structures are equal.</p> <p>Any ideas on how to solve this problem?</p>
<p>You can easily do that with recursion. This following code works because two non-empty trees have the same shape if and only if their respective subtrees have the same shape.</p> <pre><code>boolean equalTrees(Node lhs, Node rhs) { // Empty trees are equal if (lhs == null &amp;&amp; rhs == null) return true; // Empty tree is not equal to a non-empty one if ((lhs == null &amp;&amp; rhs != null) || (lhs != null &amp;&amp; rhs == null)) return false; // otherwise check recursively return equalTrees(lhs.left(), rhs.left()) &amp;&amp; equalTrees(lhs.right(), rhs.right()) } </code></pre> <p>To check two trees, pass their root nodes to the function above.</p> <pre><code>equalTrees(tree1.root(), tree2.root()) </code></pre>
How can I make my PHP-based cron job execute more often? <p>I have a file "<code>update.php</code>" which does some MySQL operations. A cron job executes this file every 5 minutes. Unfortunately, I cannot execute the cron job more often.</p> <p>So I had the idea that I could add ...</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="refresh" content="2; URL=&lt;?php echo $_SERVER['SCRIPT_NAME']; ?&gt;" /&gt; &lt;/head&gt; &lt;body&gt;&lt;/body&gt; &lt;/html&gt; </code></pre> <p>... to the page "<code>update.php</code>". Will cron execute the file in a way that the page will refresh automatically? Or will that not happen because there is no client with a browser?</p> <p>If it the meta refresh has no effect, is there any other possibility to achieve the refreshing of the page?</p> <p>Thanks in advance!</p>
<p>I'm afraid that won't work, because it's a browser feature to refresh the page.</p> <p>Question: Why can't you set the cron job to run more frequently that every 5 minutes?</p> <p>If there is no other option then you could create you're own daemon to do the job more frequently.</p> <p>e.g. Your php script could:</p> <ul> <li>Run</li> <li>Wait 60 seconds</li> <li>Run</li> <li>( Wait; Run; two more times)</li> <li>exit</li> </ul> <p>For example: (By variation of <a href="http://stackoverflow.com/questions/741910/how-can-i-make-my-php-based-cron-job-execute-more-often/753700#753700">sshow</a>'s code)</p> <pre><code>&lt;?php $secs = 60; ignore_user_abort(true); set_time_limit(0); dostuff(); sleep($secs); dostuff(); sleep($secs); dostuff(); sleep($secs); dostuff(); sleep($secs); dostuff(); ?&gt; </code></pre> <p>This version of the script will remain resident for four minutes, and execute the code 4 times which would be equivalent to running every minute, if this script is run by cron every 5 minutes.</p> <p>There seems some confusion about what a cronjob is, and how it is run. </p> <p><a href="http://en.wikipedia.org/wiki/Cron">cron</a> is a daemon, which sits in the background, and run tasks through the shell at a schedule specified in <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?crontab%2B5">crontab</a>s. </p> <p>Each user has a crontab, and there is a system crontab.</p> <p>Each user's crontab can specify jobs which are run as that user.</p> <p>For example:</p> <pre><code># run five minutes after midnight, every day 5 0 * * * $HOME/bin/daily.job &gt;&gt; $HOME/tmp/out 2&gt;&amp;1 # run at 2:15pm on the first of every month -- output mailed to paul 15 14 1 * * $HOME/bin/monthly # run at 10 pm on weekdays, annoy Joe 0 22 * * 1-5 mail -s "It's 10pm" joe%Joe,%%Where are your kids?% 23 0-23/2 * * * echo "run 23 minutes after midn, 2am, 4am ..., everyday" 5 4 * * sun echo "run at 5 after 4 every sunday" </code></pre> <p>So to run every five minutes:</p> <pre><code>*/5 * * * * echo "This will be run every five minutes" </code></pre> <p>Or to run every minute:</p> <pre><code>* * * * * echo "This will be run every minute" </code></pre> <p>The output from the commands are emailed to the owner of the crontab (or as specified by MAILTO). This means if you run something every minute it will email you every minute, unless you ensure all normal output is suppressed or redirected.</p> <p>The commands are run as the user who owns the crontab, which contrasts with the scripts run by the web-server, which are run as the 'nobody' user (or similar - whatever the web-server is configured to run as). This can make life more complicated if the cronjob is writing to files which are supposed to be accessed by the scripts run by the web-server. Basically you have to ensure that the permissions remain correct.</p> <p>Now, I'm not sure that this is the system you are refering to. If you mean something else by <code>cronjob</code> then the above might not apply.</p> <p>If you want to do something that your current host is not letting you do, then rather than hacking around the restriction, you might what to look at switching hosting provider?</p> <p><hr /></p> <p>An alternative is to put the script in you're normal scripts location, and have some external scheduler run wget against it at whatever frequency you like.</p> <p><hr /></p> <p>Another alternative is on-demand updating of the form of <a href="http://stackoverflow.com/questions/741910/how-can-i-make-my-php-based-cron-job-execute-more-often/755186#755186">vartec</a>'s suggestion. However that may not solve your problems.</p>
Programatically determining amount of parameters a function requires - Python <p>I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their apropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed the required amount inside the dictionary case statement in the form <code>{Keyword:(FunctionName, AmountofArguments)}</code>.</p> <p>This current setup works perfectly fine however I was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but I see how args and kwargs could screw such a command up because of the limitless amount of arguments they allow.</p> <p>Thanks for any help.</p>
<p><a href="http://docs.python.org/library/inspect.html#inspect.getargspec">inspect.getargspec()</a>:</p> <blockquote> <p>Get the names and default values of a function’s arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.</p> </blockquote>
TSQL make EXECUTE statement synchronous <p>I have two TSQL EXEC statements</p> <pre><code>EXECUTE (N'MyDynamicallyGeneratedStoredProcedure') -- return 0 on success SELECT @errCode = @@ERROR ; IF (@errCode = 0) BEGIN EXEC 'A Sql Statement using ##temptable created from first', @returnValue END </code></pre> <p>How do I make the two EXEC's synchronous? ; Right now the second EXEC does not wait for the first EXECUTE to complete. I tried issuing a WaitFor Delay, It waits but the second EXEC statement is never returing back. </p> <p>Thanks.</p> <p><strong>Update, Here is more info:</strong></p> <ol> <li>First execute creates a global temp table and populates it from a complex SELECT query. </li> <li>Second EXEC is a CLR Stored Procedure that generates a dynamic SP, based on the variables from recently created and populated Global Temp table. </li> </ol> <p>Now the second EXEC, complains that the Global Temp table is not found. </p> <p><strong>Update 2, Found the issue (And its me!!)</strong> </p> <p>GBN (and others) was point blank on the answer. EXEC IS synchronous. The problem? My understanding of the problem itself.. I had mentioned</p> <ol> <li>EXECUTE (N'MyDynamicallyGeneratedStoredProcedure') -- return 0 on success</li> </ol> <p>It should have been:</p> <p>1(a) EXECUTE (N'CreateMyDynamicStoredProcedure') -- return 0 on success</p> <p>1(b) <strong>EXECUTE (N'MyDynamicStoredProcedure') -- return 0 on success</strong></p> <p>I missed that 1(b) was actually executed somewhere else and after step (2) . </p> <p>(I should go get a life!!)</p>
<p>EXECUTE is sychronous. The 2nd one runs after the 1st one. Always.</p> <p>Do you have multiple connections running the same code? You are using a global temp table that will be visible to all connections so it may look like asyncc execution...</p>
How to draw opengl graphics from different threads? <p>I want to make an opengl application that shows some 3d graphics and a command-line. I would like to make them separate threads, because they both are heavy processes. I thought that I could approach this with 2 different viewports, but I would like to know how to handle the threads in opengl.</p> <p>According to what I've been reading, Opengl is asynchronous, and calling its functions from different threads can be very problematic. Is there a way that I could use to approach this problem? Ideally, I would like to draw the command line on top of the 3d graphics with some transparecy effect... (this is impossible with viewports I guess)</p> <p>Is important that the solution is portable.</p> <p>Thanks!</p>
<p>Its possible you can achieve what you want to do using Overlays.<br /> Overlays are a somewhat dated feature but it should still be supported in most setups. Basically an overlay is a separate GL Context which is rendered in the same window as another layer, drawing on top of whatever was drawn on the windows with its original context.<br /> You can read about it <a href="http://www.opengl.org/resources/faq/technical/contexts.htm" rel="nofollow">here</a>.</p>
TreeViolationException problem <p>Hi Im having some trouble when inserting to the right of a node in a binary tree... I just dont see why the exception is happening. This is the method to inset:</p> <pre><code>public void attachRight(BinaryTree&lt;T&gt; tree) { if (right != null) { throw new TreeViolationException(); } if (tree != null) { tree.parent = this; right = tree; } } </code></pre> <p>This is the code in my main class</p> <p>public class Testing {</p> <pre><code>public static void main(String[] args) { /* the tree to be built 30 * / \ * 12 16 * / \ / \ * null 1 2 5 */ //Create binary tree and set root to 30 BinaryTree&lt;Integer&gt; root = new BinaryTree&lt;Integer&gt;(); root.makeRoot(30); //System.out.println(root.getData()); //for verifying only //Insert 12 -&gt; left(30) root.attachLeft(new BinaryTree&lt;Integer&gt;()); root.left.setData(12); //Insert 16 -&gt; right(30) root.attachRight(new BinaryTree&lt;Integer&gt;()); root.right.setData(16); //insert 1 -&gt; right(12) root.right.attachRight(new BinaryTree&lt;Integer&gt;()); root.right.right.setData(1); //insert 2 -&gt; left(16) root.right.attachLeft(new BinaryTree&lt;Integer&gt;()); root.right.left.setData(2); //insert 5 -&gt; right(16) root.right.attachRight(new BinaryTree&lt;Integer&gt;()); root.right.right.setData(5); System.out.println(root.getData()); System.out.println(root.left.getData()); System.out.println(root.right.getData()); } </code></pre> <p>}</p> <p>I'm only able to insert, 30, 12, and 16. Not sure what's going on.... This is the error I get, it happens in the attachRight method</p> <p>Exception in thread "main" proj5.TreeViolationException at proj5.BinaryTree.attachRight(BinaryTree.java:98)</p> <p>TreeViolationException is just a class that I have that extends RuntimeException</p>
<p>From the information given, the exception should come from this line:</p> <pre><code>//insert 5 -&gt; right(16) root.right.attachRight(new BinaryTree&lt;Integer&gt;()); </code></pre> <p>because root.right.attachRight() has already been called on this line:</p> <pre><code>//insert 1 -&gt; right(12) root.right.attachRight(new BinaryTree&lt;Integer&gt;()); </code></pre> <p>and root.right already has right node. Why it comes earlier, is impossible to diagnose right now. You should provide more information (e.g. BinaryTree class full implementation).</p>
Postgres functions <p>I need to make a select query with joins. This should be written in a function. My approach didn't work:</p> <pre><code>CREATE OR REPLACE FUNCTION test2() RETURNS SETOF record AS' DECLARE r record; BEGIN for r in SELECT * FROM messages_wall INNER JOIN location ON messages_wall.id = location.id loop return next r; end loop; end; ' LANGUAGE 'plpgsql' </code></pre> <p>ERROR: a column definition list is required for functions returning "record"</p> <p>I should call this function from a .net application. How should I proceed?</p>
<p><code>SELECT * FROM test2() AS tabletest2 (id integer, name text);</code> if you really wanna use a function, but a view is better in this case</p>
How to detect the point of a stack overflow <p>I have the following problem with my C program: Somewhere is a stack overflow. Despite compiling without optimization and with debugger symbols, the program exits with this output (within or outside of gdb on Linux):</p> <p> Program terminated with signal SIGSEGV, Segmentation fault. The program no longer exists. <p>The only way I could detect that this actually is stack overflow was running the program through valgrind. Is there any way I can somehow force the operating system to dump a call stack trace which would help me locate the problem?</p> <p>Sadly, gdb does not allow me to easily tap into the program either.</p>
<p>If you allow the system to dump core files you can analyze them with gdb:</p> <pre><code>$ ulimit -c unlimited # bash sentence to allow for infinite sized cores $ ./stack_overflow Segmentation fault (core dumped) $ gdb -c core stack_overflow gdb&gt; bt #0 0x0000000000400570 in f () #1 0x0000000000400570 in f () #2 0x0000000000400570 in f () ... </code></pre> <p>Some times I have seen a badly generated core file that had an incorrect stack trace, but in most cases the bt will yield a bunch of recursive calls to the same method.</p> <p>The core file might have a different name that could include the process id, it depends on the default configuration of the kernel in your current system, but can be controlled with (run as root or with sudo):</p> <pre><code>$ sysctl kernel.core_uses_pid=1 </code></pre>
Does anyone know a DOM inspector javascript library or plugin? <p>Does anyone know of a DOM inspector javascript library or plugin?</p> <p>I want to use this code inside a website I am creating, I searched a lot but didn't find what I wanted except this one: <a href="http://slayeroffice.com/tools/modi/v2.0/modi_help.html">http://slayeroffice.com/tools/modi/v2.0/modi_help.html</a></p> <p><strong>UPDATE:</strong> Seems that no one understood my question :( I want to find an example or plug-in which let me implement DOM inspector. I don't want a tool to inspect DOMs with; I want to write my own.</p>
<p><a href="http://karmatics.com/aardvark/">Aardvark</a> is a firefox extension officially but you can use that as a javascript library, too. The inline demo in the said website is implemented using javascript. digg into the code &amp; you'll find <a href="http://karmatics.com/aardvark/loader.js">loader.js</a> which is bootstrapping the Aardvark modules.</p>
Silverlight installed in Firefox 3, but not detected/activated <p>As the title says really. We are working on a Silverlight banner on a redesign of our site and the Silverlight content works fine in all browsers except Firefox 3 (PC v3.0.7,8 or Mac v3.0.8). The Add-in is marked as having been installed, however.</p> <p>The problem page is at: <a href="http://clearvision.programx.co.uk/Schools/Students.aspx" rel="nofollow">http://clearvision.programx.co.uk/Schools/Students.aspx</a></p> <p>(Note: we know of the crap HTML mark-up, that is a bug in SiteFinity, the CMS we're having to use. We have tried with and without this erroneous content with no effect.)</p> <p>I've seen a number of reports (this one being particularly good: <a href="http://tempvariable.blogspot.com/2008/04/silverlight-and-firefox-3.html" rel="nofollow">http://tempvariable.blogspot.com/2008/04/silverlight-and-firefox-3.html</a>) about Firefox 3 having problems. </p> <p>The SL control is Silverlight 1.0.</p> <p>Any help much appreciated, I really do nto want to have to write alternative content for Firefox users!</p>
<p>I checked your Silverlight.js file and it was version 1.0 of the .js file. I think that upgrading to the <a href="http://code.msdn.microsoft.com/silverlightjs" rel="nofollow">2.0 version of Silverlight.js file</a> (which was updated for FF3) may solve your issue. </p>
Determine the name of the variable used as a parameter to a method <p>How would you, in C#, determine the name of the variable that was used in calling a method?</p> <p>Example:</p> <pre><code>public void MyTestMethod1() { string myVar = "Hello World"; MyTestMethod2(myVar); } public void MyMethod2(string parm) { // do some reflection magic here that detects that this method was called using a variable called 'myVar' } </code></pre> <p>I understand that the parameter might not always be a variable, but the place I am using it is in some validation code where I am hoping that the dev can either explicitly state the friendly name of the value they are validating, and if they don't then it just infers it from the name of the var that they called the method with...</p>
<p>There is a way, but it's pretty ugly.</p> <pre><code>public void MyTestMethod1() { string myVar = "Hello World"; MyTestMethod2(() =&gt; myVar); } public void MyMethod2(Expression&lt;Func&lt;string&gt;&gt; func) { var localVariable = (func.Body as MemberExpression).Member.Name; // localVariable == "myVar" } </code></pre> <p>As you can see, all your calls would have to be wrapped into lambdas and this method breaks down if you start to do anything else in the lambda besides return a single variable.</p>
Unable to move between Screens in Emacs <p>I have two screens, one is empty and the other is Emacs' manual. My cursor is at the empty screen. </p> <p>All my commands affect the empty screen.</p> <p>A similar command in Vim is C-w.</p> <p><strong>How can you switch to the Emacs' manual</strong> such that I can roll down the screen by C-v?</p>
<p><strong>Control-x + o</strong> (C-x + o), google emacs cheat sheet for help</p> <ol> <li>hold Control</li> <li>press X</li> <li>release Control and X</li> <li>press O</li> </ol>
Copy files with double credentials (windows) <p>Assume we have c:\DirA that can be read by User1 only, and c:\DirB that can be written by User2 only. Both credentials are know. </p> <p>How can I copy files from DirA to DirB directly?</p>
<p>Assuming the process is run in the context of the first user, run <a href="http://msdn.microsoft.com/en-us/library/aa378184%28VS.85%29.aspx" rel="nofollow"><code>LogonUser</code></a> to obtain a security token for the second user. Spawn a thread and call <a href="http://msdn.microsoft.com/en-us/library/aa378612%28VS.85%29.aspx" rel="nofollow"><code>ImpersonateLoggedOnUser</code></a>, passing the token as a parameter. The second thread will have access to <code>DirB</code>. Read data in the first thread, pass them to the second and write them from there.</p> <p>If the user you're running under has backup or restore privileges, the easier way would be to activate them with <a href="http://msdn.microsoft.com/en-us/library/aa379295%28VS.85%29.aspx" rel="nofollow"><code>OpenProcessToken</code></a> followed by <a href="http://msdn.microsoft.com/en-us/library/aa375202%28VS.85%29.aspx" rel="nofollow"><code>AdjustTokenPrivileges</code></a>.</p>
Tagging unit-tests <p>I'm working on a PHP project with solid unit-tests coverage.</p> <p>I've noticed, that last time, I'm making very tricky manipulations with unit-tests Command-Line Test Runner' <b>--filter</b> command.</p> <p>Here is this command's explanation from official documentation:</p> <blockquote> <blockquote> <p><b>--filter</b></p> <p>Only runs tests whose name matches the given pattern. The pattern can be either the name of a single test or a regular expression that matches multiple test names. </p> </blockquote> </blockquote> <p>I ofter use it because sometimes it becomes very useful to run just a single test suite or test case from the whole test base.</p> <p>I'm wondering if this is good practice or not?</p> <p>I have heard that sometimes it is good practice to to run the whole test suite on your Continuous Integration machine, if <b>you know for sure</b> that you have modified only one component and <b>100% percent confident</b>, that it won't fail other component's unit-tests. What do you think about it?</p> <p>Some time ago I thought that we shouldn't care so much about time require to run the whole suite of all unit-tests, but when you have very complicated business logic and unit-tests - this can take significant time.</p> <p>I understand, that "real" unit-tests shouldn't interact with DB, use mock/stubs objects, I agree with that. But sometimes, it is much easier(cheaper) to use DB fixtures for the tests.</p> <p>Please give me some advice, how this problem can be solved?</p>
<p>Good unit tests should: </p> <ul> <li>Have clear methods names and variable names to act as documentation</li> <li>Run fast. This will also be possible for test with complicated business logic. Test should run in an avarage time of something around 0.1 second.</li> <li>Test exactly one thing in one test method</li> <li>Not integrate with external resources like the filesystem, email, databases, webservices, and everything else. You can create seperate database integration tests to test your database ineraction. These test will slower then your unit test most of the time. I put my integration tests in a seperate project and I run them only when I am working on the integration code. I also run them on all builds on the CI server. </li> <li>Be completely isolated from each other. When you have tests depending on each other, you cannot see what your problem is from reading which tests are failed. You might have to debug to find the problem. Isolated tests will save you a lot of time.</li> </ul> <p>Personally, I don't use category names in my tests. I use 2 test projects per application. One for the unit test and one for the integration tests and slower tests. </p> <p>Reaction on: </p> <blockquote> <p>"But sometimes, it is much easier(cheaper) to use DB fixtures for the tests."</p> </blockquote> <p>When your code is written well, it will be easier to mock. I don't know about mocking frameworks in Php, but I use them in other languages to save me a lot of time. Writing test first and code later might help you to design your code to be testable easier.</p> <p>Personally I learned to test better by</p> <ul> <li>reading blogs about it</li> <li>reading books about it</li> <li>reading tested code written by others</li> <li>writing a lot of tests of course. It took me a few thousends of tests to become good at it.</li> </ul>
TSQL: UPDATE with INSERT INTO SELECT FROM <p>so I have an old database that I'm migrating to a new one. The new one has a slightly different but mostly-compatible schema. Additionally, I want to renumber all tables from zero. </p> <p>Currently I have been using a tool I wrote that manually retrieves the old record, inserts it into the new database, and updates a v2 ID field in the old database to show its corresponding ID location in the new database. </p> <p>for example, I'm selecting from MV5.Posts and inserting into MV6.Posts. Upon the insert, I retrieve the ID of the new row in MV6.Posts and update it in the old MV5.Posts.MV6ID field. </p> <p>Is there a way to do this UPDATE via INSERT INTO SELECT FROM so I don't have to process every record manually? I'm using SQL Server 2005, dev edition.</p>
<p>The key with migration is to do several things: First, do not do anything without a current backup. Second, if the keys will be changing, you need to store both the old and new in the new structure at least temporarily (Permanently if the key field is exposed to the users because they may be searching by it to get old records). </p> <p>Next you need to have a thorough understanding of the relationships to child tables. If you change the key field all related tables must change as well. This is where having both old and new key stored comes in handy. If you forget to change any of them, the data will no longer be correct and will be useless. So this is a critical step.</p> <p>Pick out some test cases of particularly complex data making sure to include one or more test cases for each related table. Store the existing values in work tables.</p> <p>To start the migration you insert into the new table using a select from the old table. Depending on the amount of records, you may want to loop through batches (not one record at a time) to improve performance. If the new key is an identity, you simply put the value of the old key in its field and let the database create the new keys.</p> <p>Then do the same with the related tables. Then use the old key value in the table to update the foreign key fields with something like:</p> <pre><code>Update t2 set fkfield = newkey from table2 t2 join table1 t1 on t1.oldkey = t2.fkfield </code></pre> <p>Test your migration by running the test cases and comparing the data with what you stored from before the migration. It is utterly critical to thoroughly test migration data or you can't be sure the data is consistent with the old structure. Migration is a very complex action; it pays to take your time and do it very methodically and thoroughly. </p>
How to access command line parameters outside of Main in C# <p>I am writing a .NET class that needs to parse the command line of the process. I don't want to have a dependency between the Main() method and that class. How can the class access the command line?</p>
<p>Call <code>Environment.GetCommandLineArgs()</code>.</p>
How do I parse text into lists in Java? <p>I have the following file saved as a <code>.txt</code>:</p> <pre><code>I Did It Your Way, 11.95 The History of Scotland, 14.50 Learn Calculus in One Day, 29.95 Feel the Stress, 18.50 Great Poems, 12.95 Europe on a Shoestring, 10.95 The Life of Mozart, 14.50 </code></pre> <p>I need to display the title of the books and the prices on different <code>JList</code>s in Java. How do I do that?</p> <p>Also if I have an array with two values (once I separate the title from the price) how do I copy the title and price into their respective arrays?</p>
<p>Seems simple enough that you don't need anything fancy.</p> <pre><code>BufferedReader r = new BufferedReader(new FileReader("file.txt")); List&lt;String&gt; titles = new ArrayList&lt;String&gt;(); List&lt;Double&gt; prices = new ArrayList&lt;Double&gt;(); while ((String line = r.readLine()) != null) { String[] tokens = line.split(","); titles.add(tokens[0].trim()); prices.add(Double.parseDouble(tokens[1].trim())); } r.close(); </code></pre>