instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm trying to build a Java regular expression to match "<code>.jar!</code>"</p> <p>The catch is that I don't want the matcher to consume the exclamation mark. I tried using <code>Pattern.compile("\\.jar(?=!)")</code> but that failed. As did escaping the exclamation mark.</p> <p>Can anyone get this to work or is this a JDK bug?</p> <p><strong>UPDATE</strong>: I feel like an idiot, <code>Pattern.compile("\\.jar(?=!)")</code> does work. I was using Matcher.matches() instead of Matcher.find().</p>
<p>Using your regex works for me (using Sun JDK 1.6.0_02 for Linux):</p> <pre><code>import java.util.regex.*; public class Regex { private static final String text = ".jar!"; private static final String regex = "\\.jar(?=!)"; public static void main(String[] args) { Pattern pat = Pattern.compile(regex, Pattern.DOTALL); Matcher matcher = pat.matcher(text); if (matcher.find()) { System.out.println("Match: " + matcher.group()); } else { System.out.println("No match."); } } } </code></pre> <p>prints:</p> <pre><code>Match: .jar </code></pre> <p>(without the !)</p>
<p>Additionally, you could try boxing it </p> <pre><code>Pattern.compile("\\.jar(?=[!])") </code></pre> <p><sub>Java must be broken: Perl</p> <pre><code>use strict; use warnings; my @data = qw( .jar .jar! .jarx .jarx! ); my @patterns = ( "\\.jar(?=!)", "\\.jar(?=\\!)", "\\.jar(?=[!])", ); for my $pat ( @patterns ){ for my $inp ( @data ) { if ( $inp =~ /$pat/ ) { print "$inp =~ $pat \n"; } } } </code></pre> <p>-></p> <pre><code>.jar! =~ \.jar(?=!) .jar! =~ \.jar(?=\!) .jar! =~ \.jar(?=[!]) </code></pre> <p></sub></p>
37,401
<p>Is there a way to unlock Windows files without downloading a utility?</p> <p>I have a few files on my Windows XP C: drive that are very old and very useless. When I try to delete these files I get the following message:</p> <pre> Cannot delete FILENAME.zip: It is being used by another person or program Close any programs that might be using the file and try again. </pre> <p>No one is accessing this file. No program is using it currently. Windows has screwed up the file locking mechanism. </p> <p>Is there a way to delete this file without downloading someone's unlocking utility? I find the sites offering these programs to be a tad sketchy.</p> <p>How could you force the file to unlock from within a program? I'm competent in Java, Perl, and Ruby, but I haven't seen anything among their libraries that would aid me here.</p>
<p>I've successfully used Process Explorer to find out which process has the file open. It saves a reboot that may not fix the problem anyway.</p> <p>In process explorer: Find &gt; Handle or DLL... then search for the name of the folder/file, then double click one of the search results. It'll select a handle in the main window, which you can right click and close.</p>
<p>You don't need any utility. Just use Win32 api to unlock them (simply close the handle)</p>
28,451
<p>Unfortunately, I need to do this. I'm using ELMAH for my error log. Before I route to my error.aspx view, I have to grab the default ELMAH error log so I can log the exception. You used to be able to use </p> <pre><code>Elmah.ErrorLog.Default </code></pre> <p>However, this is now marked as obsolete. The compiler directs me to use the method</p> <pre><code>Elmah.ErrorLog.GetDefault(HttpContext context) </code></pre> <p>MVC's context is of type HttpContextBase, which enables us to mock it (YAY!). How can we deal with MVC-unaware libraries that require the old style HttpContext?</p>
<p>Try <code>System.Web.HttpContext.Current</code>. It should do the trick.</p> <p>Gets HTTP-specific information about an individual HTTP request.</p> <p><a href="https://msdn.microsoft.com/en-us/library/system.web.httpcontext.current%28v=vs.110%29.aspx" rel="noreferrer">MSDN</a></p>
<pre><code>this.HttpContext.ApplicationInstance.Context </code></pre>
18,550
<p>I have this table in an Oracle DB which has a primary key defined on 3 of the data columns. I want to drop the primary key constraint to allow rows with duplicate data for those columns, and create a new column, 'id', to contain an auto-incrementing integer ID for these rows. I know how to create a sequence and trigger to add an auto-incrementing ID for new rows added to the table, but is it possible to write a PL/SQL statement to add unique IDs to all the rows that are already in the table?</p>
<p>Once you have created the sequence:</p> <pre><code>update mytable set id = mysequence.nextval; </code></pre>
<p>First you should check your PCTFREE... is there enough room for every row to get longer?</p> <p>If you chose a very small PCTFREE or your data has lots of lenght-increasing updates, you might begin chaining every row to do this as an update.</p> <p>You almost certainly better to do this as a CTAS.</p> <p>Create table t2 as select seq.nextval, t1.* from t1.</p> <p>drop t1</p> <p>rename t2 to t1.</p>
30,204
<p>Which built in (if any) tool can I use to determine the allocation unit size of a certain NTFS partition ?</p>
<p>Open an administrator command prompt, and do this command:</p> <pre><code>fsutil fsinfo ntfsinfo [your drive] </code></pre> <p>The Bytes Per Cluster is the equivalent of the allocation unit. </p>
<p>start > run > MSINFO32 </p> <p>goto components </p> <p>goto storage</p> <p>goto disk</p> <p>on the right look for Bytes/Sector</p>
10,681
<p>I'm looking for a <code>PHP</code> library that will allow me to create a print-ready <code>PDF</code>. The imposition should include 1-up, 4-up, 24-up, etc. layouts, and crop marks.</p> <p><code>FPDF</code>, <code>TCPDF</code> and <code>PHP's</code> included <code>PDF</code> libraries allow me to create an image and plop it on a PDF, but the more advanced layouts and crop marks are a bit beyond me.</p> <p>Thanks in advance!</p>
<p>We used DOMPDF <a href="http://www.digitaljunkies.ca/dompdf/" rel="nofollow noreferrer">http://www.digitaljunkies.ca/dompdf/</a> successfully - just define what you want printed in regular HTML format, then pass the doc to DOMPDF, and it'll create a PDF from it. </p> <p>Much more convenient than working with vector-based solutions that require you to essentially lay things out yourself on the page (like FPDF). Use HTML for layout! It's much easier. </p>
<p>I've had a lot of success with <a href="http://www.pdflib.com/" rel="nofollow noreferrer">PDFLib</a> it's a very powerful library with PHP (and C, C#, Perl etc) bindings.</p>
11,450
<p>Image i have a view that is cached with the OutputCache attribute but i still need to increment a counter that records that the page has been viewed, how could i do it?</p> <p>I thought about creating my own Custom ActionFilterAttribute, and using Action Filter Order of Execution to record this .. but i'm not sure it will work.</p> <p>eg.</p> <pre><code>[IncrementViewCountFilter(Order=1)] [OutputCache(Duration=60,Order=2)] public ActionResult Index(int questionId) { ... } </code></pre> <p>Firstly, my assumption here is that if the OutputCache is called, and the page is cached, then the controller code will not be ran.</p> <p>Next problem i'm guessing is that the IncrementViewCountFilter wouldn't know about the questionId, so how would it know what to increment (because it is executed before the main Index code is executed).</p> <p>Secondly, if the IncrementViewCountFilter did know the questionId .. and it's getting lots of hits, you wouldn't want it to write all the time to the DB.. but only when it gets to a certain number .. and then u 'flush' the output.</p> <p>Anyone have any thoughts?</p>
<p>Well, you have a few options. </p> <h2>Donut caching</h2> <p>One server-side option is 'Donut caching'. <strong>Donut caching</strong> allows most of the page to be cached, and portions of the page to be not cached (the hole in the middle of the donut). Donut caching <a href="http://haacked.com/archive/2008/11/05/donut-caching-in-asp.net-mvc.aspx" rel="noreferrer">is described here</a>, and I have used it with great success.</p> <h2>Image-based tracker</h2> <p>Another option is having <strong>an image</strong> on the page actually load a server-side action that records the hit. This would look like </p> <pre><code>&lt;img src="/controller/action"&gt; </code></pre> <p>on the page, where the action <a href="http://blog.rodj.org/archive/2008/09/24/asp.net-mvc-image-handler.aspx" rel="noreferrer">serves up an empty image</a> at the end.</p> <h2>Client-side tracking</h2> <p>The last option is <strong>client-side tracking</strong> -- where some script runs on the client side and uses AJAX to call something on the server to record the hit. Google uses something like this for their Analytics package. If you're on the same domain as your tracking mechanism ... like if your main page is:</p> <pre><code>http://www.domain.com/home/action </code></pre> <p>and the tracker is on</p> <pre><code>http://www.domain.com/tracking/action </code></pre> <p>then you should be fine.</p> <p>This gets tricky when your tracker is on a different domain (you need to handle this using <a href="http://remysharp.com/2007/10/08/what-is-jsonp/" rel="noreferrer">JSONP</a> or some other mechanism that allows for relatively safe cross-site scripting).</p>
<p>I don't know about the MVC side but if I was doing this in WebForms this sounds like it would be a candidate for <a href="http://tinyurl.com/donutcaching" rel="nofollow noreferrer">output cache substitution</a> aka donut caching. </p>
46,437
<p>Take the following html</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Basic Layout&lt;/title&gt; &lt;style type="text/css"&gt; html,body,div{font-family:Verdana} #Head{border-bottom:solid 10px #369} #Body{margin-left:200px;background-color:#def} #Body h2{float:left;margin-left:-200px;padding:10px;font-size:1em;} #Foot{border-top:dashed 1px #369} p{page-break-inside:avoid} &lt;/style&gt; &lt;script&gt; document.onclick = function() { alert(document.getElementById("Body").getBoundingClientRect().left); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="Head"&gt; &lt;h1&gt;Basic Layout Header&lt;/h1&gt; &lt;/div&gt; &lt;div id="Body"&gt; &lt;h2&gt;Body Header&lt;/h2&gt; &lt;p&gt; Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Mauris pretium. Morbi nisi velit, lacinia vitae, porttitor nec, laoreet nec, neque. Fusce id dolor. Vivamus scelerisque libero. Fusce aliquet gravida dui. Integer vulputate bibendum pede. Donec fringilla porta sem. Donec justo pede, fermentum eu, mattis a, malesuada id, erat. Maecenas hendrerit justo vitae felis. Praesent ut purus. Pellentesque turpis tortor, lobortis sed, fringilla venenatis, mattis nec, ipsum. Nunc non diam. Maecenas gravida mollis quam. Aenean nec urna. Quisque gravida, nulla a vulputate mattis, mauris justo mollis leo, et pellentesque eros augue sit amet urna. Aliquam rhoncus erat in mauris. Nullam ut urna. Nam pharetra, purus ac ultricies consectetuer, est leo aliquam augue, vitae pulvinar dui mi scelerisque mi. Integer urna. Praesent risus libero, porttitor vel, auctor gravida, posuere vel, felis. &lt;/p&gt; &lt;/div&gt; &lt;div id="Foot"&gt; &lt;p&gt;Footer&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Load it into your browser and click anywhere - you get 210 this is the left value for the #Body div</p> <p>However on a win form with a webbrowser control on it, navigate to the same html</p> <pre><code> webBrowser1.Navigate(_Url); </code></pre> <p>Click again, and you get 10.</p> <p>Why... why... why?</p>
<p>It is unlikely that you will find a library to read that file for C# - there aren't that many Unix users who also use C#.</p> <p>What I would do would be either to:</p> <ol> <li>Read the Python code, and then port it to C#</li> <li>Find the description of the mbox format online. As it is a Unix system, chances are that the format is just a plain text file, which should be easy enough to parse.</li> </ol>
<p>Most standard Unix mail files delimit entries with a line starting "From "</p> <p>So if you read in the mail file as a text file and switch to a new mail entry every time you see the string "From " at the start of a line it should work - Any strings elsewhere should already have been delimited by the email program</p>
41,600
<p>What is, or should I ask, is there, an equivalent to DllMain when creating a DLL using C++/CLI?</p> <p>Are there any restrictions on what cannot be called from this initialization code?</p>
<p>Dan: With respect to the loader lock, C++/CLI's delay load of the CLR and proper initialization for a mixed mode binary, I just posted yesterday on <a href="https://stackoverflow.com/questions/647310/c-to-c-cli-to-c-dll-system-io-filenotfoundexception/881110#881110">the subject here</a>.</p> <p>More or less, if you have a mixed mode binary, you must not cause any managed code to run while you are in <code>DllMain()</code>.</p>
<p>One giant advantage of .Net dlls is that they avoid the loader lock. One side effect is that there's no DllMain.</p>
43,476
<p>I read an interesting DailyWTF post today, <a href="http://thedailywtf.com/Articles/Out-of-All-the-Possible-Answers.aspx" rel="noreferrer">"Out of All The Possible Answers..."</a> and it interested me enough to dig up the original <a href="http://forums.thedailywtf.com/forums/t/10030.aspx" rel="noreferrer">forum post</a> where it was submitted. This got me thinking how I would solve this interesting problem - the original question is posed on <a href="http://projecteuler.net/index.php?section=problems&amp;id=5" rel="noreferrer">Project Euler</a> as: </p> <blockquote> <p>2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.</p> <p>What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?</p> </blockquote> <p>To reform this as a programming question, <strong>how would you create a function that can find the Least Common Multiple for an arbitrary list of numbers?</strong></p> <p>I'm incredibly bad with pure math, despite my interest in programming, but I was able to solve this after a little Googling and some experimenting. I'm curious what other approaches SO users might take. If you're so inclined, post some code below, hopefully along with an explanation. Note that while I'm sure libraries exist to compute the GCD and LCM in various languages, I'm more interested in something that displays the logic more directly than calling a library function :-) </p> <p>I'm most familiar with Python, C, C++, and Perl, but any language you prefer is welcome. Bonus points for explaining the logic for other mathematically-challenged folks out there like myself.</p> <p><strong>EDIT</strong>: After submitting I did find this similar question <a href="https://stackoverflow.com/questions/147515">Least common multiple for 3 or more numbers</a> but it was answered with the same basic code I already figured out and there's no real explanation, so I felt this was different enough to leave open.</p>
<p>This problem is interesting because it doesn't require you to find the LCM of an arbitrary set of numbers, you're given a consecutive range. You can use a variation of the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow noreferrer">Sieve of Eratosthenes</a> to find the answer.</p> <pre><code>def RangeLCM(first, last): factors = range(first, last+1) for i in range(0, len(factors)): if factors[i] != 1: n = first + i for j in range(2*n, last+1, n): factors[j-first] = factors[j-first] / factors[i] return reduce(lambda a,b: a*b, factors, 1) </code></pre> <p><hr> Edit: A recent upvote made me re-examine this answer which is over 3 years old. My first observation is that I would have written it a little differently today, using <code>enumerate</code> for example. A couple of small changes were necessary to make it compatible with Python 3.</p> <p>The second observation is that this algorithm only works if the start of the range is 2 or less, because it doesn't try to sieve out the common factors below the start of the range. For example, RangeLCM(10, 12) returns 1320 instead of the correct 660.</p> <p>The third observation is that nobody attempted to time this answer against any other answers. My gut said that this would improve over a brute force LCM solution as the range got larger. Testing proved my gut correct, at least this once.</p> <p>Since the algorithm doesn't work for arbitrary ranges, I rewrote it to assume that the range starts at 1. I removed the call to <code>reduce</code> at the end, as it was easier to compute the result as the factors were generated. I believe the new version of the function is both more correct and easier to understand.</p> <pre><code>def RangeLCM2(last): factors = list(range(last+1)) result = 1 for n in range(last+1): if factors[n] &gt; 1: result *= factors[n] for j in range(2*n, last+1, n): factors[j] //= factors[n] return result </code></pre> <p>Here are some timing comparisons against the original and the solution proposed by <a href="https://stackoverflow.com/a/196472/5987">Joe Bebel</a> which is called <code>RangeEuclid</code> in my tests.</p> <pre><code>&gt;&gt;&gt; t=timeit.timeit &gt;&gt;&gt; t('RangeLCM.RangeLCM(1, 20)', 'import RangeLCM') 17.999292996735676 &gt;&gt;&gt; t('RangeLCM.RangeEuclid(1, 20)', 'import RangeLCM') 11.199833288867922 &gt;&gt;&gt; t('RangeLCM.RangeLCM2(20)', 'import RangeLCM') 14.256165588084514 &gt;&gt;&gt; t('RangeLCM.RangeLCM(1, 100)', 'import RangeLCM') 93.34979585394194 &gt;&gt;&gt; t('RangeLCM.RangeEuclid(1, 100)', 'import RangeLCM') 109.25695507389901 &gt;&gt;&gt; t('RangeLCM.RangeLCM2(100)', 'import RangeLCM') 66.09684505991709 </code></pre> <p>For the range of 1 to 20 given in the question, Euclid's algorithm beats out both my old and new answers. For the range of 1 to 100 you can see the sieve-based algorithm pull ahead, especially the optimized version.</p>
<p>In expanding on @Alexander's comment, I'd point out that if you can factor the numbers to their primes, remove duplicates, then multiply-out, you'll have your answer.</p> <p>For example, 1-5 have the prime factors of 2,3,2,2,5. Remove the duplicated '2' from the factor list of the '4', and you have 2,2,3,5. Multiplying those together yields 60, which is your answer.</p> <p>The Wolfram link provided in the previous comment, <a href="http://mathworld.wolfram.com/LeastCommonMultiple.html" rel="nofollow noreferrer">http://mathworld.wolfram.com/LeastCommonMultiple.html</a> goes into a much more formal approach, but the short version is above.</p> <p>Cheers.</p>
22,475
<p>Maybe my understanding of agile development isn't as good as it should be, but I'm curious how an agile developer would potentially use off-the-shelf (OTS) software when the requirements and knowledge of what the final system should be are changing as rapidly as I understand them to (often after each iteration of development).</p> <hr> <p>I see two situations that are of particular interest to me:</p> <p>(1) An OTS system meets the initial set of requirements with little to no modification, other than potential integration into an existing system. However, within a few iterations of development, this system no longer meets the needs without rewriting the core code. The developers must choose to either spend additional time learning the core code behind this OTS software or throw it away and build from scratch. Either would have a drastic impact on development time and project cost.</p> <p>(2) The initial needs are not like any existing OTS system available, however, in the end when the customer accepts the product, it ends up being much like existing solutions due to requirement additions and subtractions. If the developers had more requirements and spent more time working on them up front, this solution could have been used instead of building again. The project was delivered, but later and at a higher cost than necessary.</p> <hr> <p>As a software engineer, part of my responsibilities (as I have been taught), are to deliver high-quality software to the customer on time at the lowest possible cost (among other things). Agile development allows for high-quality software, but in some cases, it might not be apparent that there are better alternatives until it is too late and too much money has been spent.</p> <p>My questions are:</p> <ol> <li>How does off-the-shelf software fit in with agile development?</li> <li>How do the agile manager and agile developer deal with these cases?</li> <li>What do the agile paradigms say about these cases?</li> </ol>
<h2>Scenario1:</h2> <p>This can occur regardless off the OTS nature of the component. Agile does not mean near-sighted.. you'd need to know the big chunks.. the framework bits and spend thinking time on it beforehand. That said, you can only build to what you know .. Delay only till the last responsible moment.Then you need to pick one of the alternatives and start on it. (I'd Avoid third party application unless the cost of developing it in-house is infeasible.. but that's just me). Prototype multiple solutions to check feasibility with list of known requirements. Keep things loosely coupled (replacable), easy to change and full tested. If you reach the fork of keep hacking or rewrite, you'd need to think of which has better value for the business and pick that option. It's comes down 'Now that we're here, what's the best we can do now?' </p> <h2>Scenario2:</h2> <p>This can happen although the chances are slim compared to the team spending 2-3 months trying to get the requirements 'finalized' only to find that the market needs or customer minds have changed and 'Now we want it this way'. Once again, its a question of what is the point of time till which you are prepared to investigate and explore before committing on a path of action. Decide wisely with whatever information you have upto that point.. Hindsight is always 20-20 but the customers wont wait forever. You can't wait till the point of time where the requirements coalesce to fit a known OTS component :)</p> <p><strong>Agile says Do whatever makes sense and strip out the non-value-adding activities :) Agile is no magic bullet.</strong> just my 2 agile cents :)</p>
<p>I think I read somewhere that if during an iteration you discover that you have more than 20% more work that you initially thought then you should abandon the sprint and start planning a new one taking into account the additional work.</p> <p>So this would mean replanning with the business to see if they still want to go ahead with the original requirements now that you know more.</p> <p>At our company we also make use of prototyping before the sprint to try and identify these kind of situations before they arise on a sprint. Although of course that still may not identify the kind of situation that you describe.</p>
7,481
<p>I'm new to both Web Services and RMI and I wonder which is the better way to do remoting between different web applications, when these applications are all written in Java, that is when different programming languages don't matter (which would be the advantage of WS).</p> <p>While on the one hand I would guess that there's a performance overhead when using web services (does anyone have some numbers to prove that?), on the other hand it seems to me that web services are much more loosely coupled and can be used to implement a more service-oriented architecture (SOA) (which isn't possible with RMI, right?).</p> <p>Although this is quite a general question, what's your opinion?</p> <p>Thanks</p>
<p>The web services do allow a loosely coupled architecture. With RMI, you have to make sure that the class definitions stay in sync in all application instances, which means that you always have to deploy all of them at the same time even if only one of them is changed (not necessarily, but it is required quite often because of serial UUIDs and whatnot)</p> <p>Also it is not very scalable, which might be an issue if you want to have load balancers.</p> <p>In my mind RMI works best for smaller, local applications, that are not internet-related but still need to be decoupled. I've used it to have a java application that handles electronic communications and I was quite satisfied with the results. For other applications that require more complex deployment and work across the internet, I rather use web services.</p>
<p>For Spring Remoting (I guessed you mean HTTP Invoker), both side should use Spring, if it is the case it can be discussed.</p> <p>For a Java to Java application RMI is a good solutionö, JAX-RPC or JAX-WS for Java-to-Java communication should be avoided if the clients are not under your control or might move to another platform.</p>
12,630
<p>I'd like to use the ADO.NET Entity Framework for data access, extend its objects for my business logic, and bind those objects to controls in my UI.</p> <p>As explained in <a href="https://stackoverflow.com/questions/260233/how-do-i-extend-adonet-entity-framework-objects-with-partial-classes">the answers to another question</a>, I cannot extend ADO.NET Entity Framework objects with partial classes and use my custom methods in LINQ queries.</p> <p><a href="http://img221.imageshack.us/img221/7329/clientsq0.gif" rel="nofollow noreferrer">ADO.NET Entity Framework partial class http://img221.imageshack.us/img221/7329/clientsq0.gif</a></p> <p>I don't want methods showing up in the Intellisense that are going to create run-time errors! How should I architect my application to avoid this problem?</p> <p><a href="http://img83.imageshack.us/img83/1580/iswashingtongn0.gif" rel="nofollow noreferrer">VB.NET LINQ with custom method http://img83.imageshack.us/img83/1580/iswashingtongn0.gif</a></p> <p>Do I need a data access Client class and also a business logic Client class? It seems like that will get confusing.</p>
<p>You can architect your solution using (Plain Old C# Objects) POCO's and Managers.</p> <p>That way you separate the business logic from the value objects.</p> <p>To make it "look pretty", you can mark your methods with the (this) modifier on the parameters so you can then use those methods as extension methods.</p> <p>An example could make this pretty clear:</p> <h2>Location Value Object:</h2> <pre><code>public class Location { public string City { get; set; } public string State { get; set; } } </code></pre> <h2>Location Manager:</h2> <pre><code>public static class LocationManager { public static bool IsWashington(this Location location) { return location.State == "WA"; } } </code></pre> <p>Now, the extension methods will show up differently than the standard properties/methods on the object.</p> <p>The "IsWashington" method can be called 2 ways</p> <pre><code>Location location = new Location { State = "WA" }; LocationManager.IsWashington(location); </code></pre> <h2>OR</h2> <pre><code>Location location = new Location { State = "WA" }; location.IsWashington(); </code></pre> <p>Now you have separation of your business logic and value objects, yet you still can have "pretty" method calls.</p> <p>If you feel your fellow devs (or you :) ) will abuse the extension method part, then just don't use it.</p>
<p>I also use entity framework and tried first to extend the classed but I soon found that was not a good solution so I ended up making new classes (in a new class library) which I prefixed with a B. I did not extend the entity classes. </p> <p>If I have a class named NewsPost the business class is named BNewsPost and all business logic connected to that class is collected here. For join the returning elements of used to place the logic.</p> <p>Not a very exiting solution but it did the trick.</p> <p>regards</p>
32,827
<p>If I'm adding a column to a table in Microsoft SQL Server, can I control where the column is displayed logically in queries?</p> <p>I don't want to mess with the physical layout of columns on disk, but I would like to logically group columns together when possible so that tools like SQL Server Management Studio list the contents of the table in a convenient way.</p> <p>I know that I can do this through SQL Management Studio by going into their "design" mode for tables and dragging the order of columns around, but I'd like to be able to do it in raw SQL so that I can perform the ordering scripted from the command line.</p>
<p>You can not do this programatically (in a safe way that is) without creating a new table. </p> <p>What Enterprise Manager does when you commit a reordering is to create a new table, move the data and then delete the old table and rename the new table to the existing name. </p> <p>If you want your columns in a particular order/grouping without altering their physical order, you can create a view which can be whatever you desire.</p>
<p>It can be done using SQL, by modifying the system tables directly. For example, look here:</p> <p><a href="http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=58912" rel="nofollow noreferrer">Alter table - Add new column in between</a></p> <p>However, I would not recommend playing with system tables, unless it's absolutely necessary.</p>
2,394
<p>How to add a click event listener to my custom control made with wxWidgets? The custom control uses wxWindow as the base. On the event list I see </p> <pre><code>wxEVT_LEFT_DOWN wxEVT_LEFT_UP wxEVT_LEFT_DCLICK wxEVT_MIDDLE_DOWN wxEVT_MIDDLE_UP wxEVT_MIDDLE_DCLICK wxEVT_RIGHT_DOWN wxEVT_RIGHT_UP wxEVT_RIGHT_DCLICK wxEVT_MOTION wxEVT_ENTER_WINDOW wxEVT_LEAVE_WINDOW wxEVT_MOUSEWHEEL </code></pre> <p>But there is no <code>wxEVT_LEFT_CLICK</code> or similar. </p>
<p>Typically, there is no "click" event (and in the case of <a href="http://www.wxwidgets.org/" rel="nofollow noreferrer">wxWidgets</a> - <a href="http://docs.wxwidgets.org/stable/wx_wxmouseevent.html#wxmouseevent" rel="nofollow noreferrer">there isn't</a> ). The action of clicking is broken into its two parts: Mouse Down and Mouse Up. Typically what you think of as a "left click" event is actually handled in a "left up" event.</p> <p>Try it out: </p> <ul> <li>Hover over a button (such as the "Add Comment" button this page) </li> <li>Click the left-mouse button down and hold</li> <li>Move the mouse off of the button while holding down</li> <li>Release the left-mouse button</li> <li>Nothing happens!</li> </ul> <p>This time:</p> <ul> <li>Hover over the same button </li> <li>Click the left-mouse button down and hold</li> <li>Release the left-mouse button</li> <li>The "click" action you expect is triggered by the up event!</li> </ul>
<p>In the first instance I recommend inheriting from wxControl not wxWindow, wxControl is designed for that exact purpose and you are less likely to find yourself fighting the system. When I look at a control I am building in my own wxWidgets app, I see that my click handler is attached to wxEVT_LEFT_DOWN. Looking in my copy of Cross Platform GUI Programming with wxWidgets I can see a list of all wxMouseEvents, and there is no wxEVT_LEFT_CLICK. I would suggest wxEVT_LEFT_DOWN is the event to use.</p> <p>Now after posting I've read Burly's answer and I agree with him, wxWidgets offers the lowest level events and that gives you the maximum amount of control of the user interface you construct for your users.</p>
12,424
<p>I have a ASP.Net page using ADO to query MS access database and as a learning exercise i would like to incorporate LINQ. I have one simple table called Quotes.</p> <p>The fields are: QuoteID, QuoteDescription, QuoteAuthor, QuoteDate. I would like to run simple queries like, "Give me all quotes after 1995". </p> <p>How would i incorporate LINQ into this ASP.Net site (C#)</p> <p>Basically, my question is does LINQ work for MS Access ??</p>
<p>LINQ to SQL doesn't support Access (that is, there's no Access/Jet provider for LINQ), but you can query a DataSet with LINQ. This means that you fill your DataSet with any possible data from your database that you might need in your results, and then you filter on the client side. After you have a typed DataSet, and you Fill() it with a TableAdapter, you do something like this:</p> <pre><code>var year = 1995; // you can pass the year into a method so you can filter on any year var results = from row in dsQuotes where row.QuoteDate &gt; year select row; </code></pre> <p>You'll have to decide whether this is worth it. You'd have to fill your DataSet with <em>all</em> the quotes, then use LINQ to filter on just those quotes that are after 1995. For a small amount of data, sure, why not? But for a very large amount of data, you'll need to make sure it won't be too slow.</p> <p>If you're using a DataSet, though, you can write custom queries that become new TableAdapter methods. So you can put the correct SQL for your query in a FillByYear() method in your TableAdapter and use that to fill your typed DataTable. That way you're only getting back the data you need.</p> <p>If you go this route, remember that Access/Jet uses positional parameters, not named parameters. So instead of</p> <pre><code>SELECT * FROM Quotes WHERE Year(QuoteDate) &gt; @Year </code></pre> <p>you'd use something like this:</p> <pre><code>SELECT * FROM Quotes WHERE Year(QuoteDate) &gt; ? </code></pre>
<p>I don't <em>think</em> LINQ to SQL supports Access. However, if your table is sufficiently small to fit into memory, LINQ to DataSet will let you query datatables etc pretty easily - especially strongly typed datasets.</p>
23,640
<p>Note: Using MySQL 4.0, which means no subqueries (at present).</p> <p>I have 2 tables:</p> <ul> <li>A "user_details" table</li> <li>A "skills" table, which has the user_id and a "skill_id", which maps to a predefined set of skills defined elsewhere.</li> </ul> <p>The current query allows an admin to search for users by selecting skills, and the query works in an OR fashion, eg:</p> <pre><code>LEFT JOIN skills ON (ud.user_id = skills.user_id) WHERE skills.skill_id in (51, 52, 53, 54, 55) GROUP BY ud.user_id </code></pre> <p>This returns too many records and thus I want this search field to work in an AND fashion, where a user must have ALL the selected skills to be returned in the search.</p> <p>It may be possible to get MySQL upgraded if subqueries are the best option.</p> <p>edit: Something to do with group by, count, having etc. Can you restrict a group by command with a requirement on how many matched rows you return? (eg 5 in this example).</p> <p>edit2: Testing out:</p> <pre><code>HAVING COUNT( * ) &gt; 5 </code></pre>
<p>You don't need a subquery or a join.</p> <pre><code>SELECT user_id FROM skills WHERE skill_id IN (51, 52, 53, 54, 55) GROUP BY user_id HAVING COUNT(*) = 5; </code></pre>
<p>If you wanted the user details included in the same query you could simply do the following:</p> <pre><code>SELECT * FROM user_details JOIN skills USING (user_id) WHERE skill_id IN (51, 52, 53, 54, 55) GROUP BY user_id HAVING COUNT(*) = 5 </code></pre>
47,174
<p>I'm looking for a simple Python script that can minify CSS as part of a web-site deployment process. (Python is the only scripting language supported on the server and full-blown parsers like <a href="http://cthedot.de/cssutils/" rel="noreferrer">CSS Utils</a> are overkill for this project).</p> <p>Basically I'd like <a href="http://www.crockford.com/javascript/jsmin.py.txt" rel="noreferrer">jsmin.py</a> for CSS. A single script with no dependencies.</p> <p>Any ideas?</p>
<p>This seemed like a good task for me to get into python, which has been pending for a while. I hereby present my first ever python script:</p> <pre><code>import sys, re with open( sys.argv[1] , 'r' ) as f: css = f.read() # remove comments - this will break a lot of hacks :-P css = re.sub( r'\s*/\*\s*\*/', "$$HACK1$$", css ) # preserve IE&lt;6 comment hack css = re.sub( r'/\*[\s\S]*?\*/', "", css ) css = css.replace( "$$HACK1$$", '/**/' ) # preserve IE&lt;6 comment hack # url() doesn't need quotes css = re.sub( r'url\((["\'])([^)]*)\1\)', r'url(\2)', css ) # spaces may be safely collapsed as generated content will collapse them anyway css = re.sub( r'\s+', ' ', css ) # shorten collapsable colors: #aabbcc to #abc css = re.sub( r'#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3(\s|;)', r'#\1\2\3\4', css ) # fragment values can loose zeros css = re.sub( r':\s*0(\.\d+([cm]m|e[mx]|in|p[ctx]))\s*;', r':\1;', css ) for rule in re.findall( r'([^{]+){([^}]*)}', css ): # we don't need spaces around operators selectors = [re.sub( r'(?&lt;=[\[\(&gt;+=])\s+|\s+(?=[=~^$*|&gt;+\]\)])', r'', selector.strip() ) for selector in rule[0].split( ',' )] # order is important, but we still want to discard repetitions properties = {} porder = [] for prop in re.findall( '(.*?):(.*?)(;|$)', rule[1] ): key = prop[0].strip().lower() if key not in porder: porder.append( key ) properties[ key ] = prop[1].strip() # output rule if it contains any declarations if properties: print "%s{%s}" % ( ','.join( selectors ), ''.join(['%s:%s;' % (key, properties[key]) for key in porder])[:-1] ) </code></pre> <p>I believe this to work, and output it tests fine on recent Safari, Opera, and Firefox. It will break CSS hacks other than the underscore &amp; /**/ hacks! Do not use a minifier if you have a lot of hacks going on (or put them in a separate file).</p> <p>Any tips on my python appreciated. Please be gentle though, it's my first time. :-)</p>
<p>I don't know of any ready made python css minifiers, but like you said css utils has the option. After checking and verifying that the license allows for it, you could go through the source code and snip out the portions that do the minifying yourself. Then stick this in a single script and voila! There you go.</p> <p>As a head start, the csscombine function in .../trunk/src/cssutils/script.py seems to do the work of minifying somewhere around line 361 (I checked out revision 1499). Note the boolean function argument called "minify".</p>
27,464
<p>I just had to add a checkbox to an application that was written before I got here, and it was way more difficult than it had to be because the app uses some third-party LayoutManager that attempts to do pseudo-absolute, gridlike positioning. The API was terrible, it takes position-designating strings that are comma-delimited lists of two, four, or six parameters (I still don't know why this varies), and I would much rather let the LayoutManager handle a lot of this grunt work, anyway. I've always felt like allowing Swing to position things itself led to better organization than anything I could generate. I felt the same way with CGI applications, where other than occasionally grouping checkboxes or radio boxes with tables I pretty much just let the browser flow and wrap things however the user wants.</p> <p>Are the LayoutManager implementations included with Swing adequate, or is it really necessary to incorporate this kind of absolute control to force the layout to be exactly what you want (and give you a million more decisions to make)?</p>
<p>This situation is getting a lot better. I would say the three most common non-standard layout managers are:</p> <ul> <li>JGoodies FormLayout</li> <li>TableLayout</li> <li>MigLayout</li> </ul> <p>The last two are pretty similar, but MigLayout came slightly later, and will be part of the JDK in future. I'd say any of the three have "standard" enough to use fairly comfortably, but MigLayout is likely to win out now it's to be part of Swing itself.</p> <p>So at the moment, I'd say no. Once MigLayout's in the JDK, yes.</p>
<p>In addition to the 3 abovementioned 3rd party layout managers, you might want to give a try to DesignGridLayout which, although not as powerful as MigLayout, is much easier to use and makes it difficult to design bad forms.</p> <p>Disclaimer: I am one of the authors of DesignGridLayout, but I really believe this is a good LayoutManager compared with Swing default ones, and also other 3rd-party layouts that are a bit too complicated to start with.</p>
41,215
<p>I do more and more exercise with Lambda but I do not figure out why sometime example use <code>.AsQueryable();</code> that use the IQueryable and sometime it omit the <code>.AsQueryable();</code> and use the IEnumerable.</p> <p>I have read the <a href="http://msdn.microsoft.com/en-us/library/bb351562.aspx" rel="nofollow noreferrer">MSDN</a> but I do no see how "executing an expression tree" is an advantage over not.</p> <p>Anyone can explain it to me?</p>
<p>IQueryable implements IEnumerable, so right off the bat, with IQueryable, you can do everything that you can do with IEnumerable. IQueryables deal with converting some lambda expression into query on the underlying data source - this could be a SQL database, or an object set. </p> <p>Basically, you should usually not have to care one way or the other if it is an IQueryable, or an IEnumerable.</p>
<p>I agree with Arne Claassen, there are cases when you need to think about the underlying implmentatoin provided by the data sources. For example check this <a href="http://jonkruger.com/blog/2007/10/19/iqueryable-vs-ienumerable-in-linq-to-sql-queries/" rel="nofollow noreferrer">blog post</a> which shows how the SQL generated by IEnumerable and IQueryable are different in certain scenarios.</p>
30,434
<p>I want to build a toolchain from gnuarm.org from sources. I don't want to use binary version because i'm running x64 linux. Can you point me to some kind of tutorial?</p>
<p>Here are the default commands/parameters used to build the binary packages. Download the sources, unpack and issue them:</p> <ol> <li>cd [binutils-build]</li> <li>[binutils-source]/configure --target=arm-elf --prefix=[toolchain-prefix] --enable-interwork --enable-multilib --with-float=soft</li> <li>make all install</li> <li>export PATH="$PATH:[toolchain-prefix]/bin"</li> <li>cd [gcc-build]</li> <li>[gcc-source]/configure --target=arm-elf --prefix=[toolchain-prefix] --enable-interwork --enable-multilib --with-float=soft --enable-languages="c,c++" --with-newlib --with-headers=[newlib-source]/newlib/libc/include</li> <li>make all-gcc install-gcc</li> <li>cd [newlib-build]</li> <li>[newlib-source]/configure --target=arm-elf --prefix=[toolchain-prefix] --enable-interwork --enable-multilib --with-float=soft <ol start="10"> <li>make all install</li> <li>cd [gcc-build]</li> <li>make all install</li> <li>cd [gdb-build]</li> <li>[gdb-source]/configure --target=arm-elf --prefix=[toolchain-prefix] --enable-interwork --enable-multilib --with-float=soft</li> <li>make all install </li> </ol></li> </ol> <p>lines 11-12 seem to have no effect. Using gcc &lt; 4.x is not advised, and building binutils can give the following error:</p> <p>../../binutils-2.19/gas/config/tc-arm.c: In function 's_arm_unwind_save_mmxwr': ../../binutils-2.19/gas/config/tc-arm.c:3459: error: format not a string literal and no format arguments</p> <p>the solution is easy, just add "%s" as the FIRST parameter to the lines with error as the patch here suggests: <a href="http://www.mail-archive.com/bug-binutils@gnu.org/msg06475.html" rel="nofollow noreferrer">http://www.mail-archive.com/bug-binutils@gnu.org/msg06475.html</a></p> <p>I could not build insight but i guess it is possible to debug it with something else.</p>
<ol> <li>Download the sources available under "Files"</li> <li>Unpack them </li> <li><p>Go to each unpacked directory and type:</p> <p>./configure --help</p> <p>to get the available options, then run</p> <p>./configure [options]</p> <p>make</p> <p>make check</p> <p>make install</p></li> </ol>
43,950
<p>What is the content type for MHT files?</p>
<p>Microsoft, who co-authored the spec for MHT, seem to think that it should be '<code>message/rfc822</code>' on <a href="http://support.microsoft.com/kb/937912" rel="nofollow noreferrer">this support page</a>.</p> <p>No specific MIME type seems to be given in the spec though: <a href="https://www.rfc-editor.org/rfc/rfc2557" rel="nofollow noreferrer">RFC2557: MIME Encapsulation of Aggregate Documents, such as HTML (MHTML)</a></p>
<p>application/octet-stream</p> <p>You can stream the contents of a .eml file to a browser with this content type and .mht as the extension, and the email will be rendered similar to the way it is rendered in an email client.</p>
5,117
<p>I have an articles table and a categories table. I want to fetch 7 articles for each category. Currently I have this but it's terrible slow on large tables so it's not really a solution:</p> <pre><code>SELECT id, title, categories_id, body, DATE_FORMAT(pubdate, "%d/%m/%y %H:%i") as pubdate FROM articles AS t WHERE ( SELECT COUNT(*) FROM articles WHERE t.categories_id = categories_id AND id&lt; t.id AND publish = 1 AND expires &gt; '2008-12-14 18:38:02' AND pubdate &lt;= '2008-12-14 18:38:02' ) &lt; 7 ORDER BY categories_id DESC </code></pre> <p>Using explain, it shows me it's doing a join type ALL &amp; REF. The select types are PRIMARY and DEPENDENT SUBQUERY .</p> <p>Is there a better solution?</p>
<p>Here's how I'd solve this problem:</p> <pre><code>SELECT a1.id, a1.title, a1.categories_id, a1.body, DATE_FORMAT(a1.pubdate, "%d/%m/%y %H:%i") as pubdate FROM articles AS a1 LEFT OUTER JOIN articles AS a2 ON (a1.categories_id = a2.categories_id AND (a1.pubdate &lt; a2.pubdate OR (a1.pubdate = a2.pubdate AND a1.id &lt; a2.id))) GROUP BY a1.id HAVING COUNT(*) &lt; 7; </code></pre> <p>A correlated subquery usually performs poorly, so this technique uses a join instead.</p> <p>For a given article, search for articles (a2) that match the category of the current article under consideration (a1), and have a more recent date (or higher <code>id</code> in the case of a tie). If there are fewer than seven articles that meet that criteria, then the current one must be among the most recent of its category.</p> <p>If you can rely on the unique <code>id</code> column having the same sort order as <code>pubdate</code>, then you can simplify the join because there will be no ties over a unique column:</p> <pre><code> ON (a1.categories_id = a2.categories_id AND a1.id &lt; a2.id) </code></pre>
<p>You have several options - some might result in performance issues but it depends on many factors.</p> <p>You could split it into several queries. One query to read out all the categories:</p> <pre><code>SELECT categories_id FROM Categories </code></pre> <p>Then for each category, read out the top seven articles:</p> <pre><code>SELECT id, title, ...etc. FROM articles where categories_id = 1 </code></pre> <p>... and so on for each category.</p> <p>This has the benefit of being a bit simpler to understand but the downside is it turns one query into 1 + (1* number of cats). Then again, you could put a limit on the number of categories so you have some element of control. Sometimes you find that 5 simple queries perform a lot better than 1 complicated one!</p> <p>This kind of assumes you are calling the SQL from some code you have control of - is this the case?</p>
47,893
<p>Do you know a simple script to count NLOCs (netto lines of code). The script should count lines of C Code. It should not count empty lines or lines with just braces. But it doesn't need to be overly exact either.</p>
<p>I would do that using <strong>awk</strong> &amp; <strong>cpp</strong> (preprocessor) &amp; <strong>wc</strong> . awk removes all braces and blanks, the preprocessor removes all comments and wc counts the lines:</p> <pre><code>find . -name \*.cpp -o -name \*.h | xargs -n1 cpp -fpreprocessed -P | awk '!/^[{[:space:]}]*$/' | wc -l </code></pre> <p>If you want to have comments included:</p> <pre><code>find . -name \*.cpp -o -name \*.h | xargs awk '!/^[{[:space:]}]*$/' | wc -l </code></pre>
<p>I have a program called <code>scc</code> that strips C comments (and C++ comments, though with C99 they're the same). Apply that plus a filter to remove blank lines and, if so desired, lines containing just open and close braces, to generate the line counts. I've used that on internal projects - not needed to discount open/close braces. Those scripts were more complex, comparing the source code for two different versions of a substantial project stored in ClearCase. They also did statistics on files added and removed, and on lines added and removed from common files, etc.</p> <p>Not counting braces makes quite a difference:</p> <pre><code>Black JL: co -q -p scc.c | scc | sed '/^[ ]*$/d' | wc -l 208 Black JL: co -q -p scc.c | scc | sed '/^[ {}]*$/d' | wc -l 144 Black JL: co -p -q scc.c | wc -l 271 Black JL: </code></pre> <p>So, 144 lines under your rules; 208 counting open and close brace lines; 271 counting everything.</p> <p>Lemme know if you want the code for <code>scc</code> (send email to first dot last at gmail dot com). It's 13 KB of gzipped tar file including man page, torture test, and some library files.</p> <hr> <p>@litb commented that '<code>cpp -fpreprocessed -P file</code>' handles stripping of comments. It mostly does. However, when I run it on the stress test for SCC, it complains when (in my opinion) it should not:</p> <pre><code>SCC has been trained to handle 'q' single quotes in most of the aberrant forms that can be used. '\0', '\', '\'', '\\ n' (a valid variant on '\n'), because the backslash followed by newline is elided by the token scanning code in CPP before any other processing occurs. </code></pre> <p>When the CPP from GCC 4.3.2 processes this, it complains (warns):</p> <pre><code>SCC has been trained to handle 'q' single quotes in most of &lt;stdin&gt;:2:56: warning: missing terminating ' character the aberrant forms that can be used. '\0', '\', '\'', '\\ &lt;stdin&gt;:3:27: warning: missing terminating ' character n' (a valid variant on '\n'), because the backslash followed by newline is elided by the token scanning code in CPP before any other processing occurs. </code></pre> <p>Section 5.1.1.2 Translation Phases of the C99 standard says:</p> <blockquote> <p>The precedence among the syntax rules of translation is specified by the following phases.(<em>Footnote 5</em>)</p> <ol> <li><p>Physical source file multibyte characters are mapped, in an implementation-defined manner, to the source character set (introducing new-line characters for end-of-line indicators) if necessary. Trigraph sequences are replaced by corresponding single-character internal representations.</p></li> <li><p>Each instance of a backslash character () immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character before any such splicing takes place.</p></li> </ol> <p>Footnote 5 is:</p> <p>(5) Implementations shall behave as if these separate phases occur, even though many are typically folded together in practice.</p> </blockquote> <p>Consequently, in my view, CPP is mishandling phase two in the example text. Or, at least, the warning is not what I want - the construct is valid C and it is not self-evident that the warning is warranted.</p> <p>Granted, it is an edge case, and extra warnings are permitted. But it would annoy the living daylights out of me. If I didn't have my own, possibly better tool for the job, then using '<code>cpp -fpreprocessed -P</code>' would do - it is an extreme edge case that I'm complaining about (and, it might be legitimate to argue that it is more likely that there is a problem than not -- though a better heuristic would observe that the line was spliced and the result was a legitimate single character constant and therefore the complaint should be suppressed; if the result was not a legitimate single character constant, then the complaint should be produced. (On my test case - admittedly a torture test - CPP yields 13 problems, mostly related to the one I'm complaining about, where SCC correctly yields 2.)</p> <p>(I observe that the '<code>-P</code>' manages to suppress a '<code>#line</code>' directive in the output that appears when the option is omitted.)</p>
41,865
<p>What the best way to get up to speed on MathML and its usage in the world?</p> <p>In particular I mean:</p> <ul> <li>What do you use for rendering/editing it</li> <li>Is it used in any commercial/open source applications that you can point me to</li> <li>Is it popular and used a lot?</li> <li>Are there any viewers that can be used inside a C#, C++, Java, ... application?</li> <li>... (any other info available about MathML)</li> </ul>
<p>The <a href="http://www.w3.org/Math/" rel="nofollow noreferrer">W3C's MathML homepage</a> is of course a good place to start. They have a list of software using MathML. There are two portions to the MathML specification: the presentation set, which will tell a rendering engine how to typeset the equation (for instance, distinguishing between a stacked vs. beveled fraction), and the content set, which will tell calculation engines how to interpret the equation (is y(x) a function y of x or two variables being multiplied?). Most applications will focus on one subset of MathML or the other depending on the scope of the application.</p> <p>MathML is being used more and more widely and with good reason - MathML has all of the advantages of XML (for more information, see our white paper <a href="http://dessci.com/en/reference/white_papers/mathml_is_xml.htm" rel="nofollow noreferrer">MathML is XML</a>).</p> <p>Design Science makes <a href="http://dessci.com/en/products/webeq/" rel="nofollow noreferrer">WebEQ</a>, which includes components for editing and displaying MathML on your website. We also have an SDK version if you would like to include these components in a desktop application. WebEQ is Java based.</p> <p>Hope this helps, but if you have more questions, feel free to email support@dessci.com.</p> <p>Best wishes,</p> <p>Autumn Cuellar, XML Specialist at Design Science</p>
<p>Likely not what you wanted to hear, but after trying MathML I went back to TeX, as it's far more readable and compact than the XML representation. TeX also has a large user base and a number of stable, open WYSIWYG editors.</p> <p>Also, <a href="http://www.mozilla.org/projects/mathml/" rel="nofollow noreferrer">Mozilla MathML</a> page contains links to a TeX->MathML translator and a (possibly dead) javascript MathML editor</p>
26,516
<p>I'm trying to chart the number of registrations per day in our registration system. I have an Attendee table in sql server that has a smalldatetime field A_DT, which is the date and time the person registered.</p> <p>I started with this:</p> <pre><code>var dailyCountList = (from a in showDC.Attendee let justDate = new DateTime(a.A_DT.Year, a.A_DT.Month, a.A_DT.Day) group a by justDate into DateGroup orderby DateGroup.Key select new RegistrationCount { EventDateTime = DateGroup.Key, Count = DateGroup.Count() }).ToList(); </code></pre> <p>That works great, but it won't include the dates where there were no registrations, because there are no attendee records for those dates. I want every date to be included, and when there is no data for a given date, the count should just be zero.</p> <p>So this is my current working solution, but I KNOW THAT IT IS TERRIBLE. I added the following to the code above:</p> <pre><code>// Create a new list of data ranging from the beginning to the end of the first list, specifying 0 counts for missing data points (days with no registrations) var allDates = new List&lt;RegistrationCount&gt;(); for (DateTime date = (from dcl in dailyCountList select dcl).First().EventDateTime; date &lt;= (from dcl in dailyCountList select dcl).Last().EventDateTime; date = date.AddDays(1)) { DateTime thisDate = date; // lexical closure issue - see: http://www.managed-world.com/2008/06/13/LambdasKnowYourClosures.aspx allDates.Add(new RegistrationCount { EventDateTime = date, Count = (from dclInner in dailyCountList where dclInner.EventDateTime == thisDate select dclInner).DefaultIfEmpty(new RegistrationCount { EventDateTime = date, Count = 0 }).Single().Count }); } </code></pre> <p>So I created ANOTHER list, and loop through a sequence of dates I generate based on the first and last registrations in the query, and for each item in the sequence of dates, I QUERY the results of my first QUERY for the information regarding the given date, and supply a default if nothing comes back. So I end up doing a subquery here and I want to avoid this.</p> <p>Can anyone thing of an elegant solution? Or at least one that is less embarrassing?</p>
<p>O(n) with 2 enumerations. It's very good to pull the items into memory before trying this. Database has enough to do without thinking about this stuff.</p> <pre><code> if (!dailyCountList.Any()) return; //make a dictionary to provide O(1) lookups for later Dictionary&lt;DateTime, RegistrationCount&gt; lookup = dailyCountList.ToDictionary(r =&gt; r.EventDateTime); DateTime minDate = dailyCountList[0].EventDateTime; DateTime maxDate = dailyCountList[dailyCountList.Count - 1].EventDateTime; int DayCount = 1 + (int) (maxDate - minDate).TotalDays; // I have the days now. IEnumerable&lt;DateTime&gt; allDates = Enumerable .Range(0, DayCount) .Select(x =&gt; minDate.AddDays(x)); //project the days into RegistrationCounts, making up the missing ones. List&lt;RegistrationCount&gt; result = allDates .Select(d =&gt; lookup.ContainsKey(d) ? lookup[d] : new RegistrationCount(){EventDateTime = d, Count = 0}) .ToList(); </code></pre>
<p>Does this syntax for left outer joins no longer work as well after SP1, then?</p> <p>Usually, you should able to do the following, but you'd need a calendar table of sorts in your SQL database joined to your date key in the registrations table (w/a foreign key on the date id field), and then try:</p> <pre><code>var query = from cal in dataContext.Calendar from reg in cal.Registrations.DefaultIfEmpty() select new { cal.DateID, reg.Something }; </code></pre>
18,105
<p>I had a discussion with a developer earlier today re identifying TCP packets going out on a particular interface with the same payload. He told me that the probability of finding a TCP packet that has an equal payload (even if the same data is sent out several times) is very low due to the way TCP packets are constructed at system level. I was aware this may be the case due to the system's MTU settings (usually 1500 bytes) etc., but what sort of probability stats am I really looking at? Are there any specific protocols that would make it easier identifying matching payloads?</p>
<p>EDIT: Sorry, my original idea was ridiculous. </p> <p>You got me interested so I googled a little bit and found <a href="http://monkey.org/~jose/software/flowgrep/" rel="nofollow noreferrer">this</a>. If you wanted to write your own tool you would probably have to inspect each payload, the easiest way would probably be some sort of hash/checksum to check for identical payloads. Just make sure you are checking the payload, not the whole packet.</p> <p>As for the statistics I will have to defer to someone with greater knowledge on the workings of TCP.</p>
<p>Sending the same PAYLOAD is probably fairly common (particularly if you're running some sort of network service). If you mean sending out the same tcp segment (header and all) or the whole network packet (ip and up), then the probability is substantially reduced.</p>
10,719
<p>I'm wondering how you'd implement the following use-case in REST. Is it even possible to do without compromising the conceptual model?</p> <p>Read or update multiple resources within the scope of a single transaction. For example, transfer $100 from Bob's bank account into John's account.</p> <p>As far as I can tell, the only way to implement this is by cheating. You could POST to the resource associated with either John or Bob and carry out the entire operation using a single transaction. As far as I'm concerned this breaks the REST architecture because you're essentially tunneling an RPC call through POST instead of really operating on individual resources.</p>
<p>Consider a RESTful shopping basket scenario. The shopping basket is conceptually your transaction wrapper. In the same way that you can add multiple items to a shopping basket and then submit that basket to process the order, you can add Bob's account entry to the transaction wrapper and then Bill's account entry to the wrapper. When all the pieces are in place then you can POST/PUT the transaction wrapper with all the component pieces. </p>
<p>I guess you could include the TAN in the URL/resource:</p> <ol> <li>PUT /transaction to get the ID (e.g. "1")</li> <li>[PUT, GET, POST, whatever] /1/account/bob</li> <li>[PUT, GET, POST, whatever] /1/account/bill</li> <li>DELETE /transaction with ID 1</li> </ol> <p>Just an idea.</p>
17,724
<p>I cloned a Git master and made a lot of changes on the clone. I have since committed these changes on the clone and now want the master to be a carbon copy of what is on the clone.</p> <p>I've tried Git push on the clone to push the changes to the master - but nothing I do updates the master.</p> <p>How can I make the master an exact copy of what is on the clone? What is the command workflow of updating the clone and having the master sync with the clone?</p>
<p>There are 2 kinds of git repository, bare and non-bare. A non bare repository is any repository which has a 'working copy' i.e. some part of the repository currently checked out.</p> <p>You <em>can</em> push into a non-bare repository, but it won't update the checked out working copy even if the checked out branch is the same as the branch you pushed. This is because the checked out copy might have changes that aren't committed, and git won't ever destroy changes without you explicitly asking (usually such commands have a --hard argument)</p> <p>Read <a href="http://git.or.cz/gitwiki/GitFaq#head-b96f48bc9c925074be9f95c0fce69bcece5f6e73" rel="noreferrer">Why won't I see changes in the remote repo after "git push"?</a> and <a href="http://git.or.cz/gitwiki/GitFaq#push-is-reverse-of-fetch" rel="noreferrer">How would I use "git push" to sync out of a firewalled host?</a> for a full description of the problem and a potential solution. Word of warning, if you've pushed into a remote repo, any non-committed changes in that remote-repo will have to be discarded.</p> <p>Generally it sounds like the approach you want isn't really adopted by gitters, because it doesn't really match the distributed repository mentality. It's your own responsibility to make sure your copy of the repo is up to date.</p>
<p>I like Gareth's and Greg's answers. I'd simply add that I find it really handy to use a bare repository to synchronize work with others. That lets anyone push/pull their changes (including branches) to the bare repository and then others can fetch/pull/merge as they see fit. It's not the same as having a single, central repository since each clone is a full-fledged repository.</p>
36,502
<p>Before anybody asks, I am not doing any kind of screenscraping.</p> <p>I'm trying to parse an html string to find a div with a certain id. I cannot for the life of me get this to work. The following expression worked in one instance, but not in another. I'm not sure if it has to do with extra elements in the html or not.</p> <pre><code>&lt;div\s*?id=(\""|&amp;quot;|&amp;#34;)content(\""|&amp;quot;|&amp;#34;).*?&gt;\s*?(?&gt;(?! &lt;div\s*?&gt; | &lt;/div&gt; ) | &lt;div\s*?&gt;(?&lt;DEPTH&gt;) | &lt;/div&gt;(?&lt;-DEPTH&gt;) | .?)*(?(DEPTH)(?!))&lt;/div&gt; </code></pre> <p>It is finding the first div with the right id correctly, but it then closes at the first closing div, and not the related div.</p> <pre><code>&lt;div id="firstdiv"&gt;begining content&lt;div id="content"&gt;some other stuff &lt;div id="otherdiv"&gt;other stuff here&lt;/div&gt; more stuff &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This should bring back</p> <pre><code>&lt;div id="content"&gt;some other stuff &lt;div id="otherdiv"&gt;other stuff here&lt;/div&gt; more stuff &lt;/div&gt; </code></pre> <p>, but for some reason, it is not. It is bring back:</p> <pre><code> &lt;div id="content"&gt;some other stuff &lt;div id="otherdiv"&gt;other stuff here&lt;/div&gt; </code></pre> <p>Does anybody have an easier expression to handle this?</p> <p>To clarify, this is in .NET, and I'm using the DEPTH keyword. You can find more details <a href="http://www.m-8.dk/resources/RegEx-Balancing-Group.aspx" rel="noreferrer">here</a>.</p>
<p>In .NET you can do this:</p> <pre><code>(?&lt;text&gt; (&lt;div\s*?id=(\"|&amp;quot;|&amp;\#34;)content(\"|&amp;quot;|&amp;\#34;).*?&gt;) (?&gt; .*?&lt;/div&gt; | .*?&lt;div (?&gt;depth) | .*?&lt;/div&gt; (?&gt;-depth) )*) (?(depth)(?!)) .*?&lt;/div&gt; </code></pre> <p>You must use the singleline option. Here is an example using the console:</p> <pre><code>using System; using System.Text.RegularExpressions; namespace Temp { class Program { static void Main() { string s = @" &lt;div id=""firstdiv""&gt;begining content&lt;div id=""content""&gt;some other stuff &lt;div id=""otherdiv""&gt;other stuff here&lt;/div&gt; more stuff &lt;/div&gt; &lt;/div&gt;"; Regex r = new Regex(@"(?&lt;text&gt;(&lt;div\s*?id=(\""|&amp;quot;|&amp;\#34;)" + @"content(\""|&amp;quot;|&amp;\#34;).*?&gt;)(?&gt;.*?&lt;/div&gt;|.*?&lt;div " + @"(?&gt;depth)|.*?&lt;/div&gt; (?&gt;-depth))*)(?(depth)(?!)).*?&lt;/div&gt;", RegexOptions.Singleline); Console.WriteLine("HTML:\n"); Console.WriteLine(s); Match m = r.Match(s); if (m.Success) { Console.WriteLine("\nCaptured text:\n"); Console.WriteLine(m.Groups[4]); } Console.ReadLine(); } } } </code></pre>
<p>What programming language? If it's .Net and you're sure the html is well-formed you can load it into an XmlDocument or XDocument object and do an xpath query on it.</p>
36,349
<p>So, I've been living with my cvs repositories for some time. Though there is a thing I miss - if i rename a file that is already in repository, I need to delete the one with old name from there and add the new one. Hence, I loose all my change-history. And sometimes there's a need to rename a file in alredy existing project.</p> <p>From what I saw, cvs/svn can't handle something like this, or am I wrong? If not, what other source control system would you recommend, that allows the renaming of files? </p>
<p>Subversion can do this, but you have to do it with </p> <pre><code>svn move &lt;oldfile&gt; &lt;newfile&gt; </code></pre> <p>Edit: And in this decade, we do <code>git mv &lt;oldfile&gt; &lt;newfile&gt;</code>, or just use <code>mv</code> and git usually figures it out on its own.</p>
<p>Subversion has rename capability.</p>
19,706
<p>I am having trouble grabbing the values from the form once processed. I need your help.</p> <pre><code>function updateUser($table, $id) { if($_POST) { processUpdate($table, $id); } else { updateForm($table, $id); } } function processUpdate($table, $id) { print $table; //testing print $id; //testing $email=addslashes($HTTP_POST_VARS['email']); $lname=addslashes($HTTP_POST_VARS['lname']); $fname=addslashes($HTTP_POST_VARS['fname']); print $lname; //which table do we update switch($table) { case "maillist": $result = mysql_query("UPDATE $table SET email='$email', lname='$lname', fname='$fname' WHERE id='$id'") or die(mysql_error()); break; } } </code></pre> <p>The function updateForm($table, $id); just outputs the form, has email, lname, fname fields. And when you process the form, the action is the same, w/ the table and id being passed thru the URL, so it GET's the id and table that way, and for lname, fname, and email, it should grab it via post.</p> <p>EDIT: this is what the form tag is for the updateForm function: <code>&lt;form method="post" action="?mode=upd&amp;id='.$id.'&amp;table='.$table.'"&gt;</code></p> <p>But for some reason, it does not post the values.</p>
<p>Is the method attribute of the form set to post?</p> <pre><code>&lt;form method = "post" action = "..."&gt; </code></pre> <p>And are all of the input's name attribute set right?</p> <p>Have you looked at the html output to make sure that there were no syntax errors? Also, try using</p> <p><code>$_POST</code></p> <p>instead of</p> <p><code>$HTTP_POST_VARS</code></p>
<p>Please make sure that you use an up-to-date tutorial for one of the latest versions of PHP5. NOT some PHP 3.x tut full of deprecated functions ;-)</p> <p>That will make your life (and ours) a whole lot easier :P</p> <p>By the way one more tip that will prevent you from having major SQL injections in this script: <strong>ESCAPE EVERY VARIABLE YOU ARE GOING TO PASS!!</strong></p> <p>You don't escape ID here, which is a nice huge hole to drop your db</p>
23,064
<p>I have seen continuations in Jetty 6.0 that addresses scaling for comet/reverse-ajax applications. </p> <p>Are there any other libraries/frameworks to be used with Tomcat 5.5? </p>
<p>I would check out DWR(Direct Web Remoting). It has fairly decent documentation and a respectable user base.</p> <p><a href="http://directwebremoting.org/" rel="nofollow noreferrer">DWR</a></p>
<p><a href="https://atmosphere.dev.java.net/" rel="nofollow noreferrer">Atmosphere</a> is the kind of thing I was looking for.</p>
23,958
<p>I have been working for a while to create an iPhone app. Today when my battery was low, I was working and constantly saving my source files then the power went out...</p> <p>Now when I plugged my computer back in and it is getting good power I try to open my project file and I get an error:</p> <blockquote> <p>Unable to Open Project</p> <p>Project ... cannot be opened because the project file cannot be parsed.</p> </blockquote> <p>Is there a way that people know of that I can recover from this? I tried using an older project file and re inserting it and then compiling. It gives me a funky error which is probably because it isn't finding all the files it wants...</p> <p>I really don't want to rebuild my project from scratch if possible.</p> <hr /> <h3>EDIT</h3> <p>Ok, I did a diff between this and a slightly older project file that worked and saw that there was some corruption in the file. After merging them (the good and newest parts) it is now working.</p> <p>Great points about the SVN. I have one, but there has been some funkiness trying to sync XCode with it. I'll definitely spend more time with it now... ;-)</p> <p><img src="https://i.stack.imgur.com/Up53v.png" alt="enter image description here" /></p>
<p>I came across this problem and my senior told me about a solution i.e:</p> <p>Right click on your <code>projectname.xcodeproj</code> file here <code>projectname</code> will be the name of your project. Now after right clicked select <em>Show Packages Contents</em>. After that open your <code>projectname.pbxproj</code> file in a text editor. Now search for the line containing <code>&lt;&lt;&lt;&lt;&lt;&lt;&lt; .mine</code>, <code>=======</code> and <code>&gt;&gt;&gt;&gt;&gt;&gt;&gt; .r</code>. For example in my case it looked liked this </p> <pre><code>&lt;&lt;&lt;&lt;&lt;&lt;&lt; .mine    9ADAAC6A15DCEF6A0019ACA8 .... in Resources */, =======    52FD7F3D15DCEAEF009E9322 ... in Resources */, &gt;&gt;&gt;&gt;&gt;&gt;&gt; .r269 </code></pre> <p>Now remove those <code>&lt;&lt;&lt;&lt;&lt;&lt;&lt; .mine</code>, <code>=======</code> and <code>&gt;&gt;&gt;&gt;&gt;&gt;&gt; .r</code> lines so it would look like this </p> <pre><code>    9ADAAC6A15DCEF6A0019ACA8 /* BuyPriceBtn.png in Resources */,    52FD7F3D15DCEAEF009E9322 /* discussionForm.zip in Resources */, </code></pre> <p>Now save and open your Xcode project and build it. Everything will be fine.</p>
<p>subversion will corrupt my project file after a svn up on an almost weekly basis. I'm trying to figure out why it does this right now and came across this problem. </p>
47,219
<p>This is a weird problem I have started having recently. My team is developing a COTS application and we have a few people with their hands in the code. A few weeks ago, I received an error message when trying to debug (and run the compiled EXE):</p> <blockquote> <p>"Windows cannot access the specified device, path, or file. You may not have the appropriate permissions to access the item."</p> </blockquote> <p>It ended up I had to refactor this snippet of code:</p> <pre><code>mcolSchedulesNeedingOverride(New Guid(lstrErrorParts(0))) &amp;= vbNewLine &amp; lstrErrorParts(2) </code></pre> <p>In to this:</p> <pre><code>Dim lguidKey As New Guid(lstrErrorParts(0)) Dim lstrErrorMsg As String = mcolSchedulesNeedingOverride(lguidKey) lstrErrorMsg &amp;= vbNewLine &amp; lstrErrorParts(2) mcolSchedulesNeedingOverride(lguidKey) = lstrErrorMsg </code></pre> <p>That then allowed VS to generate a EXE that actually worked. I really don't understand why, but it worked. I did use the peverify utility to determine which assembly was having an issue.</p> <p>Now I have the same issue in a different code branch after about 25 files were updated yesterday. This is NOT going to be fun to track down - so I was hoping someone could offer some insight as to why this might be happening - and that might help me narrow down where to look.</p> <p>peverify shows all <em>our</em> assemblies to be correct, but is spitting back 90+ errors for System.Windows.Forms.dll!</p> <p>Anybody have any tips?</p>
<p>You say that you have several developers working on the project, so I wonder whether they experience this problem as well. </p> <p>If it is only happening on your machine than I would not go searching for a problem inside the code (the refactoring that you did seems quite unrelated to the error so I guess the reason why it was working afterwards was another) but go looking for a problem in your environment. </p> <p>Maybe something is broken or incorrectly configured with you .NET Framework installation. Can you see which file is throwing the error message? Any policy defined for any assembly on your machine?</p>
<p>I most commonly encounter that error message when I pull a binary off the net/some untrusted location. Windows will be "helpful" and block access to it.</p> <p>Right click the file and choose properties, then 'unblock'</p> <p>It's strange that the error manifests itself differently elsewhere, so this may be totally unrelated; but building on your machine would have windows treating the file differently than a downloaded copy...not sure how that relates to a reboot though.</p> <p>Edit: see <a href="http://support.microsoft.com/kb/883260" rel="nofollow noreferrer">this</a> kb article for a more thorough description of the "functionality" I was referring to</p>
41,087
<p>I know this isn't strictly speaking a programming question but something I always hear from pseudo-techies is that having a lot of entries in your registry slows down your Windows-based PC. I think this notion comes from people who are trying to troubleshoot their PC and why it's running so slow and they open up the registry at some point and see leftover entries from programs they uninstalled ages ago.</p> <p>But is there any truth to this idea? I would not think so since the registry is essentially just a database and drilling down to an entry wouldn't take significantly longer on a larger registry. But does it?</p> <p><strong>EDIT:</strong> To be clear, I'm not looking for advice on how to make a PC run faster, or asking why my PC in particular is slow (it's not), I'm just curious if people who say "bigger registry means slower PC" are accurate or not.</p>
<p>In short, not really. </p> <p>In the old days when machines were slower the answer was yes; but having a modern processor rip through even a 60MB registry is not a problem.</p> <p>Typically, the real reason a modern machine starts running slow is due to everything from malware to virus scanners: Mcafee, Norton's, etc are prime targets in my mind.</p> <p>Also, the WinSXS folder tends to grow as service packs and applications are installed. This seems to have a negative impact on system performance. There are only two possible solutions in this scenario. First, if possible, reinstall the OS with the latest service pack already slipstreamed into the install. Second, if that isn't possible AND you are running Vista with SP1, you can run the vsp1cln.exe tool (see <a href="http://technet.microsoft.com/en-us/library/cc766219.aspx" rel="nofollow noreferrer">technet</a>) which will clean up a lot of the older versions of components. Note that this tool can only be executed once and it does not allow you to roll back.</p>
<p>any problems occur on the registry could also make your computer much slower.the fix registry problems you need to install a <a href="http://www.windows7-slow.com/computer-running-extremely-slow/" rel="nofollow">registry cleaner</a> as this will fix the errors and make your pc back to its normal state.</p>
7,317
<p>I want to compute for month difference of 2 dates which will return a float value.</p> <p>example:</p> <p>date1='4/23/2008' date2='12/31/2008'</p> <p>that will be 7.y months. I want to find the y value. can someone give me the formula to make this in sql codes? tnx..</p>
<p>There's no standard sql to handle this universally. It depends on what database you're using. Basically, you need to convert the two date strings to the date format your database engine uses internally and subtract the two dates, what the result of the subtraction means will, again, depend. In Oracle, you'd use <code>to_date()</code> for the conversion and the result of the subtraction will be a float representing the time in number of days.</p> <p>In short, search your db's manual for a section about date handling or data types.</p>
<p>An approximately result for Sql Server;</p> <pre><code>select cast(datediff(dd, date1, date2) as float) / 30 </code></pre>
31,015
<p>I made a rotating image fader using Javascript and CSS to show images and unload them. I wanted to use transparent PNG's, I didn't expect or care if they looked good in IE 6, but IE 7 and 8 treated them with the same disrespect. Firefox and other modern browsers looked great. <br>Every picture with <code>image.filter = alpha(opacity=xxx)</code> in it looks like some of the transparency has some leftover noise, maybe from compression or something, no matter what I do to the picture, there's still something there. <p> I've done workarounds by placing JPG's on white background and using GIF's. <br>Also can someone tell me if this is actually a bug in IE? <hr> Let me know if you need an example and I'll make one</p>
<p>I like <a href="http://www.gtk.org/" rel="nofollow noreferrer">GTK+</a> personally but that or any of the ones you mentioned should be OK. I don't know which is the best in terms of least RAM usage.</p>
<p>I think you should try Html Application.It is something like web page it contain DHTML,java script,ActiveX but it is execute like .exe .</p> <p><strong>Edit:</strong> Sorry for advice you html application.I just know it can run on windows only.</p>
13,829
<p>I am looking for a little bit of JQuery or JS that allows me to produce a horizontally scrolling "news ticker" list.</p> <p>The produced HTML needs to be standards compliant as well.</p> <p>I have tried <a href="http://www.gcmingati.net/wordpress/wp-content/lab/jquery/newsticker/jq-liscroll/scrollanimate.html" rel="noreferrer">liScroll</a> but this has a habit of breaking (some content ends up on a second line at the start of the scroll), especially with longer lists.</p> <p>I have also tried <a href="http://www.mioplanet.com/rsc/newsticker_javascript.htm" rel="noreferrer">this News Ticker</a> but when a DOCTYPE is included the scrolling will jolt rather than cycle smoothly at the end of each cycle.</p> <p>Any suggestions are appreciated.</p> <p><strong>Edit</strong></p> <p>So thanks to Matt Hinze's suggestion I realised I could do what I wanted to do with JQuery animate (I require continuous scrolling not discrete scrolling like the example). However, I quickly ran into similar problems to those I was having with liScroll and after all that realised a CSS issue (as always) was responsible.</p> <p>Solution: liScroll - change the default 'var stripWidth = 0' to something like 100, to give a little space and avoid new line wrapping.</p>
<p>Smooth Div Scroll can also be used as a news ticker/stock ticker. It can pause on mouse over or mouse down and it can loop endlessly if you want it to.</p> <p>Here's <a href="http://www.maaki.com/" rel="nofollow noreferrer">the example</a> with a running ticker.</p>
<p>An Alternative solution would also be the <a href="http://jonmifsud.com/web-tools/jquery-webticker/" rel="nofollow">jQuery webTicker</a>; its very similar to liscroll however resolves the problem with the ticker stopping after the whole list completes; whilst also adding some new fancy features like; direction of movement; speed; and ability to use multiple tickers per page.</p>
6,231
<p>Where I'm at the developers have been updated to Excel 2007, but most of the users haven't. I'm building a spreadsheet template (*.xlt) for a user that's gonna need some vba code included, and I'm wondering what issues I'm likely to run into building this in 2007 instead of 2003? I don't have access to a machine with Excel 2003 for testing, and I'm worried this particular project is headed for disaster.</p>
<p>The VBA language hasn't changed, but there are additional objects in Office 2007 that are not in Office 2003. Naturally, this will cause a runtime error when you try to access these items in a 2003 environment. What's stopping you from setting about a virtual machine with Excel 2003 to develop under?</p>
<p>i used to develop a lot of macros under 2003, what a POTA,, things like Find, Dir and some others are not available or something change. therefore some erros can be expected, i used to count from 65000 row to the first non empty row to count the rows to work on.... now more rows means more work to do </p>
24,145
<p>The MSDN documentation on <a href="http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx" rel="noreferrer">Object.GetHashCode()</a> describes 3 contradicting rules for how the method should work. </p> <ol> <li>If two objects of the same type represent the same value, the hash function must return the same constant value for either object.</li> <li>For the best performance, a hash function must generate a random distribution for all input.</li> <li>The hash function must return exactly the same value regardless of any changes that are made to the object.</li> </ol> <p>Rules 1 &amp; 3 are contradictory to me.</p> <p>Does Object.GetHashCode() return a unique number based on the <strong>value</strong> of an object, or the <strong>reference</strong> to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows.</p>
<blockquote> <p>Rules 1 &amp; 3 are contradictory to me.</p> </blockquote> <p>To a certain extent, they are. The reason is simple: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. It is important that while objects are stored in a hash table, they retain their hash value.</p> <p>To realize this it is often simplest to make hashable objects immutable, thus evading the whole problem. It is however sufficient to make only those fields immutable that determine the hash value.</p> <p>Consider the following example:</p> <pre><code>struct Person { public readonly string FirstName; public readonly string Name; public readonly DateTime Birthday; public int ShoeSize; } </code></pre> <p>People rarely change their birthday and most people never change their name (except when marrying). However, their shoe size may grow arbitrarily, or even shrink. It is therefore reasonable to identify people using their birthday and name but not their shoe size. The hash value should reflect this:</p> <pre><code>public int GetHashCode() { return FirstName.GetHashCode() ^ Name.GetHashCode() ^ Birthday.GetHashCode(); } </code></pre>
<p>By default it does it based on the reference to the object, but that means that it's the exact same object, so both would return the same hash. But a hash should be based on the value, like in the case of the string class. "a" and "b" would have a different hash, but "a" and "a" would return the same hash.</p>
5,475
<p>Below is an example class hierarchy and code. What I'm looking for is a way to determine if 'ChildClass1' or 'ChildClass2' had the static method whoAmI() called on it without re-implementing it in each child class.</p> <pre><code>&lt;?php abstract class ParentClass { public static function whoAmI () { // NOT correct, always gives 'ParentClass' $class = __CLASS__; // NOT correct, always gives 'ParentClass'. // Also very round-about and likely slow. $trace = debug_backtrace(); $class = $trace[0]['class']; return $class; } } class ChildClass1 extends ParentClass { } class ChildClass2 extends ParentClass { } // Shows 'ParentClass' // Want to show 'ChildClass1' print ChildClass1::whoAmI(); print "\n"; // Shows 'ParentClass' // Want to show 'ChildClass2' print ChildClass2::whoAmI(); print "\n"; </code></pre>
<p>I believe what you're referring to is a known php bug. Php 5.3 is aiming to address this issue with a new Late Static Binding feature. </p> <p><a href="http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html" rel="nofollow noreferrer">http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html</a></p>
<p>No. Wait for PHP 5.3.</p>
10,943
<p>Is there a better way to do this?</p> <pre><code>string[] s = {"zero", "one", "two", "three", "four", "five"}; var x = s .Select((a,i) =&gt; new {Value = a, Index = i}) .Where(b =&gt; b.Value.StartsWith("t")) .Select(c =&gt; c.Index); </code></pre> <p>i.e. I'm looking for a more efficient or more elegant way to get the positions of the items matching the criteria.</p>
<p>You could easily add your own extension method:</p> <pre><code>public static IEnumerable&lt;int&gt; IndexesWhere&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; predicate) { int index=0; foreach (T element in source) { if (predicate(element)) { yield return index; } index++; } } </code></pre> <p>Then use it with:</p> <pre><code>string[] s = {"zero", "one", "two", "three", "four", "five"}; var x = s.IndexesWhere(t =&gt; t.StartsWith("t")); </code></pre>
<p>I discussed this interesting problem with a colleague and at first I thought JonSkeet's solution was great, but my colleague pointed out one problem, namely that if the function is an extension to <code>IEnumerable&lt;T&gt;</code>, then it can be used where a collection implements it.</p> <p>With an array, it's safe to say the order produced with <code>foreach</code> will be respected (i.e. <code>foreach</code> will iterate from first to last), but it would not necessarily be the case with other collections (List, Dictionary, etc), where <code>foreach</code> would not reflect <em>necessarily</em> "order of entry". Yet the function is there, and it can be misleading.</p> <p>In the end, I ended up with something similar to tvanfosson's answer, but as an extension method, for arrays:</p> <pre><code>public static int[] GetIndexes&lt;T&gt;(this T[]source, Func&lt;T, bool&gt; predicate) { List&lt;int&gt; matchingIndexes = new List&lt;int&gt;(); for (int i = 0; i &lt; source.Length; ++i) { if (predicate(source[i])) { matchingIndexes.Add(i); } } return matchingIndexes.ToArray(); } </code></pre> <p>Here's hoping <code>List.ToArray</code> will respect the order for the last operation...</p>
29,382
<p>I'm looking for an online solution for generating .ICO files. I'd like the ICO files to have the ability to have transparency as well.</p> <p>What software or web site do you use to create them?</p> <p>[Update]</p> <p>To clarify, I have an existing image in PNG format, 32 x 32 pixels. I want to generate the icon from this existing file, not create a brand new one online. Sorry for the confusion.</p>
<p>I have found the application <a href="http://icofx.ro/" rel="nofollow noreferrer">IcoFx</a> useful, you can import pretty much any image type to use for icon creation, including PNG's.</p>
<p>I can't imagine drawing icons online. Nowadays icons are usually <em>drawn</em> as vectors, and I'm not aware of any online vector packages.</p> <p>In case you decide to draw off-line instead, I use Xara (www.xara.com) to draw all my computer artwork, and I use Gif Movie Gear to create .ico files. The former is a superb vector package, the latter is just something I have lying around.</p>
2,974
<p>I have a problem which requires me to parse several log files from a remote machine. There are a few complications: 1) The file may be in use 2) The files can be quite large (100mb+) 3) Each entry may be multi-line</p> <p>To solve the in-use issue, I need to copy it first. I'm currently copying it directly from the remote machine to the local machine, and parsing it there. That leads to issue 2. Since the files are quite large copying it locally can take quite a while.</p> <p>To enhance parsing time, I'd like to make the parser multi-threaded, but that makes dealing with multi-lined entries a bit trickier. </p> <p>The two main issues are: 1) How do i speed up the file transfer (Compression?, Is transferring locally even neccessary?, Can I read an in use file some other way?) 2) How do i deal with multi-line entries when splitting up the lines among threads?</p> <p>UPDATE: The reason I didnt do the obvious parse on the server reason is that I want to have as little cpu impact as possible. I don't want to affect the performance of the system im testing.</p>
<p>If you are reading a sequential file you want to read it in line by line over the network. You need a transfer method capable of streaming. You'll need to review your IO streaming technology to figure this out.</p> <p>Large IO operations like this won't benefit much by multithreading since you can probably process the items as fast as you can read them over the network.</p> <p>Your other great option is to put the log parser on the server, and download the results.</p>
<p>I've used <a href="http://www.icsharpcode.net/OpenSource/SharpZipLib" rel="nofollow noreferrer">SharpZipLib</a> to compress large files before transferring them over the Internet. So that's one option.</p> <p>Another idea for 1) would be to create an assembly that runs on the remote machine and does the parsing there. You could access the assembly from the local machine using .NET remoting. The remote assembly would need to be a Windows service or be hosted in IIS. That would allow you to keep your copies of the log files on the same machine, and in theory it would take less time to process them.</p>
16,579
<p>I would like to create dynamic urls that route to controller actions with an Id value. I've created the following route using a catch-all parameter</p> <pre><code>routes.MapRoute( "RouteName", "{id}/{*Url}", new { controller = "Controller", action = "Action", id = "" } ); </code></pre> <p>This works as expected and allows me to use the following Urls:</p> <p>"<a href="http://website.com/1/fake/url/path" rel="nofollow noreferrer">http://website.com/1/fake/url/path</a>" (1 being the id that gets passed to the action method)</p> <p>Does anyone know a way to achieve it this way instead without creating my own http module?:</p> <p>"<a href="http://website.com/fake/url/path/1" rel="nofollow noreferrer">http://website.com/fake/url/path/1</a>"</p> <p>Thanks - Mark</p>
<p>That's a really difficult one, for me anyway.</p> <p>Given the following route:</p> <pre><code>routes.MapRoute("Default", "{*token}", new { controller = "Home", action = "Index", token = 0 }); </code></pre> <p>Your controller and supporting classes would be something like this:</p> <pre><code>[HandleError] public class HomeController : Controller { public ActionResult Index([ModelBinder(typeof(IndexReqquestBinder))] IndexRequest request) { ViewData["Title"] = "Home Page"; ViewData["Message"] = String.Format("We're looking at ID: {0}", request.ID); return View(); } } public class IndexRequest { public Int32 ID { get; set; } public IndexRequest(Int32 id) { this.ID = id; } } public class IndexReqquestBinder : IModelBinder { public ModelBinderResult BindModel(ModelBindingContext bindingContext) { if ( null != bindingContext.RouteData.Values["token"] ) { foreach ( String v in bindingContext.RouteData.Values["token"].ToString().Split('/') ) { Int32 id = 0; if ( Int32.TryParse(v, out id) ) { return new ModelBinderResult(new IndexRequest(id)); } } } return new ModelBinderResult(new IndexRequest(0)); } } </code></pre>
<p>I would suggest overriding of DefaultControllerFactory</p> <pre><code>&gt; public class CustomControllerFactory : DefaultControllerFactory &gt; { &gt; public override IController &gt; CreateController(System.Web.Routing.RequestContext &gt; requestContext, string controllerName) &gt; { &gt; try &gt; { &gt; return base.CreateController(requestContext, &gt; controllerName); &gt; } &gt; catch (Exception exception) &gt; { &gt; // collect route data &gt; string id = (string)requestContext.RouteData.Values["id"]; &gt; string action = (string)requestContext.RouteData.Values["action"]; &gt; // set full path as routing "page" parameter &gt; VirtualPathData path = requestContext.RouteData.Route.GetVirtualPath(requestContext, &gt; requestContext.RouteData.Values); &gt; requestContext.RouteData.Values["id"] &gt; = path.VirtualPath; // or anything you need &gt; // use controller page by default &gt; controllerName = "MyController"; &gt; // set basuc routing data &gt; requestContext.RouteData.Values["controller"] &gt; = controllerName; &gt; requestContext.RouteData.Values["action"] &gt; = "index"; &gt; // call base method to create controller &gt; return base.CreateController(requestContext, &gt; controllerName); &gt; } &gt; } &gt;} </code></pre> <p>And than just register this as default controller factory in global.asax.cs file</p> <pre><code>protected void Application_Start() { ControllerBuilder.Current.SetControllerFactory(new MyNameSpace.CustomControllerFactory ()); RegisterRoutes(RouteTable.Routes); // this already exists by default } </code></pre>
37,890
<p>I'm using PHP 5.2. I'd like to find a way to output a unique id for every object, so it's easy when looking over logs to see which objects are the same.</p> <p>In Ruby, I'd just say object.object_id to get Ruby's internal identifier for the object. There doesn't seem to be an obvious way to do this in PHP.</p> <p>Is there is a built-in way of doing this? If there isn't, can you offer any other suggestions?</p>
<p>Use <a href="http://php.net/manual/en/function.spl-object-hash.php" rel="noreferrer"><code>spl_object_hash()</code></a> for that.</p> <p>It returns an unique identifier for each object instance, and not the name of the class, so it seems more suitable for you.</p> <p><strong>Edit:</strong></p> <p>For PHP &lt; 5.2.x users, see <a href="https://stackoverflow.com/a/19250740/179104">this answer</a>.</p>
<p>I know this is old topic, but i think i've found a solution.</p> <p>The trick is in storing reference to each object in array with assigned key. You can then get object id by searching through that array and returning found key.</p> <pre><code>&lt;?php class objectMarker { private $storage; function add($object) { $this-&gt;storage[] = $object; } function getId($object) { foreach ($this-&gt;storage as $id =&gt; $item) { if ($item === $object) { return $id; } } return null; } } $marker = new objectMarker; $t1 = new stdClass; $t2 = new stdClass; $marker-&gt;add($t1); $marker-&gt;add($t2); echo $marker-&gt;getId($t1) . "\n"; echo $marker-&gt;getId($t2) . "\n"; unset($t1); $t1 = new stdClass; $marker-&gt;add($t1); echo $marker-&gt;getId($t1) . "\n"; $t2-&gt;x = 1; echo $marker-&gt;getId($t2) . "\n"; /* output: 0 1 2 1 */ </code></pre>
39,679
<p>I have client application that uses WCF service to insert some data to backend database. Client application is going to call service on per event basis (it can be every hour or every second).</p> <p>I'm wondering what's the best way of calling that service. </p> <p>Should I create communication channel and keep it open all the time, or should I close channel after each call and create it again?</p>
<p>The first question is whether your server needs to maintain any state about the client directly (i.e. are you doing session-like transactions?) If you are, you will need to be able to manage how the server holds the information between communications.</p> <p>My initial feeling of your question is that if there is no need to leave a connection open, then close it each time and recreate a new connection on demand. This will avoid issues where a connection can be placed into a faulted state between calls. The overhead of creating and destroying connections is minimal, and it will (probably) save you a lot of time in debugging <em>when</em> something goes wrong.</p>
<p>I would think you probably wanna implement a <a href="http://en.wikipedia.org/wiki/Keepalive" rel="nofollow noreferrer">Keep Alive pattern</a>, with a configurable duration to inform your underlying mechanism to close the connection if past beyond the Keep-alive duration with zero communication activity.</p>
30,616
<p>I'm looking to write a programming language for fun, however most of the resource I have seen are for writing a context free language, however I wish to write a language that, like python, uses indentation, which to my understanding means it can't be context free.</p>
<p>A context-free grammar is, simply, one that doesn't require a symbol table in order to correctly parse the code. A context-sensitive grammar does.</p> <p>The D programming language is an example of a context free grammar. C++ is a context sensitive one. (For example, is T*x declaring x to be pointer to T, or is it multiplying T by x ? We can only tell by looking up T in the symbol table to see if it is a type or a variable.)</p> <p>Whitespace has nothing to do with it.</p> <p>D uses a context free grammar in order to greatly simplify parsing it, and so that simple tools can parse it (such as syntax highlighting editors).</p>
<p>Just because a language uses significant indentation doesn't mean that it is inherently context-sensitive. As an example, Haskell makes use of significant indentation, and (to my knowledge) its grammar is context-free.</p> <p>An example of source requiring a context-sensitive grammar could be this snippet from Ruby:</p> <pre><code>my_essay = &lt;&lt; END_STR This is within the string END_STR &lt;&lt; self def other_method ... end end </code></pre> <p>Another example would be Scala's XML mode:</p> <pre><code>def doSomething() = { val xml = &lt;code&gt;def val &lt;tag/&gt; class&lt;/code&gt; xml } </code></pre> <p>As a general rule, context-sensitive languages are slightly harder to imagine in any precise sense and thus far less common. Even Ruby and Scala don't <em>really</em> count since their context sensitive features encompass only a minor sub-set of the language. If I were you, I would formulate my grammar as inspiration dictates and then worry about parsing methodologies at a later date. I think you'll find that whatever you come up with will be naturally context-free, or very close to it.</p> <p>As a final note, if you <em>really</em> need context-sensitive parsing tools, you might try some of the less rigidly formal techniques. Parser combinators are used in Scala's parsing. They have some annoying limitations (no lexing), but they aren't a bad tool. LL(*) tools like ANTLR also seem to be more adept at expressing such "ad hoc" parsing escapes. Don't try to use Yacc or Bison with a context-sensitive grammar, they are far to strict to express such concepts easily.</p>
9,374
<p>Is there any way to check if a drag and drop is in progress? Some method or win32 api which can be checked? I know I can set AllowDrop and use events but it doesn't work in this case. Basically i want to check, with code, if <strong>any</strong> drag&amp;drop is in progress.</p>
<p>I had a similar question which I answered myself (after some hours messing about) See - <a href="https://stackoverflow.com/questions/480156/how-do-i-tell-if-a-drag-drop-has-ended-in-winforms">How do I tell if a Drag Drop has ended in Winforms?</a>.</p> <p>Basically if you do as earwicker suggests you need to set the flag when the drag drop begins near the DoDragDrop call. You will need to unset the flag in both the DragDrop event and in the QueryContinueDrag if the QueryContinueDragEventArgs indicate a drop or a cancel.</p>
<p>Assuming it's in the context of just your own code, you could identify all the places in your code where a drag/drop happens, and set a global boolean flag to true for the duration of the operation, then back to false after it finishes.</p> <p>So the next question is, how are drag/drop operations being started in your application?</p>
48,888
<p>My HTML is all marked up, ready to make it rain CSS. The problem is that I have to go back and find out what all my id and class names are so I can get started. What I need is a tool that parses my HTML and spits out a stylesheet with all the possible elements ready to be styled (maybe even with some defaults). Does such a tool exist?</p>
<p>I have a poor man's version of this I have used in the past... this requires jquery and firebug...</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { $('*[@id]').each(function() { console.log('#' + this.id + ' {}'); }); $('*[@class]').each(function() { $.each($(this).attr('class').split(" "), function() { console.log('.' + this + ' {}'); }); }); }); &lt;/script&gt; </code></pre> <p>it gives you something like this:</p> <pre><code>#spinner {} #log {} #area {} .cards {} .dialog {} .controller {} </code></pre> <p>if you want them in "natural" page order instead...</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { $('*').each(function() { if($(this).is('[@id]')) { console.log('#' + this.id + ' {}'); } if($(this).is('[@class]')) { $.each($(this).attr('class').split(" "), function() { console.log('.' + this + ' {}'); }); } }); }); &lt;/script&gt; </code></pre> <p>I just load the page with that script in there, then cut and paste the results out of firebug... then obviously, remove the script :)</p> <p>you'll need to remove the dups manually or just toss in some simple dup checking logic with a map or array or something.. one for IDs and one for classes.</p>
<p>I've made a generator which makes the html and css for you = <a href="https://www.andy-howard.com/css-skeleton-screen-generator/" rel="nofollow noreferrer">https://www.andy-howard.com/css-skeleton-screen-generator/</a></p> <p>Not much else to say really, it utilises the :empty selector in css.</p>
3,761
<p>I have a user who gets an error from ajax calls on our site.</p> <p>The error is pasted below. </p> <p>They get the error in FF3 Windows, but not IE.</p> <p>Based on some searching it seems this issue is often caused by the client protocol squid (you'll notice at the end of the error, squid is mentioned).</p> <p>My ajax code is the same used here: <a href="http://www.w3schools.com/Ajax/ajax_browsers.asp" rel="nofollow noreferrer">http://www.w3schools.com/Ajax/ajax_browsers.asp</a></p> <p>Any ideas?</p> <pre><code>ERROR The requested URL could not be retrieved While trying to process the request: POST /library/cart/cart_ajax.php?action=refreshCartWidget&amp;qty=dontuse&amp; HTTP/1.1 Host: mydomain.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3 (.NET CLR 3.5.30729) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: identity,gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: Close Referer: http://mydomain.com/library Pragma: no-cache Cache-Control: no-cache The following error was encountered: Invalid Request Some aspect of the HTTP Request is invalid. Possible problems: Missing or unknown request method Missing URL Missing HTTP Identifier (HTTP/1.0) Request is too large Content-Length missing for POST or PUT requests Illegal character in hostname; underscores are not allowed Your cache administrator is webmaster. Generated Wed, 12 Nov 2008 09:28:58 GMT by ipwal3.osi-tech.com (squid/2.6.STABLE17) </code></pre>
<p>Save yourself some time and use <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a>. It has an abstraction for ajax, which works in all browsers and not just Internet Explorer, and maybe FF. ;-) I am assuming that the code up there is old and didn't get an update in a long while.</p> <p>A simple ajax call in jQuery is as follows:</p> <pre><code>$.post( '/the/url/to/post/to', { some: data }, function(data) { alert(data); } ); </code></pre> <p>It also helps if you understand the basics of HTTP - for example, the request methods (<code>PUT</code>, <code>POST</code>, <code>GET</code>, <code>DELETE</code>, <code>HEAD</code>) and so on. The error you pasted means that the header <code>Content-Length</code> is missing with your request and most servers (if not all) expect it to be send when you issue <code>PUT</code> or <code>POST</code> because those are assumed to be "data changing" (e.g. create, update).</p> <p>Maybe IE adds the header for you, but Firefox apparently doesn't.</p> <p>jQuery takes care of all that. ;)</p>
<p>You should sit together with your user and put the <a href="http://www.fiddlertool.com/fiddler/" rel="nofollow noreferrer">Fiddler</a> HTTP tracing tool in between. Then you can easily compare the request being sent by IE and FF3.</p> <p>This way it should become visible where the differences are and why they're causing problems.</p>
35,973
<p>What is the approved way to convert from char* to System::string and back in C++/CLI? I found a few references to marshal_to&lt;> templated functions on Google, but it appears that this feature never made the cut for Visual Studio 2005 (and isn't in Visual Studio 2008 either, AFAIK). I have also seen some code on <a href="http://blogs.msdn.com/slippman/archive/2004/06/02/147090.aspx" rel="noreferrer">Stan Lippman's blog</a>, but it's from 2004. I have also seen Marshal::StringToHGlobalAnsi(). Is there a method that is considered "best practice"?</p>
<p>System::String has a constructor that takes a char*:</p> <pre><code> using namespace system; const char* charstr = "Hello, world!"; String^ clistr = gcnew String(charstr); Console::WriteLine(clistr); </code></pre> <p>Getting a char* back is a bit harder, but not too bad:</p> <pre><code> IntPtr p = Marshal::StringToHGlobalAnsi(clistr); char *pNewCharStr = static_cast&lt;char*&gt;(p.ToPointer()); cout &lt;&lt; pNewCharStr &lt;&lt; endl; Marshal::FreeHGlobal(p); </code></pre>
<p>One additional link to a summary of possible ways:</p> <p><a href="http://support.microsoft.com/?kbid=311259" rel="nofollow">http://support.microsoft.com/?kbid=311259</a></p>
8,052
<p>I've got a small piece of code that is parsing an index value to determine a cell input into Excel. It's got me thinking...</p> <p>What's the difference between </p> <pre><code>xlsSheet.Write("C" + rowIndex.ToString(), null, title); </code></pre> <p>and</p> <pre><code>xlsSheet.Write(string.Format("C{0}", rowIndex), null, title); </code></pre> <p>Is one "better" than the other? And why?</p>
<p><strong>Before C# 6</strong></p> <p>To be honest, I think the first version is simpler - although I'd simplify it to:</p> <pre><code>xlsSheet.Write("C" + rowIndex, null, title); </code></pre> <p>I suspect other answers <em>may</em> talk about the performance hit, but to be honest it'll be minimal <em>if present at all</em> - and this concatenation version doesn't need to parse the format string.</p> <p>Format strings are great for purposes of localisation etc, but in a case like this concatenation is simpler and works just as well.</p> <p><strong>With C# 6</strong></p> <p>String interpolation makes a lot of things simpler to read in C# 6. In this case, your second code becomes:</p> <pre><code>xlsSheet.Write($"C{rowIndex}", null, title); </code></pre> <p>which is probably the best option, IMO.</p>
<p>String concatenation takes more memory compared to String.Format. So best way to concatenate strings is using String.Format or System.Text.StringBuilder Object.</p> <p>Let's take first case: "C" + rowIndex.ToString() Let's assume rowIndex is a value type so ToString() method has to Box to convert the value to String and then CLR creates memory for the new string with both values included.</p> <p>Where as string.Format expects object parameter and takes in rowIndex as an object and converts it to string internally offcourse there will be Boxing but it's intrinsic and also it's won't take up as much memory as in first case.</p> <p>For short strings it won't matter that much I guess...</p>
37,984
<p>Can you recommend a minimalistic python webserver that I can embedded in my Desktop Application.</p>
<p>How minimalistic and for what purpose? </p> <p><a href="https://docs.python.org/2/library/simplehttpserver.html" rel="nofollow noreferrer">SimpleHTTPServer</a> comes free as part of the standard Python libraries.</p> <p>If you need more features, look into <a href="http://cherrypy.org/" rel="nofollow noreferrer">CherryPy</a> or (at the top end) <a href="http://twistedmatrix.com/trac/" rel="nofollow noreferrer">Twisted</a>.</p>
<p>I made this one. <a href="http://www.blendedtechnologies.com/python-trick-really-little-http-server/220" rel="nofollow noreferrer">It just enhances Python's SimpleHTTPServer a bit to let you define custom actions depending on the request.</a></p>
38,869
<p>I have a custom class that implements <code>ICollection</code>, and this class is readonly, ie. <code>IsReadOnly</code> returns true (as opposed to using the <code>readonly</code> keyword), and all functions that would normally modify the data in the collection throw <code>InvalidOperationException</code>'s.</p> <p>Now, given such a construct, and a quick skim over the thread-safety issues when implementing <code>ICollection</code> (specifically <a href="http://msdn.microsoft.com/en-us/library/system.collections.icollection.issynchronized.aspx" rel="noreferrer"><code>ICollection.IsSynchronized</code></a> and friends), I came up with this quick and dirty solution.</p> <pre><code>bool ICollection.IsSynchronised { get{ return true; } } object ICollection.SyncRoot { get{ return new Object(); } } </code></pre> <p>Now, given the examples in MSDN, this won't cause different threads to lock properly, because they are getting different objects from <code>SyncRoot</code>. Given that this is a readonly collection though, is this an issue? Are there memory/GC issues with returning <code>new Object()</code>? Any other issues you can see with this implementation?</p>
<p>Yes this is an issue in some cases. Even though the collection is read only and cannot be changed, the objects the collection references are not read only. Thus if the clients use the SyncRoot to perform locking they will not be thread safe when modifying the objects referenced by the collection.</p> <p>I would recommend adding:</p> <pre><code>private readonly object syncRoot = new object(); </code></pre> <p>to your class. Return this as the SyncRoot and you're good to go.</p>
<p>I guess the issue would be if clients used your sync root to achieve locking of not only your collection, but something else. Supposed they cached the size of the collection - or maybe "what subset of this collection matches a predicate" - they would reasonably assume that they could use your SyncRoot to guard both your collection and their other member.</p> <p>Personally I hardly use SyncRoot at all, but I think it would be sensible to always return the same thing.</p>
25,983
<p>I've been struggling with this for quite awhile and haven't been able to find a solution. I need a user to be able to view multiple top level domains with a single login.</p> <p>My understanding is that this needs to be set in <code>environment.rb</code> and called with <code>before_dispatch</code>. This is what I've come up with:</p> <pre><code>require 'activesupport' require 'dispatcher' module ActionController class Dispatcher def set_session_domain ActionController::Base.session_options.update :session_domain =&gt; "#{@request.host}" end before_dispatch :set_session_domain end end </code></pre> <p>However, this does not seem to be working when I try and pull the values from <code>session[:session_domain]</code>.</p> <p>Any help is greatly appreciated.</p>
<p>This one is a bit tricky. Since cookies can only be assigned to (and retrieved from) the current domain ("forms.example.com", say) and parent domains (".example.com", but not ".com"), but NOT to other domains ("othersite.com"), you'll have to find yourself another solution. This has nothing to do with Rails, but with how cookies work.</p> <p>EDIT: Sessions rely on a client-specific handle, stored in a cookie, which is why sessions also don't work cross-domain.</p> <p><a href="http://www.theserverside.com/patterns/thread.tss?thread_id=31258" rel="noreferrer">This site</a> has one possible solution for creating a cross-domain cookie, and it's the cleanest way I know of, although it may have some security implications. A more complicated version would have the servers communicate directly through some secure channel.</p> <p>If you're looking for a more general-purpose single-login service, try implementing some form of <a href="http://openid.net/" rel="noreferrer">OpenID</a>.</p>
<p>Your question is not really precise enough IMHO. Do you want a single cookie for all Rails apps you have or is it within the context of a single one? If the former, you want to look at solutions using database-backed sessions or something along the line of <a href="http://code.google.com/p/rubycas-client/" rel="nofollow noreferrer">RubyCAS</a> to implement the <a href="http://www.ja-sig.org/products/cas/" rel="nofollow noreferrer">CAS</a> protocol.</p>
49,383
<p>When developing an app that will listen on a TCP/IP port, how should one go about selecting a default port? Assume that this app will be installed on many computers, and that avoiding port conflicts is desired.</p>
<p>Go <a href="http://www.iana.org/assignments/port-numbers" rel="noreferrer">here</a> and pick a port with the description <code>Unassigned</code></p>
<p>Well, you can reference some commonly used port numbers <a href="http://www.iana.org/assignments/port-numbers" rel="nofollow noreferrer">here</a> and try not to use anyone else's.</p> <p>If by "open to the public at large" you mean you're opening ports on your own systems, I'd have a chat with your system administrators about which ports they feel comfortable with doing that with.</p>
16,196
<p>Very odd problem as this is working perfectly on our old Classic ASP site. We are basically querying the database and exporting around 2200 lines of text to a Text File through Response.Write to be output to a dialog box and allows the user to save the file.</p> <p>Response.Clear() Response.ClearContent() Response.ClearHeaders()</p> <pre><code> Dim fileName As String = "TECH" &amp; test &amp; ".txt" Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", fileName)) Response.ContentType = "text/plain" Response.Write(strHeader) Dim sw As New IO.StringWriter() Dim dtRow As DataRow For Each dtRow In dt3.Rows sw.Write(dtRow.Item("RECORD") &amp; vbCrLf) Next Response.Write(sw.ToString) Response.Write(strTrailer &amp; intRecCount) Response.End() </code></pre> <p>I can either use StringWriter or simply use Response.Write(dt.Rows(i).Item("RECORD").toString</p> <p>Either way, the Export is causing a horrendous hang on our development site. My local machine causes no hang and is almost instantaneous. The recordset isn't very large, and the lines it is writing are small. </p> <p>Anyone have any idea why this would be hanging? It does EVENTUALLY allow for a save and display the file, but it's well over 3-4 minutes.</p>
<p>Attach a remote debugger and find where its hanging?</p> <p>You need to figure out if its the string writer loop, or the actual query code (which is not provided here).</p>
<p>Sounds like maybe you're overflowing the output buffer. Perhaps add a counter in there to flush every few hundred lines.</p> <p>Also, the Response object basically does most of the work for a StringWriter for you. Using the StringWriter as an intermediary is probably redundant.</p>
36,598
<p>Is there any way to create an Access / Jet database from within Linux?</p> <p>I'm trying to feed data from a linux application server (mysql backend) and have not found any tools that let me do this - it seems there should be something.</p> <p>If I can't create a database, is there a way to insert into an existing Access database file from within Linux?</p> <p>CLI tool, wrapper to SQL command file, C library, Ruby library, anything?</p> <p>Thanks.</p>
<p>There is a java library called <a href="http://jackcess.sourceforge.net/" rel="nofollow">jackcess</a> that can write to Access mdb files from any platform that can run a jvm.</p>
<ol> <li><p>If you want to create an access database (mdb file) from scratch, you'll need some Microsoft Office dll, so I think you can forget it.</p></li> <li><p>If your idea is to insert/manipulate data in an Access mdb file, you'll need a specific driver for the kind of connexion you want to use. I think your choice will be basically between ODBC and OLEDB. You can then use this connexion to modify your data (INSERT, UPDATE, DELETE), extract it (SELECT) of even manipulate your database structure through DDL instructions (CREATE, DROP, etc).</p></li> </ol>
32,003
<p>I'm trying to find a way to get the execution time of a section of code in C. I've already tried both time() and clock() from time.h, but it seems that time() returns seconds and clock() seems to give me milliseconds (or centiseconds?) I would like something more precise though. Is there a way I can grab the time with at least microsecond precision?</p> <p>This only needs to be able to compile on Linux.</p>
<p>You referred to <code>clock()</code> and <code>time()</code> - were you looking for <code>gettimeofday()</code>? That will fill in a <code>struct timeval</code>, which contains seconds and microseconds.</p> <p>Of course the actual resolution is up to the hardware.</p>
<p>If you are developing on x86 or x64 why not use the Time Stamp Counter: <a href="http://en.wikipedia.org/wiki/RDTSC" rel="nofollow noreferrer">RDTSC</a>.</p> <p>It will be more reliable then Ansi C functions like time() or clock() as RDTSC is an atomic function. Using C functions for this purpose can introduce problems as you have no guarantee that the thread they are executing in will not be switched out and as a result the value they return will not be an accurate description of the actual execution time you are trying to measure.</p> <p>With RDTSC you can better measure this. You will need to convert the tick count back into a human readable time H:M:S format which will depend on the processors clock frequency but google around and I am sure you will find examples.</p> <p>However even with RDTSC you will be including the time your code was switched out of execution, while a better solution than using time()/clock() if you need an exact measurement you will have to turn to a profiler that will instrument your code and take into account when your code is not actually executing due to context switches or whatever.</p>
20,896
<p>After the last project I've done using WebForms, I've decided to pass on using that framework in the future. It's great for getting your basic features out there...not so great when you have more complex UI logic.</p> <p>I'm looking at ASP.NET MVC, and like what I see so far. Of course the issue is that you lose the server side controls when you make that change. I've been looking for an Ajax Library that will a good replacement for the Web Forms widgets and like YUI right now.</p> <p>Not having a lot of experience in this area, I'd like to ask someone who has more knowledge. Which Ajax toolkit offers the most complete widget library? Is it possible to combine two or more toolkits to provide supplement to each other (e.g YUI has a great Grid, Scriptaculous has a great Calendar, let's use the best of both worlds)? Or are you more or less tied to one once you choose?</p> <p><strong>Thanks for the answers and great sample. ExtJS definitely looks interesting, we spent more than that on the Infragistics WebForms suite and don't get the source. Flexigrid looks pretty good as well. Thanks again!</strong></p> <p><strong>Update 2 Just found out MSFT will be shipping <a href="http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx" rel="nofollow noreferrer">jQuery with ASP.NET MVC</a></strong></p>
<p>I have written an ASP.NET MVC application and I incorporated jQuery into it. I found that jQuery helped me manipulate things that would have overcomplicated my View... such as adding alternating styles to my grids, etc...</p> <p>There are many plugins for jQuery that fill in a lot of the gaps that other libraries may have. For example, I used a great jQuery plugin called <a href="http://www.webplicity.net/flexigrid/" rel="noreferrer">Flexigrid</a> and I am very pleased with the look and features of the control. I wrote a <a href="http://webdevdotnet.blogspot.com/2008/07/flexigrid.html" rel="noreferrer">blog entry</a> about how to use c# 3.0 and LINQ to populate the grid with JSON.</p>
<p>This site (stackoverflow) uses ASP.NET MVC and jQuery, if that's any influence.</p> <p>Also, ASP.NET MVC is now shipping with jQuery</p> <p><a href="http://www.hanselman.com/blog/jQueryToShipWithASPNETMVCAndVisualStudio.aspx" rel="nofollow noreferrer">http://www.hanselman.com/blog/jQueryToShipWithASPNETMVCAndVisualStudio.aspx</a></p>
17,453
<p>Given the following idioms:</p> <p>1)</p> <p><pre><code>variable = value1 if condition variable = value2</code></pre></p> <p>2)</p> <p><pre><code>variable = value2 if not condition variable = value1</pre></code></p> <p>3)</p> <p><pre><code>if condition variable = value2 else variable = value1</pre></code></p> <p>4)</p> <p><pre><code>if not condition variable = value1 else variable = value2</pre></code></p> <p>Which do you prefer, and why?</p> <p>We assume the most common execution path to be that of <code>condition</code> being false.</p> <p>I tend to learn towards using 1), although I'm not exactly sure why I like it more.</p> <p><em>Note: The following examples may be simpler&mdash;and thus possibly more readable&mdash;but not all languages provide such syntax, and they are not suitable for extending the variable assignment to include more than one statement in the future.</em></p> <pre><code>variable = condition ? value2 : value1 ... variable = value2 if condition else value1</code></pre>
<p>In theory, I prefer #3 as it avoids having to assign a value to the variable twice. In the real world though I use any of the four above that would be more readable or would express more clearly my intention.</p>
<p><code>switch</code> statement also works. If it's simple and more than 2 or 3 options, that's what I use.</p>
18,389
<p>I have a HTML application, partially HTML, partially VBscript, disguised as a form. What it does is it opens a few local files, runs a DOS box containing GAWK and presents a text file as its result. I wish to expand upon it by letting it create a bitmap image with the results in a stacked bar graph, for instance as a .BMP file. But I'm stumped. I haven't the faintest idea where to start.</p>
<p>Is javascript an option? That would be a lot easier than creating an image file. </p> <p>I have used this jquery plugin <a href="http://code.google.com/p/flot/" rel="nofollow noreferrer">http://code.google.com/p/flot/</a> a few times and works well. </p> <p>I have not used VBScript for a few years now, think you would probably need to use an active-x object of some kind to generate an image file, but I could be wrong there.</p>
<p>Graphics are beyond the capabilities of VBScript alone. You can try if you find an ActiveX/COM component that can do it for you. Looking into Google, my guess is that most of them come as dumbed-down trial versions of quite expensive commercial products. Maybe someone else here knows one that is for free.</p> <p>As an alternative route, you could set up a web service somewhere that does the image processing (for example PHP/gdlib) using URL parameters. Then you would just have to link to the image in your HTA with an <code>&lt;img&gt;</code> tag like you normally would.</p>
41,841
<p>This concept is a new one for me -- I first came across it at the <a href="http://developer.yahoo.com/yui/articles/hosting/#configure" rel="nofollow noreferrer">YUI dependency configurator</a>. Basically, instead of having multiple requests for many files, the files are chained into one http request to cut down on page load time.</p> <p>Anyone know how to implement this on a LAMP stack? (I saw a similar question was asked already, but it <a href="https://stackoverflow.com/questions/47937/combining-and-caching-multiple-javascript-files-in-aspnet">seems to be ASP specific</a>.</p> <p>Thanks!</p> <p>Update: Both answers are helpful...(my rep isn't high enough to comment yet so I'm adding some parting thoughts here). I also came <a href="http://www.artzstudio.com/2008/08/using-modconcat-to-speed-up-render-start/" rel="nofollow noreferrer">across another blog post</a> with PHP-specific examples that might be useful. David's build answer, though, is making me consider a different approach. Thanks, David!</p>
<p>There are various ways, the two most obvious would be:</p> <ol> <li>Build a tool like YUI which builds a bespoke, unique version based on the components you ticked as required so that you can still serve the file as static. MooTools and jQuery UI all provide package-builders like this when you download their package to give you the most streamlined and effecient library possible. I'm sure a generic all purpose tool exists out there.</li> <li>Create a simple Perl/PHP/Python/Ruby script that serves a bunch of JavaScript files based on the request. So "onerequest.js?load=ui&amp;load=effects" would go to a PHP script that loads in the files and serves them with the correct content-type. There are many examples of this but personally I'm not a fan. </li> </ol> <p>I prefer not to serve static files through any sort of script, but I also like to develop my code with 10 or so seperate small class files without the cost of 10 HTTP requests. So I came up with a custom build process that combines all the most common classes and functions and then minifies them into a single file like project.min.js and have a condition in all my views/templates that includes this file on production. </p> <p>Edit - The "custom build process" is actually an extremely simple perl script. It reads in each of the files that I've passed as arguments and writes them to a new file, optionally passing the entire thing through <a href="http://www.crockford.com/javascript/jsmin.html" rel="noreferrer">JSMIN</a> (available in all your favourite languages) automatically. </p> <p>At the command like it looks like:</p> <pre><code>perl build-project-master.pl core.js class1.js etc.js /path/to/live/js/file.js </code></pre>
<p>Capistrano is a fairly popular Ruby-based web deployment tool. If you're considering it or already using it, there's a great gem that will figure out CSS and Javascript dependencies, merge, and minify the files.</p> <p><code>gem install juicer</code></p> <p>From the <a href="https://github.com/cjohansen/juicer" rel="nofollow">Juicer GitHub page</a>, it can figure out which files depend on each other and merge them together, reducing the number of http requests per page view, thus improving performance.</p>
12,740
<p>This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity. </p> <pre><code>array( 0 =&gt; '-- SELECT --', 1 =&gt; 'Afghanistan', 2 =&gt; 'Albania', 3 =&gt; 'Algeria', 4 =&gt; 'American Samoa', 5 =&gt; 'Andorra',) </code></pre> <p>The id's need to stay intact. So making them -1 or -2 will unfortunately not work.</p>
<p>What I usually do in these situations is to add a separate field called DisplayOrder or something similar. Everything defaults to, say, 1... You then sort by DisplayOrder and then the Name. If you want something higher or lower on the list, you can tweak the display order accordingly while keeping your normal IDs as-is.</p> <p>-- Kevin Fairchild</p>
<p>You can not change the order of elements within the same array by "moving" an item around. What you can do it to build a new array that first has your favourite items and then adds anything else from the original countries array at the end:</p> <pre><code>$countries = array( 0 =&gt; '-- SELECT --', 1 =&gt; 'Afghanistan', 2 =&gt; 'Albania', 3 =&gt; 'Algeria', 4 =&gt; 'American Samoa', 5 =&gt; 'Andorra', 22 =&gt; 'Canada', 44 =&gt; 'United States',); # tell what should be upfront (by id) $favourites = array(0, 44, 22); # add favourites at first $ordered = array(); foreach($favourites as $id) { $ordered[$id] = $countries[$id]; } # add everything else $ordered += array_diff_assoc($countries, $ordered); # result print_r($ordered); </code></pre> <p><a href="http://codepad.org/YQSfToYj" rel="nofollow">Demo</a></p>
6,600
<p>I'm aware that I can grab the CPU identifier and the volume serial number for a physical drive by querying WMI, but WMI usually takes its sweet time. What other speedier options, if any, are available to retrieve this information? Are there Win32 APIs that would accomplish this?</p> <p><strong>Edit:</strong> Allow me to clarify. By CPU identifier, I'm referring to the same value one gets by querying the following WMI instance properties: </p> <ul> <li>Win32_Processor::ProcessorId</li> <li>Win32_LogicalDisk::VolumeSerialNumber</li> </ul>
<p>Just keep in mind that ID of the CPU is not always available. </p> <p>By the way, what are you trying to accomplish? If you want to generate a unique key for a computer instance, check the <a href="http://www.codeproject.com/KB/cs/GenerateUniqueKey.aspx" rel="nofollow noreferrer">Generating Unique Key (Finger Print) for a Computer for Licensing Purposes</a> post by Sowkot Osman at Codeproject; it can give you some hints (also read comments).</p>
<p>I like <a href="http://msdn.microsoft.com/en-us/library/ms724381(VS.85).aspx" rel="nofollow noreferrer">GetSystemInfo</a> but that doesn't cover physical drives..</p>
30,850
<p>I have a large Java app that is split up into multiple projects. Each project has its own folder in a Subversion repository like so:</p> <p>AccountingCore</p> <ul> <li>trunk</li> <li>branches</li> <li>tags</li> </ul> <p>Common</p> <ul> <li>trunk</li> <li>branches</li> <li>tags</li> </ul> <p>WebCommon</p> <ul> <li>trunk</li> <li>branches</li> <li>tags</li> </ul> <p>etc...</p> <p>I want to start using <strong>git-svn</strong> locally instead of subversion. </p> <p>This may be a stupid question, but is there a way to checkout <em>all the projects</em> in the repository at once (including branches and all) instead checking out each project individually?</p> <p>Thanks, Tony</p>
<p>If you have a shell, you could enter</p> <p><code>for DIR in AccountingCore Common WebCommon; do mkdir $DIR; cd $DIR; git init; git svn init -s svn://host/path/$DIR; git svn fetch; cd ..; done</code></p> <p>That is, if I made no mistakes.</p>
<p>Yes. just checkout at the root path. If your repo is hosted here:</p> <p>svn://host/path/AccountingCore svn://host/path/Common svn://host/path/WebCommon</p> <p>Then do your <code>git svn</code> command on <code>svn://host/path</code>.</p>
35,257
<p>How is it done? What steps do I need to take and what pitfalls and gotchas are there to consider?</p>
<p>I've gotten this to work, thanks to some inside help over at the <a href="https://devforums.apple.com/" rel="noreferrer">Apple Devforums</a>, you should sign up if you're a dedicated IPhone developer.</p> <p>First thing's first, it's <em>__asm__()</em>, not plain <em>asm()</em>.</p> <p>Secondly, by default, XCode generates a compilation target that compiles inline assembly against the ARM Thumb instruction set, so <em>usat</em> wasn't recognized as a proper instruction. To fix this, do "Get Info" on the Target. Scroll down to the section "GCC 4.0 - Code Generation" and uncheck "Compile for Thumb". Then this following snippet will compile just fine if you set the Active SDK to "Device"</p> <pre><code>inline int asm_saturate_to_255 (int a) { int y; __asm__("usat %0, #8, %1\n\t" : "=r"(y) : "r"(a)); return y; } </code></pre> <p>Naturally, now it won't work with the IPhone Simulator. But <em>TargetConditionals.h</em> has defines you can #ifdef against. Namely <em>TARGET_OS_IPHONE</em> and <em>TARGET_IPHONE_SIMULATOR</em>.</p>
<h1>Background</h1> <ul> <li>Now is 2021 year -&gt; other answer seems is too old?</li> <li>the most iOS device(iPhone etc.) is ARM 64bit: <code>arm64</code></li> </ul> <h1>Inline assembly on the iPhone</h1> <h2>asm keyword</h2> <ul> <li>GNU/GCC compiler <ul> <li>standard C (compile flag: <code>-ansi</code> / <code>-std</code>): use <code>__asm__</code></li> <li>GNU extensio: use <code>asm</code></li> </ul> </li> <li>ARM compiler: use <code>__asm</code></li> </ul> <h2>asm syntax</h2> <p>AFAIK, there many asm syntax</p> <ul> <li>asm syntax <ul> <li><code>AT&amp;T syntax</code> ~= <code>GNU syntax</code> ~= <code>UNIX syntax</code></li> <li><code>Intel syntax</code></li> <li><code>ARM syntax</code></li> </ul> </li> </ul> <p>here only focus on most common used <code>GNU/GCC</code> syntax</p> <h3><code>GNU/UNIX syntax</code></h3> <h4>Basic Asm</h4> <pre><code>asm(&quot;assembly code&quot;); __asm__(&quot;assembly code&quot;); </code></pre> <h4>Extended Asm</h4> <pre><code>asm asm-qualifiers ( AssemblerTemplate : OutputOperands [ : InputOperands [ : Clobbers ] ]) </code></pre> <hr /> <h1>My Example code</h1> <ul> <li>environment <ul> <li>dev <ul> <li>macOS <ul> <li>IDE: XCode <ul> <li>compiler: <code>clang</code></li> </ul> </li> </ul> </li> </ul> </li> <li>running <ul> <li>iOS - iPhone <ul> <li>hardware arch: <code>ARM64</code></li> </ul> </li> </ul> </li> </ul> </li> </ul> <h2>inline asm to call svc 0x80 for ARM64 using Extended Asm</h2> <ul> <li>inline asm inside ObjC code</li> </ul> <pre class="lang-c prettyprint-override"><code>// inline asm code inside iOS ObjC code __attribute__((always_inline)) long svc_0x80_syscall(int syscall_number, const char * pathname, struct stat * stat_info) { register const char * x0_pathname asm (&quot;x0&quot;) = pathname; // first arg register struct stat * x1_stat_info asm (&quot;x1&quot;) = stat_info; // second arg register int x16_syscall_number asm (&quot;x16&quot;) = syscall_number; // special syscall number store to x16 register int x4_ret asm(&quot;x4&quot;) = -1; // store result __asm__ volatile( &quot;svc #0x80\n&quot; &quot;mov x4, x0\n&quot; : &quot;=r&quot;(x4_ret) : &quot;r&quot;(x0_pathname), &quot;r&quot;(x1_stat_info), &quot;r&quot;(x16_syscall_number) // : &quot;x0&quot;, &quot;x1&quot;, &quot;x4&quot;, &quot;x16&quot; ); return x4_ret; } </code></pre> <ul> <li>call inline asm</li> </ul> <pre class="lang-c prettyprint-override"><code>// normal ObjC code #import &lt;sys/syscall.h&gt; ... int openResult = -1; struct stat stat_info; const char * filePathStr = [filePath UTF8String]; ... // call inline asm function openResult = svc_0x80_syscall(SYS_stat64, filePathStr, &amp;stat_info); </code></pre> <h1>Doc</h1> <ul> <li><a href="https://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html#s6" rel="nofollow noreferrer">GCC-Inline-Assembly-HOWTO (ibiblio.org)</a></li> <li><a href="https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html" rel="nofollow noreferrer">Extended Asm (Using the GNU Compiler Collection (GCC))</a></li> <li><a href="https://developer.arm.com/documentation/ihi0055/latest" rel="nofollow noreferrer">Procedure Call Standard for the Arm® 64-bit Architecture</a></li> <li><a href="http://www.ethernut.de/en/documents/arm-inline-asm.html" rel="nofollow noreferrer">ARM GCC Inline Assembler Cookbook</a></li> <li><a href="https://gcc.gnu.org/wiki/ConvertBasicAsmToExtended" rel="nofollow noreferrer">ConvertBasicAsmToExtended - GCC Wiki</a></li> <li><a href="https://stackoverflow.com/questions/32985409/fork-implementation-by-using-svc-call/32990553#32990553">ios - fork() implementation by using svc call - Stack Overflow</a></li> <li><a href="https://stackoverflow.com/questions/37358451/arm-inline-asm-exit-system-call-with-value-read-from-memory/37363860#37363860">linux - ARM inline asm: exit system call with value read from memory - Stack Overflow</a></li> </ul>
29,444
<p>I am trying to add a "title" element but am getting a NO_MODIFICATION_ALLOWED_ERR error...</p> <pre><code>private static void saveDoc(String f) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(f); // create DOMSource for source XML document DOMSource xmlSource = new DOMSource(doc); Node nextNode = xmlSource.getNode().getFirstChild(); while (nextNode != null) { System.out.print("\n node name: " + nextNode.getNodeName() + "\n"); if (nextNode.getNodeName().equals("map")) { nextNode.appendChild(doc.createElement("title")); </code></pre> <p><strong>the line above is throwing error:</strong></p> <blockquote> <p>Exception in thread "main" org.w3c.dom.DOMException: <code>NO_MODIFICATION_ALLOWED_ERR</code>: An attempt is made to modify an object where modifications are not allowed. at com.sun.org.apache.xerces.internal.dom.ParentNode.internalInsertBefore(Unknown Source) at com.sun.org.apache.xerces.internal.dom.ParentNode.insertBefore(Unknown Source) at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(Unknown Source) at myProject.Main.saveDoc(Main.java:171) at myProject.Main.main(Main.java:48)</p> </blockquote> <pre><code> break; } nextNode = nextNode.getNextSibling(); } } </code></pre> <p>My xml file looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?dctm xml_app="LOPackage"?&gt; &lt;!DOCTYPE map PUBLIC "-//OASIS//DTD DITA Map//EN" "file:C:/Documents%20and%20Settings/joe/Desktop//LOPackage/map.dtd"&gt; &lt;map xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" class="- map/map " ditaarch:DITAArchVersion="1.1" domains="(map mapgroup-d) (topic indexing-d)"&gt; &lt;topicref class="- map/topicref " href="dctm://ai/0501869e80002504?DMS_OBJECT_SPEC=RELATION_ID" type="Le"/&gt; &lt;topicref class="- map/topicref " href="dctm://ai/0501869e80002505?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/&gt; &lt;topicref class="- map/topicref " href="dctm://ai/0501869e80002506?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/&gt; &lt;/map&gt; </code></pre>
<p>Not sure if that's the reason, but check if your DOM implementation validates all the changes to the DOM. Because in you code,</p> <pre><code>nextNode.appendChild(doc.createTextNode("title")); </code></pre> <p>will attempt to create a text node as the child of <code>map</code> element and DITA Map doesn't allow that. Instead, try</p> <pre><code>Element title = doc.createElement("title"); title.appendChild(doc.createTextNode("title content")) nextNode.appendChild(title); </code></pre>
<p>For some reason, the parent node seems to be read-only. Clone the document by using:</p> <pre><code>Document newDoc = doc.cloneNode(true); </code></pre> <p>Set it to read-write by:</p> <pre><code>newDoc.setReadOnly(false,true); // ^^^^ also sets children </code></pre> <p>Then do your stuff. I would return the new document after saving it though.</p>
32,505
<p>How do large server farms handle gracefully shutting down all or part of the farm? I'm thinking of planed and unplanned cases like:</p> <ul> <li>"We need to shutdown Rack 42" </li> <li>"We need to do work on the power feeds to the whole block" </li> <li>"Blackout! UPS's running out of Juice! Aahh!"</li> <li>"AC is down, air temp is 125F and climbing"</li> </ul> <p>The issues I'm interested in are how people handle sequencing, and kicking the whole thing off. Also it occurs to me that this could easily get mixed with bringing up and down services and with the software up grade system.</p> <p>(At this point I'm more asking out of curiosity than anything.)</p>
<p>Computers can use a lot more power coming back online than they do running, since they have to get all of the platters and fans spinning, typically have heavy CPU activity starting all of the applications, and so on. Most shops will have a set sequence that staggers the startups, so they don't max out the circuit and have to start all over again. This is also important if you have a bunch of applications that expect to talk to a database, or a bunch of web servers that need to talk to the app servers. You usually start from the bottom up, and stagger the startups by 30 seconds to a minute, depending on how many boxes are on your circuit.</p>
<p>One method is to mirror the live machines on temporary hot-swaps and, assuming access is via network, cut over by reconfiguring the router to divert traffic to the mirrors. This process can be automated for unplanned outages.</p> <p>For planned maintenance, some simply notify their users that the system will be unavailable during a certain window.</p> <p>Redundant power supplies and gas-powered generators handle most power-related problems, again with automated failover.</p>
36,262
<p>Say I have a class named Frog, it looks like:</p> <pre><code>public class Frog { public int Location { get; set; } public int JumpCount { get; set; } public void OnJump() { JumpCount++; } } </code></pre> <p>I need help with 2 things:</p> <ol> <li>I want to create an event named Jump in the class definition.</li> <li>I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps.</li> </ol>
<pre><code>public event EventHandler Jump; public void OnJump() { EventHandler handler = Jump; if (null != handler) handler(this, EventArgs.Empty); } </code></pre> <p>then</p> <pre><code>Frog frog = new Frog(); frog.Jump += new EventHandler(yourMethod); private void yourMethod(object s, EventArgs e) { Console.WriteLine("Frog has Jumped!"); } </code></pre>
<p>Here is a sample of how to use a normal EventHandler, or a custom delegate. Note that <code>?.</code> is used instead of <code>.</code> to insure that if the event is null, it will fail cleanly (return null)</p> <pre><code>public delegate void MyAwesomeEventHandler(int rawr); public event MyAwesomeEventHandler AwesomeJump; public event EventHandler Jump; public void OnJump() { AwesomeJump?.Invoke(42); Jump?.Invoke(this, EventArgs.Empty); } </code></pre> <p>Note that the event itself is only null if there are no subscribers, and that once invoked, the event is thread safe. So you can also assign a default empty handler to insure the event is not null. Note that this is technically vulnerable to someone else wiping out all of the events (using GetInvocationList), so use with caution.</p> <pre><code>public event EventHandler Jump = delegate { }; public void OnJump() { Jump(this, EventArgs.Empty); } </code></pre>
11,068
<p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack" rel="noreferrer">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
<p>I'm surprised there isn't a single mention of lxml. It's blazingly fast and will work in any environment that allows CPython libraries.</p> <p>Here's how <a href="http://codespeak.net/lxml/xpathxslt.html" rel="noreferrer">you can parse HTML via XPATH using lxml</a>.</p> <pre><code>&gt;&gt;&gt; from lxml import etree &gt;&gt;&gt; doc = '&lt;foo&gt;&lt;bar&gt;&lt;/bar&gt;&lt;/foo&gt;' &gt;&gt;&gt; tree = etree.HTML(doc) &gt;&gt;&gt; r = tree.xpath('/foo/bar') &gt;&gt;&gt; len(r) 1 &gt;&gt;&gt; r[0].tag 'bar' &gt;&gt;&gt; r = tree.xpath('bar') &gt;&gt;&gt; r[0].tag 'bar' </code></pre>
<p>There is a free C implementation for XML called libxml2 which has some api bits for XPath which I have used with great success which you can specify HTML as the document being loaded. This had worked for me for some less than perfect HTML documents.. </p> <p>For the most part, XPath is most useful when the inbound HTML is properly coded and can be read 'like an xml document'. You may want to consider using a utility that is specific to this purpose for cleaning up HTML documents. Here is one example: <a href="http://tidy.sourceforge.net/" rel="nofollow noreferrer">http://tidy.sourceforge.net/</a></p> <p>As far as these XPath tools go- you will likely find that most implementations are actually based on pre-existing C or C++ libraries such as libxml2.</p>
36,327
<p>I'm looking into using <a href="http://lucene.apache.org/java/docs/" rel="nofollow noreferrer">Lucene</a> and/or <a href="http://lucene.apache.org/solr/" rel="nofollow noreferrer">Solr</a> to provide search in an RDBMS-powered web application. Unfortunately for me, all the documentation I've skimmed deals with how to get the data out of the index; I'm more concerned with how to build a useful index. Are there any "best practices" for doing this?</p>
<p>Will multiple applications be writing to the database? If so, it's a bit tricky; you have to have some mechanism to identify new records to feed to the Lucene indexer.</p> <p>Another point to consider is do you want one index that covers all of your tables, or one index per table. In general, I recommend one index, with a field in that index to indicate which table the record came from.</p> <p><a href="http://www.hibernate.org/hib_docs/search/reference/en/html_single/" rel="nofollow noreferrer">Hibernate</a> has support for full text search, if you want to search persistent objects rather than unstructured documents.</p> <p>There's an OpenSymphony project called <a href="http://www.opensymphony.com/compass" rel="nofollow noreferrer">Compass</a> of which you should be aware. I have stayed away from it myself, primarily because it seems to be <strong>way</strong> more complicated than search needs to be. Also, as I can tell from the documentation (I confess I haven't found the time necessary to read it all), it stores Lucene segments as blobs in the database. If you're familiar with the Lucene architecture, Compass implements a Lucene Directory on top of the database. I think this is the wrong approach. I would leverage the database's built-in support for indexing and implement a Lucene IndexReader instead. The same criticism applies to distributed cache implementations, etc.</p>
<p>As introduction:</p> <p>Brian McCallister wrote a nice blog post: <a href="http://kasparov.skife.org/blog/2004/09/11/" rel="nofollow noreferrer"><strong>Using Lucene with OJB</strong></a>. </p>
37,896
<p>I need to recover form an error case where a file gets left in a locked state. How can I in c# tell this file to reset it's locks? I need to add to this the file is opened by a 3rd party dll and I don't actually have access to the file handle.</p>
<p>Locking a file is the responsibility of the Operating System (on behalf of the program that opens it). If a file is left in a locked state, its really up to the OS to unlock. This typically happens automatically when the process that opened the file exits.</p> <p>There is, however, a really cool utility that I came across that will help. It's called <a href="http://www.emptyloop.com/unlocker/" rel="nofollow noreferrer">Unlocker</a>.</p>
<p>You have to close the file using .Close(). You need to make sure you still have a way of accessing the file object.</p> <p>You usually can avoid this error by writing a try{} ... finally {} construct after the code that does your file I/O. In the finally {} block, you'd call the Close method of your file object, preventing this condition. You can also use a using {} block when you create your files, and this will also take care of this problem.</p>
28,255
<p>For a in-house hardware monitoring utility, I need to use gauges and charts to help visualize various metrics. Is there any good open source or free charting and gauge library available for .NET? I am not interested in purchasing any components (which excludes components such as Dundas Charts &amp; Graph, which I know would do the job, but would not fit in our budget).</p> <p><strong>Edit:</strong> I also know about Google Charts API. The actual application needs to work without an internet connection, so it is out of the question in this particular case.</p>
<p>I know this isn't open source, but it's worth noting that Microsoft just released a free charting pack for ASP.NET and WinForms. More details <a href="http://blogs.msdn.com/sqlrsteamblog/archive/2008/10/25/microsoft-chart-controls-for-net-framework-35.aspx" rel="nofollow noreferrer">here</a>.</p>
<p>I'm having a look at NPlot, but it looks a bit impenetrable at first glance.</p>
29,908
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2246772/whats-the-difference-between-not-exists-vs-not-in-vs-left-join-where-is-null">What&#39;s the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?</a> </p> </blockquote> <p>I need to wite a query that will retrieve the records from Table A , provided that the key in Table A does not exist in Table B.</p> <p>Any help will be appreciated.</p> <p>Thanks</p>
<pre><code>SELECT * FROM A WHERE ID NOT IN (SELECT ID FROM B) </code></pre>
<p>Assuming: TableA's Id = Id TableB's Id = Id</p> <pre><code>select * from TableA ta where ta.Id not in (select Id from TableB) </code></pre>
35,513
<p>I got a core that looks very different from the ones I usually get - most of the threads are in __kernel_vsyscall() :</p> <pre><code> 9 process 11334 0xffffe410 in __kernel_vsyscall () 8 process 11453 0xffffe410 in __kernel_vsyscall () 7 process 11454 0xffffe410 in __kernel_vsyscall () 6 process 11455 0xffffe410 in __kernel_vsyscall () 5 process 11474 0xffffe410 in __kernel_vsyscall () 4 process 11475 0xffffe410 in __kernel_vsyscall () 3 process 11476 0xffffe410 in __kernel_vsyscall () 2 process 11477 0xffffe410 in __kernel_vsyscall () 1 process 11323 0x08220782 in MyClass::myfunc () </code></pre> <p>What does that mean?</p> <p>EDIT: In particular, I usually see a lot of threads in "pthread_cond_wait" and "___newselect_nocancel" and now those are on the second frame in each thread - why is this core different?</p>
<p><code>__kernel_vsyscal</code> is the method used by linux-gate.so (a part of the Linux kernel) to make a system call using the fastest available method, preferably the <code>sysenter</code> instruction. The thing is properly explained by <a href="http://www.trilithium.com/johan/2005/08/linux-gate" rel="noreferrer">Johan Petersson</a>.</p>
<p>As Adam said, the main reason is performance. See this link for some old numbers <a href="http://lkml.org/lkml/2002/12/9/13" rel="nofollow noreferrer">http://lkml.org/lkml/2002/12/9/13</a>.</p> <p>If you have a vDSO enabled kernel, you're not using interrupts to run syscalls, as Stefan said, actually was because interrupts was getting slower that the whole vDSO thing was added to the kernel.</p>
44,861
<p>I have found a video about Invisalign. I saw a 3D printer in the video but I did not understand its type. Can you help me? Do you share a brief piece of information about its type?</p> <p>Below is the video on YouTube.</p> <p><div class="youtube-embed"><div> <iframe width="640px" height="395px" src="https://www.youtube.com/embed/bKsGNrEKx9M?start=0"></iframe> </div></div></p>
<p>In the video, there is this still from <a href="https://youtu.be/bKsGNrEKx9M?t=32" rel="nofollow noreferrer">0:32</a>:</p> <p><a href="https://youtu.be/bKsGNrEKx9M?t=32" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jf2F8.png" alt="enter image description here" /></a></p> <p>The labeling is iPro 8000, which is a <a href="http://infocenter.3dsystems.com/product-library/sla/ipro-8000-9000" rel="nofollow noreferrer">3dSystems resin printer using SLA technology.</a></p>
<p>If you look at the video at 37 seconds, it appears to be SLA or DLP.</p> <p>Further reading: <a href="https://www.solidprint3d.co.uk/wp-content/uploads/2019/04/SLA_vs_DLP.pdf" rel="nofollow noreferrer">https://www.solidprint3d.co.uk/wp-content/uploads/2019/04/SLA_vs_DLP.pdf</a></p>
1,876
<p>Wikipedia says SQL Server Express Edition is limited to "one processor, 1 GB memory and 4 GB database files". Does anyone have practical experience with how well this scales?</p>
<p>It's a regular sql server, it just has a limit. SharePoint by default uses the sql server express if that gives you any idea. We have our entire office (80+) people running on that instance.</p>
<p>It really comes down to the nature of your database and application. What kind of application(s) are hitting SQL Server? In my experience, it only handles 5-10 users with a heavy read/write application.</p>
5,610
<p>I want to sprintf() an unsigned long long value in visual C++ 6.0 (plain C).</p> <pre><code>char buf[1000]; //bad coding unsigned __int64 l = 12345678; char t1[6] = "test1"; char t2[6] = "test2"; sprintf(buf, "%lli, %s, %s", l, t1, t2); </code></pre> <p>gives the result</p> <pre><code>12345678, (null), test1 </code></pre> <p>(watch that <code>test2</code> is not printed)</p> <p>and <code>l = 123456789012345</code> it gives an exception handle</p> <p>any suggestions?</p>
<p>To print an <code>unsigned __int64</code> value in Visual C++ 6.0 you should use <code>%I64u</code>, not <code>%lli</code> (refer to <a href="http://msdn.microsoft.com/en-us/library/aa272936%28VS.60%29.aspx" rel="nofollow noreferrer">this page</a> on MSDN). <code>%lli</code> is only supported in Visual Studio 2005 and later versions. So, your code should be:</p> <pre><code>sprintf(buf, "%I64u, %s, %s", l, t1, t2); </code></pre>
<p>Apparently, you did not assign <code>additionaltext</code> to the necessary <code>char *</code> (string). Note that the <code>long int</code> was processed, the comma was copied and only the <code>%s</code> generated <code>(null)</code>.</p>
24,488
<p>If you create a simple "Hello World" VSTO2SE add-in targeting Microsoft Office Excel 2003, it takes 15 seconds to load on a cold startup. During that time, Excel is completely unresponsive. </p> <p>The cold-startup time is always poor in Excel 2003. I have seen one test machine where the startup time is instant in Excel 2007, but all my other test machines take 15 seconds to initialize. (test environment - windows xp pro + VSTO2SE runtime + XP SP3)</p> <p>How can this performance be improved?</p> <p>Things I've already tried with no success:</p> <ol> <li><p>Disasble CRL (certificate revoke list) checking - this doesn't seem to help, plus I can't expect users to do this.</p></li> <li><p>Use NGEN to create native assemblies.<br> a) It seems that Office 2003 never uses the native assemblies. b) My office 2007 test client that starts fast, does so even with IL assemblies. c) Even if I NGEN my entire depencency tree, there are still VSTO dependencies that may not have native images.</p></li> <li><p>Delay load the add-in - this is the workaround "stock response" i get from Microsoft. The thing is, my add-in is launched from a menu item - how can I delay load the add-in and still get my menus? I could use a VB6 add-in to draw the menus and forward the calls via interop, but then why would I even write a VSTO add-in in the first place?</p></li> </ol> <p>Edit - Yes, that is the only line on the "connection" event in the add-in. (actually messagebox).. It takes a full 15 seconds before the message box appears. – J Davis</p>
<p>You're going to take a hit on cold start up because it has to load all of the assemblies for the first time.</p> <p>If warm start up are significantly faster, then the only real options you have are</p> <p>1) Have a separate program load when windows starts and load all of the assemblies for you r addin in the background.</p> <p>2)Try to reduce the number of assemblies you are using. Granted, you shouldn't be using much with Hello World.</p> <p>3) Preload everything when Excel starts. This will hurt Excel start up time, but will make your menu selection speedier. You could also preload everything in the background, to help this.</p>
<p>Have you verified what the actual holdup is? If you put a Debug.Write() statement as the first line in your VSTO addin, does it take 15 seconds to show up in the debug window?</p> <p>We're working with VSTO and whenever we have holdups, it's usually something other than the actual runtime that's causing the slowdown. We've solved this problem by spinning off background threads to do the slow things while not blocking the main thread, which holds up Excel startup.</p> <p>ps. We're also not huge fans of the VSTO technology. We're 100% bought into the vision, but the implementation leaves alot to be desired.</p>
30,870
<p>What is Windows' best I/O event notification facility? </p> <p>By best I mean something that ...</p> <ol> <li>doesn't have a limit on number of input file descriptors</li> <li>works on all file descriptors (disk files, sockets, ...)</li> <li>provides various notification modes (edge triggered, limit triggered)</li> </ol>
<p>In Windows, async operations are done by file operation, not by descriptor. There are several ways to wait on file operations to complete asynchronously.</p> <p>For example, if you want to know when data is available on a network socket, issue an async read request on the socket and when it completes, the data was available and was retrieved.</p> <p>In Win32, async operations use the <a href="http://msdn.microsoft.com/en-us/library/ms684342(VS.85).aspx" rel="noreferrer"><code>OVERLAPPED</code></a> structure to contain state about an outstanding IO operation.</p> <ol> <li>Associate the files with an <a href="http://msdn.microsoft.com/en-us/library/aa365198(VS.85).aspx" rel="noreferrer">IO Completion Port</a> and dispatch async IO requests. When an operation completes, it will put a completion message on the queue which your worker thread(s) can wait on and retrieve as they arrive. You can also put user defined messages into the queue. There is no limit to how many files or queued messages can be used with a completion port</li> <li>Dispatch each IO operation with an event. The event associated with an operation will become signaled (satisfy a wait) when it completes. Use <a href="http://msdn.microsoft.com/en-us/library/ms687025(VS.85).aspx" rel="noreferrer"><code>WaitForMultipleObjects</code></a> to wait on all the events at once. This has the disadvantage of only being able to wait on <code>MAXIMUM_WAIT_OBJECTS</code> objects at once (64). You can also wait on other types of events at the same time (process/thread termination, mutexes, events, semaphores)</li> <li>Use a <a href="http://msdn.microsoft.com/en-us/library/ms686760(VS.85).aspx" rel="noreferrer">thread pool</a>. The thread pool can take an unlimited number of objects and file operations to wait on and execute a <a href="http://msdn.microsoft.com/en-us/library/ms684124(VS.85).aspx" rel="noreferrer">user defined function</a> upon completion each.</li> <li>Use <code><a href="http://msdn.microsoft.com/en-us/library/aa365468(VS.85).aspx" rel="noreferrer">ReadFileEx</a></code> and <a href="http://msdn.microsoft.com/en-us/library/aa365748(VS.85).aspx" rel="noreferrer"><code>WriteFileEx</code></a> to queue <a href="http://msdn.microsoft.com/en-us/library/ms681951(VS.85).aspx" rel="noreferrer">Asynchronous Procedure Calls</a> (APCs) to the calling thread and <a href="http://msdn.microsoft.com/en-us/library/ms686307(VS.85).aspx" rel="noreferrer"><code>SleepEx</code></a> (or <code>WaitFor{Single|Multiple}ObjectsEx</code>) with <code>Alertable TRUE</code> to receive a notification message for each operation when it completes. This method is similar to an IO completion port, but only works for one thread. </ol> <p>The Windows NT kernel makes no distinction between socket, disk file, pipe, etc. file operations internally: all of these options will work with all the file types.</p>
<p>select() function is POSIX and usable on windows including "winsock.h" or "winsock2.h". </p>
9,266
<p>I have a couple search forms, 1 with ~50 fields and the other with ~100. Typically, as the HTML spec says, I do searches using the GET method as no data is changed. I haven't run into this problem yet, but I'm wondering if I will run out of URL space soon?</p> <p>The limit of <a href="http://support.microsoft.com/kb/208427" rel="noreferrer">Internet Explorer</a> is 2083 characters. Other browsers, have a <a href="http://www.boutell.com/newfaq/misc/urllength.html" rel="noreferrer">much higher limit</a>. I'm running Apache, so the limit there is around 4000 characters, which IIS is 16384 characters.</p> <p>At 100 fields, say average field name length of 10 characters, that's already 5000 characters...amazing on the 100 field form, I haven't had any errors yet. (25% of the fields are multiple selects, so the field length is much longer.)</p> <p>So, I'm wondering what my options are. (Shortening the forms is not an option.) Here my ideas:</p> <ul> <li>Use POST. I don't like this as much because at the moment users can bookmark their searches and perform them again later--a really dang nice feature.</li> <li>Have JavaScript loop through the form to determine which fields are different than default, populate another form and submit that one. The user would of course bookmark the shortened version.</li> </ul> <p>Any other ideas?</p> <p>Also, does anyone know if the length is the encoded length or just plain text?</p> <p>I'm developing in PHP, but it probably doesn't make a difference.</p> <p><strong>Edit:</strong> I am unable to remove any fields; I am unable to shorten the form. This is what the client has asked for and they often do use a range of fields, in the different categories. I know that it's hard to think of a form that looks nice with this many fields, but the users don't have a problem understanding how it works.</p>
<p>Are your users actually going to be using all 50-100 fields to do their searches? If they're only using a few, why not POST the search to an "in between" page which header()-redirects them to the results page with only the user-changed fields in the URL? The results page would then use the default values for the fields that don't exist in the URL.</p>
<p>Use post and if the user bookmarks the search, save it in a database and give it a unique token, then redirect to the search page using <code>GET</code> and passing the token as parameter.</p> <p>TinyURL is a nice example: You give it a very long URL, it saves it to a DB, gives you a unique identifier for that URL and later you can request the long URL using that identifier.</p> <p>In PHP it would be something along the lines of:</p> <pre><code>&lt;?php if (isset($_GET['token'])) { $token = addslashes($_GET['token']); $qry = mysql_query("SELECT fields FROM searches WHERE token = '{$token}'"); if ($row = mysql_fetch_assoc($qry)) { performSearch(unserialize($row['fields'])); exit; } showError('Your saved search has been removed because it hasn\'t been used in a while'); exit; } $fields = addslashes(serialize($_POST)); $token = sha1($_SERVER['REMOTE_ADDR'].rand()); mysql_query("INSERT INTO searches (token, fields, save_time) Values ('{$token}', '{$fields}', NOW())"); header('Location: ?token='.$token); exit; ?&gt; </code></pre> <p>And run a script daily:</p> <pre><code>&lt;?php mysql_query('DELETE FROM searches WHERE save_time &lt; DATE_ADD(NOW(), INTERVAL -200 DAY)'); ?&gt; </code></pre>
38,065
<p>Can someone explain why how the result for the following unpack is computed?</p> <pre><code>"aaa".unpack('h2H2') #=&gt; ["16", "61"] </code></pre> <p>In binary, 'a' = 0110 0001. I'm not sure how the 'h2' can become 16 (0001 0000) or 'H2' can become 61 (0011 1101).</p>
<p>Not 16 - it is showing 1 and then 6. h is giving the hex value of each nibble, so you get 0110 (6), then 0001 (1), depending on whether its the high or low bit you're looking at. Use the high nibble first and you get 61, which is hex for 97 - the value of 'a'</p>
<p>The hex code of char <code>a</code> is 61.</p> <p>Template <code>h2</code> is a hex string (low nybble first), <code>H2</code> is the same with high nibble first.</p> <p>Also see the <a href="http://perldoc.perl.org/functions/pack.html" rel="nofollow noreferrer">perl documentation</a>.</p>
15,990
<p>A coworker of mine has this problem, apparently after installing Re#, which seems totally irrelevant. But perhaps it isn't.</p> <p>Could not load file or assembly "SqlManagerUi, Version=9.0.242.0..." or one of its dependencies. The module was expected to contain an assembly manifest. (mscorlib).</p> <p>Why is this?</p> <p>Thanks</p>
<p>I was with a similar problem, i could not open my SQL Server Management Studio. This steps works for me:</p> <p>In file <code>C:\Program Files (x86)\Microsoft SQL Server Management Studio 18\Common7\IDE\Ssms.exe.config</code>, erase the item <code>&lt;NgenBind_OptimizeNonGac enabled="1" /&gt;</code>.</p> <p>Example:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;!-- ...snip... --&gt; &lt;runtime&gt; &lt;!-- ...snip... --&gt; &lt;!-- Remove this line (~line 38) --&gt; &lt;NgenBind_OptimizeNonGac enabled="1" /&gt; &lt;!-- ...snip... --&gt; &lt;/runtime&gt; &lt;!-- ...snip... --&gt; &lt;/configuration&gt; </code></pre> <p>I hope this helps.</p>
<p>was there any installing/uninstalling of VS involved? Don't get me started on SQL 2005 and VS intall conficts. </p>
15,511
<p>this should be simple...could someone provide me a simple code sample that has an aspx page hosting both a silverlight app (consisting of, say a button) and an iframe (pointing to, say stackoverflow.com). The silverlight app and iframe could be in separate div's, the same div, whatever. </p> <p>Everything I've tried so far leaves me with a page that has no silverlight control rendered on it.</p> <p>EDIT: At the request for what my xaml looks like (Plus I should point out that my controls render just fine if I comment out the iframe.)</p> <pre><code>&lt;UserControl x:Class="SilverlightApplication1.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Grid x:Name="LayoutRoot" Background="Pink"&gt; &lt;Button Content="Click Me!"/&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>Thats it. Just for good measure here is my aspx page...</p> <pre><code>&lt;form id="form1" runat="server"&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server"/&gt; &lt;div style="height:100%;"&gt; &lt;asp:Silverlight ID="Silverlight1" runat="server" Source="~/ClientBin/SilverlightApplication1.xap" MinimumVersion="2.0.30523" Width="400" Height="400" /&gt; &lt;/div&gt; &lt;iframe src ="http://www.google.com" width="400"/&gt; &lt;/form&gt; </code></pre>
<p>Hmm, sound a bit odd, a quick google gave me <a href="http://silverlight.net/forums/p/21584/75457.aspx" rel="nofollow noreferrer">this top result</a> which talks about using an Iframe and Silverlight on the same page, without problems.</p> <p>Also a quick test with the following code:</p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" %&gt; &lt;%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;"&gt; &lt;head runat="server"&gt; &lt;title&gt;Test Page&lt;/title&gt; &lt;/head&gt; &lt;body style="height:100%;margin:0;"&gt; &lt;form id="form1" runat="server" style="height:100%;"&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server"&gt;&lt;/asp:ScriptManager&gt; &lt;div style="height:100%;"&gt; &lt;asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/Test.xap" MinimumVersion="2.0.30523" Width="400" Height="400" /&gt; &lt;/div&gt; &lt;iframe src ="http://www.google.com" width="400"&gt;&lt;/iframe&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Renders out both Silverlight and the Iframe quite happily.</p> <p>What code were you using when trying and it didn't work?</p>
<p>What does your XAML look like? </p> <p>It could be something along the lines of the size set on the usercontrol in XAML, doesn't match the size set on the plugin on the aspx page. In that case, your button might be there but just not in the viewable area... Try checking the size of things, make sure they match.</p> <p>A quick test you could do is to change the background color of your root element in the XAML and see if anything happen on the page.</p> <p>Also, does the silverlight work if you remove the Iframe but leave everything else as is?</p> <p>Sorry if this a too simple suggestion but without knowing your experience level with XAML... </p>
11,852
<p>I am working on an application that is about 250,000 lines of code. I'm currently the only developer working on this application that was originally built in .NET 1.1. Pervasive throughout is a class that inherits from CollectionBase. All database collections inherit from this class. I am considering refactoring to inherit from the generic collection List instead. Needless to say, Martin Fowler's Refactoring book has no suggestions. Should I attempt this refactor? If so, what is the best way to tackle this refactor?</p> <p>And yes, there are unit tests throughout, but no QA team.</p>
<p>Don't. Unless you have a really good business justification for putting your code base through this exercise. What is the cost savings or revenue generated by your refactor? If I were your manager I would probably advise against it. Sorry. </p>
<p>I agree with Thomas.</p> <p>I feel the question you should always ask yourself when refactoring is "What do I gain by doing this vs doing something else with my time?" The answer can be many things, from increasing maintainability to better performance, but it will always come at the expense of something else.</p> <p>Without seeing the code it's hard for me to tell, but this sounds like a very bad situation to be refactoring in. Tests are good, but they aren't fool-proof. All it takes is for one of them to have a bad assumption, and your refactor could introduce a nasty bug. And with no QA to catch it, that would not be good.</p> <p>I'm also personally a little leary of massive refactors like this. Cost me a job once. It was my first job outside of the government (which tends to be a little more forgiving, once you get 'tenure' it's damn hard to get fired) and I was the sole web programmer. I got a legacy ASP app that was poorly written dropped in my lap. My first priority was to get the darn thing refactored into something less...icky. My employer wanted the fires put out and nothing more. Six months later I was looking for work again :p Moral of this story: Check with your manager first before embarking on this.</p>
12,382
<p>I added a text file to a testapp's solution and I want to read said file. I don't remember how to do this, I know it has to do with reflections but I need a push in the right direction.</p>
<p>If you add the text file to a .ResX file, you can have all the benefits (dynamic updating, for instance) AND not need to worry about interacting with an actual file. VB will automatically create a class to access the file - suppose you have Resources.resx. You can access it with My.Resources.MyFile - it will return a string.</p>
<p>I was going to write some code, but instead found a better explanation <a href="http://www.homeandlearn.co.uk/NET/nets8p2.html" rel="nofollow noreferrer">here</a></p> <p>In your case, you'll need to use your application path instead of "C:\".</p>
42,990
<p>I personally use <a href="http://php.net/var_dump" rel="nofollow noreferrer"><code>var_dump</code></a>, but lots of people like <a href="http://php.net/print_r" rel="nofollow noreferrer"><code>print_r</code></a>. </p> <p>What does everyone use? Pros and Cons?</p> <p>Does someone have a special home brew function of their own?</p>
<p>I use <code>print_r()</code> because I like the pretty array structure... but <code>var_dump</code> does give you a bit more information (like types)</p> <pre><code>$obj = (object) array(1, 2, 3); // output of var_dump: object(stdClass)#1 (3) { [0]=&gt; int(1) [1]=&gt; int(2) [2]=&gt; int(3) } // output of print_r stdClass Object ( [0] =&gt; 1 [1] =&gt; 2 [2] =&gt; 3 ) </code></pre>
<p>print_r() usually, but var_dump() provides better information for primitives.</p> <p>That being said, I do most of my <em>actual</em> debugging with the Zend Server Debugger.</p>
17,103
<p>We've looked in Silverlight 2 recently and found no way to edit formatted text there. Is this really true, and are there any (maybe commercial) external rich text editors available?</p>
<p>Vectorlight has a <a href="http://www.vectorlight.net/silverlight_rich_textbox_demo.aspx" rel="nofollow noreferrer">rich text box</a>.</p>
<p>I haven't tried it myself yet but this is one I know of.</p> <p><a href="http://www.codeplex.com/richtextedit" rel="nofollow noreferrer">http://www.codeplex.com/richtextedit</a></p>
15,611
<p>Stack exchange isn't a good platform for product recommendations in general, but a few sites allow it with a tight focus and control. Some that have allowed it in the past have decided to discontinue it for a variety of reasons.</p> <p>I expect at the start we are going to get a lot of "What specific machine should I use" or "is there a 3D model of item X I can print".</p> <ol> <li>Should we allow product or part recommendations?</li> <li>If we do, what can we do to make sure they are limited, rather than open ended questions where dozens or hundreds of answers would be different but correct?</li> </ol>
<p>I agree with Jeff's blog post: <a href="https://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/">https://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/</a></p> <blockquote> <p>don't ask us what you should buy -- ask us <em>what you need to learn</em> to tell what you should buy.</p> </blockquote>
<p>I think that hardware recommendations are ok, but in a <strong>limited</strong> and <strong>specific</strong> scope:</p> <p>Bad:</p> <blockquote> <p>Can you recommend a cheap printer with a heated bed that's at least 8&quot;*8&quot;*8&quot;.</p> <p>Which is better? Printer X or printer Y?</p> </blockquote> <p>Good:</p> <blockquote> <p>What hotend can I use to print at 300+C?</p> <p>What are the advantages of borosilicate glass over picture frame glass?</p> </blockquote>
2
<p>It seems like Groovy was forgotten in this thread so I'll just ask the same question for Groovy.</p> <ul> <li>Try to limit answers to Groovy core</li> <li>One feature per answer</li> <li>Give an example and short description of the feature, not just a link to documentation</li> <li>Label the feature using bold title as the first line</li> </ul> <p>See also:</p> <ol> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a></li> <li><a href="https://stackoverflow.com/questions/63998/hidden-features-of-ruby">Hidden features of Ruby</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl">Hidden features of Perl</a></li> <li><a href="https://stackoverflow.com/questions/15496/hidden-features-of-java">Hidden features of Java</a></li> </ol>
<p><strong>Using the spread-dot operator</strong></p> <pre><code>def animals = ['ant', 'buffalo', 'canary', 'dog'] assert animals.size() == 4 assert animals*.size() == [3, 7, 6, 3] </code></pre> <p>This is a shortcut for <code>animals.collect { it.size() }</code>.</p>
<h2><strong>Elvis operator</strong></h2> <p><strong>"Elvis operator"</strong> is a shortening of the ternary operator. One instance of where this is handy is for returning a 'sensible default' value if an expression resolves to false(as in Groovy truth). A simple example might look like this:</p> <p>with the ternary operator, you have to repeat the value you want to assign </p> <pre><code>displayCity = user.city ? user.city: 'UnKnown City' </code></pre> <p>with the Elvis operator, the value, which is tested, is used if it is not false</p> <pre><code>displayCity = user.city ?: 'UnKnown City' </code></pre>
38,996
<p>So I have a daemon running on a Linux system, and I want to have a record of its activities: a log. The question is, what is the "best" way to accomplish this?</p> <p>My first idea is to simply open a file and write to it.</p> <pre><code>FILE* log = fopen("logfile.log", "w"); /* daemon works...needs to write to log */ fprintf(log, "foo%s\n", (char*)bar); /* ...all done, close the file */ fclose(log); </code></pre> <p>Is there anything inherently wrong with logging this way? Is there a better way, such as some framework built into Linux?</p>
<p>Unix has had for a long while a special logging framework called <a href="http://en.wikipedia.org/wiki/Syslog" rel="noreferrer">syslog</a>. Type in your shell </p> <pre><code>man 3 syslog </code></pre> <p>and you'll get the help for the C interface to it.</p> <p><a href="http://www.codeproject.com/KB/IP/syslog_client.aspx" rel="noreferrer">Some</a> <a href="http://www.c.happycodings.com/Gnu-Linux/code21.html" rel="noreferrer">examples</a></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;syslog.h&gt; int main(void) { openlog("slog", LOG_PID|LOG_CONS, LOG_USER); syslog(LOG_INFO, "A different kind of Hello world ... "); closelog(); return 0; } </code></pre>
<p>There are a lot of potential issues: for example, if the disk is full, do you want your daemon to fail? Also, you will be overwriting your file every time. Often a circular file is used so that you have space allocated on the machine for your file, but you can keep enough history to be useful without taking up too much space. There are tools like log4c that you can help you. If your code is c++, then you might consider log4cxx in the Apache project (apt-get install liblog4cxx9-dev on ubuntu/debian), but it looks like you are using C.</p>
19,162
<p>I like the flexibility of Dynamic SQL and I like the security + improved performance of Prepared Statements. So what I really want is Dynamic Prepared Statements, which is troublesome to make because bind_param and bind_result accept "fixed" number of arguments. So I made use of an eval() statement to get around this problem. But I get the feeling this is a bad idea. Here's example code of what I mean</p> <pre><code>// array of WHERE conditions $param = array('customer_id'=&gt;1, 'qty'=&gt;'2'); $stmt = $mysqli-&gt;stmt_init(); $types = ''; $bindParam = array(); $where = ''; $count = 0; // build the dynamic sql and param bind conditions foreach($param as $key=&gt;$val) { $types .= 'i'; $bindParam[] = '$p'.$count.'=$param["'.$key.'"]'; $where .= "$key = ? AND "; $count++; } // prepare the query -- SELECT * FROM t1 WHERE customer_id = ? AND qty = ? $sql = "SELECT * FROM t1 WHERE ".substr($where, 0, strlen($where)-4); $stmt-&gt;prepare($sql); // assemble the bind_param command $command = '$stmt-&gt;bind_param($types, '.implode(', ', $bindParam).');'; // evaluate the command -- $stmt-&gt;bind_param($types,$p0=$param["customer_id"],$p1=$param["qty"]); eval($command); </code></pre> <p>Is that last eval() statement a bad idea? I tried to avoid code injection by encapsulating values behind the variable name $param.</p> <p>Does anyone have an opinion or other suggestions? Are there issues I need to be aware of?</p>
<p>I think it is dangerous to use <code>eval()</code> here.</p> <p>Try this:</p> <ul> <li>iterate the params array to build the SQL string with question marks <code>"SELECT * FROM t1 WHERE p1 = ? AND p2 = ?"</code></li> <li>call <code>prepare()</code> on that </li> <li>use <code>call_user_func_array()</code> to make the call to <code>bind_param()</code>, passing in the dynamic params array.</li> </ul> <p>The code:</p> <pre><code>call_user_func_array(array($stmt, 'bind_param'), array($types)+$param); </code></pre>
<p>You don't really need prepared statements and bound arguments, because you can always use mysql_real_escape_string(). And you're right; dynamically generated SQL is far more flexible and valuable. </p> <p>Here's a simple example using the regular mysql_* interface:</p> <pre><code>// Array of WHERE conditions $conds = array("customer_id" =&gt; 1, "qty" =&gt; 2); $wherec = array("1"); foreach ($conds as $col=&gt;$val) $wherec[] = sprintf("`%s` = '%s'", $col, mysql_real_escape_string($val)); $result_set = mysql_query("SELECT * FROM t1 WHERE " . implode(" AND ", $wherec); </code></pre> <p>Of course, this is a simplistic example, and to make it useful you have to build and refine it a lot, but it shows the ideas and it's really very very useful. For example, here is a completely generic function to insert a new row into an arbitrary table, with the columns filled with the values from an associative array and completely SQL-injection safe:</p> <pre><code>function insert($table, $record) { $cols = array(); $vals = array(); foreach (array_keys($record) as $col) $cols[] = sprintf("`%s`", $col); foreach (array_values($record) as $val) $vals[] = sprintf("'%s'", mysql_real_escape_string($val)); mysql_query(sprintf("INSERT INTO `%s`(%s) VALUES(%s)", $table, implode(", ", $cols), implode(", ", $vals))); } // Use as follows: insert("customer", array("customer_id" =&gt; 15, "qty" =&gt; 86)); </code></pre>
24,599
<p>How do I make the XDocument object save an attribute value of a element with single quotes?</p>
<p>I'm not sure that any of the formatting options for LINQ to XML allow you to specify that. Why do you need to? It's a pretty poor kind of XML handler which is going to care about it...</p>
<p>I'm not sure that any of the formatting options for LINQ to XML allow you to specify that. Why do you need to? It's a pretty poor kind of XML handler which is going to care about it...</p>
27,496
<p>any thoughts on this would be appreciated:</p> <pre><code>std::string s1 = "hello"; std::string s2 = std::string(s1); </code></pre> <p>I'd now expect these two strings to be independent, i.e. I could append ", world" to s2 and s1 would still read "hello". This is what I find on windows and linux but running the code on a HP_UX machine it seems that s2 and s1 are the same string, so modifying s2 changes s1.</p> <p>Does this sound absolutely crazy, anyone seen anything similar?</p>
<p>Although I could not reproduce the exact bug of the OP, I came across a similar bug in the HP-UX aCC compilers. I posted about it on the <a href="http://forums12.itrc.hp.com/service/forums/questionanswer.do?admit=109447627+1223649583692+28353475&amp;threadId=1108413" rel="noreferrer">HP boards</a>, and eventually got a response from HP. Basically their versions 3.xx (3.70, 3.73, 3.67, etc.) of aCC have messed up std::string construction. We had to move to the 6.xx versions of the compiler. The problem we had at the time was that there was not a 6.xx compiler available for PA-RISC machines, just Itanium. I believe that a 6.xx compiler was released for PA-RISC in September 2007.</p> <p>The code that was giving the problem was:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; class S : public std::string // An extension of std::string { public: explicit S(const char* s) : std::string(s) { } }; class N // Wraps an int { public: explicit N(int n) : _n(n) {} operator S() const // Converts to a string extension { return _n == 0 ? S("zero") : (_n == 1 ? S("one") : S("other")); } private: int _n; }; int main(int, char**) { N n0 = N(0); N n1 = N(1); std::string zero = n0; std::cout &lt;&lt; "zero = " &lt;&lt; zero &lt;&lt; std::endl; std::string one = n1; std::cout &lt;&lt; "zero = " &lt;&lt; zero &lt;&lt; ", one = " &lt;&lt; one &lt;&lt; std::endl; return 0; } </code></pre> <p>This was printing:<br> zero = zero<br> <strong><em>zero = one</em></strong>, one = one</p> <p>In other words the construction of string one from n1 was clobbering another string completely (string zero).</p> <p>NOTES:<br> To see the version of the compiler, type "aCC -V"<br> To see the type of machine, type "uname -m" (9000/800 ==> PA-RISC, ia64 ==> Itanium) </p>
<p>That sure sounds like a bug to me. Can anyone else who has access to HP/UX repro this?</p> <p>You're saying that this program displays the same text on both lines?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string&gt; int main () { std::string s1 = "hello"; std::string s2 = std::string(s1); // note: std::string s2( s1); would reduce the number of copy ctor calls s2.append( ", world"); printf( "%s\n", s1.c_str()); printf( "%s\n", s2.c_str()); } </code></pre>
22,988
<p>I would like create a web service in ASP.Net 2.0 that will supports JSON. Is there a way to do this without WCF and .Net 3.5? Can anyone point me to a good article or sample code? </p> <p><strong>Clarification</strong></p> <p>I need direction on what is the best method, using the .Net 2.0 framework, to communicate JSON objects to a client. Is it possible to do this without serializing the object to a string and then deserializing on the client?</p>
<p>use JayRock!</p> <p>JayRock will work with .net 2.0</p> <p><a href="http://jayrock.berlios.de/" rel="nofollow noreferrer">http://jayrock.berlios.de/</a></p>
<p>You can utilize WCF for your website, The WCF JSON endpoint can even generate javascript client proxy for the service.</p> <p>Check out this post</p> <p><a href="https://stackoverflow.com/questions/186631/rest-soap-endpoints-for-a-wcf-service#186695">REST / SOAP endpoints for a WCF service</a></p> <p>A download sample can be found </p> <p><a href="http://www.codemeit.com/wcf/wcf-restful-pox-json-and-soap-coexist.html" rel="nofollow noreferrer">http://www.codemeit.com/wcf/wcf-restful-pox-json-and-soap-coexist.html</a></p>
29,945
<p>Suppose <code>a</code> and <code>b</code> are both of type <code>int</code>, and <code>b</code> is nonzero. Consider the result of performing <code>a/b</code> in the following cases:</p> <ol> <li><code>a</code> and <code>b</code> are both nonnegative.</li> <li><code>a</code> and <code>b</code> are both negative.</li> <li>Exactly one of them is negative.</li> </ol> <p>In Case 1 the result is rounded down to the nearest integer. But what does the standard say about Cases 2 and 3? An old draft I found floating on the Internet indicates that it is implementation dependent (yes, even case 2) but the committee is leaning toward making it always 'round toward zero.' Does anyone know what the (latest) standard says? Please answer only based on the standard, not what makes sense, or what particular compilers do.</p>
<p>According to the May 2008 revision,</p> <p>You're right:</p> <blockquote> <p>The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined75).</p> </blockquote> <p>Note 75 says:</p> <blockquote> <p>According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.</p> </blockquote> <p>Chances are that C++ will lag C in this respect. As it stands, it's undefined but they have an eye towards changing it.</p> <p>I work in the same department as Stroustrup and with a member of the committee. Things take AGES to get accomplished, and its endlessly political. If it seems silly, it probably is. </p>
<p>Sometimes we need to take a step back, and look just at the mathematics of it:</p> <p>Given int x, int y</p> <p>if int i1 = x/y and int i2 = x%y</p> <p>then y * i1 + i2 must be x</p> <p>So this is not so much about the standard, but there is only one way this can possibly be. If any standards allows it to be any other way, then the standard is wrong, and that means the language is broken. </p>
41,366
<p>So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address <a href="http://www.stackoverflow.com/questions/ask">http://www.stackoverflow.com/questions/ask</a>. I would need the protocol and domain (e.g. <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a>) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions?</p>
<p>Dan is right: urlparse is your friend:</p> <pre><code>&gt;&gt;&gt; from urlparse import urlparse &gt;&gt;&gt; &gt;&gt;&gt; parts = urlparse("http://www.stackoverflow.com/questions/ask") &gt;&gt;&gt; parts.scheme + "://" + parts.netloc 'http://www.stackoverflow.com' &gt;&gt;&gt; parts.path '/questions/ask' </code></pre> <p><strong>Note</strong>: In Python 3 it's <code>from urllib.parse import urlparse</code></p>
<pre><code>import re url = "http://stackoverflow.com/questions/ask" protocol, domain = re.match(r"(http://[^/]*)(.*)", url).groups() </code></pre>
36,357