input
stringlengths
51
42.3k
output
stringlengths
18
55k
return eats exception <p>I found the following behavior at least <em>weird</em>:</p> <pre><code>def errors(): try: ErrorErrorError finally: return 10 print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined </code></pre> <p>The exception disappears when you use <code>return</code> inside a <code>finally</code> clause. Is that a bug? Is that documented anywhere?</p> <p>But the real question (and the answer I will mark as correct) is:<br> What is the python developers' reason to allow that odd behavior?</p>
<blockquote> <p>The exception disappears when you use <code>return</code> inside a <code>finally</code> clause. .. Is that documented anywhere?</p> </blockquote> <p><a href="http://docs.python.org/reference/compound_stmts.html#the-try-statement" rel="nofollow">It is:</a></p> <blockquote> <p>If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. <strong>If the finally clause raises another exception or executes a return or break statement, the saved exception is lost.</strong></p> </blockquote>
Why volatile is not enough? <p>I'm confused. Answers to my <a href="http://stackoverflow.com/questions/516940/can-multiple-cpus-simultaneously-write-to-the-same-ram-location">previous question</a> seems to confirm my assumptions. But as stated <a href="http://stackoverflow.com/questions/154551/volatile-vs-interlocked-vs-lock">here</a> volatile is not enough to assure atomicity in .Net. Either operations like incrementation and assignment in MSIL are not translated directly to single, native OPCODE or many CPUs can simultaneously read and write to the same RAM location.</p> <p>To clarify:</p> <ol> <li>I want to know if writes and reads are atomic on multiple CPUs?</li> <li>I understand what volatile is about. But is it enough? Do I need to use interlocked operations if I want to get latest value writen by other CPU? </li> </ol>
<p>Herb Sutter recently wrote an article on <code>volatile</code> and what it really means (how it affects ordering of memory access and atomicity) in the native C++. .NET, and Java environments. It's a pretty good read:</p> <ul> <li><a href="http://www.ddj.com/hpc-high-performance-computing/212701484" rel="nofollow">volatile vs. volatile</a></li> </ul>
JMS rollback <p>I have a process which involves sending a JMS message. The process is part of a transaction. If a later part of the transaction fails, a part that is after a previous part that sent the message, I need to cancel the message. One thought I had was to somehow set on the message that it is not to be picked up for a certain amount of time, and if I need to rollback, then I could go and cancel the message. Not knowing messaging, I do not know if the idea is possible. Or, is there a better idea? Thanks</p>
<p>What you have described is an XA transaction. This allows a transaction to scope across multiple layers i.e. JMS provider, DB or any other EIS. Most containers can be configured to use both non XA and none XA transaction so check your container settings!</p> <p>For example if you are using JMS with XA transactions the following is possible.</p> <pre><code>Start Transaction | DB Insert | Send JMS Msg | More DB Inserts | Commit Transaction &lt;- Only at this point will the database records be inserted and the JMS message sent. </code></pre> <p>XA Tranactions are only available in full Java EE containers so XA transactions are not available in Tomcat.</p> <p>Good luck!</p> <p>Karl</p>
SharePoint Workflows - How to associate with specific content types (particularly folders)? <p>I noticed when working with SharePoint Designer that each workflow has a config xml with tags. Does anyone know how to: 1) Associate the workflow with a specific content type? 2) Know if it is possible to associate a workflow with folders?</p>
<p>It is possible to associate workflows with folders. Apparently Visual Studio created Windows Workflow Foundation (WWF) development is the only tried-and-true way to create custom workflows that can be associated with different content types. There are some enterprise tools that can help a lot for creating custom workflows such as <a href="http://www.k2.com/en/displaycontent.aspx?id=901" rel="nofollow">K2's Blackpoint</a> (though I haven't had a chance to try the software).</p> <p>I did find a couple of other workflow tutorials to start me off:</p> <ul> <li><a href="http://www.codeproject.com/KB/sharepoint/MOSS_FolderContentTypeWF.aspx?display=Print" rel="nofollow">SharePoint Workflows for Folder Content Type - codeproject.com</a></li> <li><a href="http://blogs.msdn.com/sharepoint/archive/tags/Workflow/default.aspx" rel="nofollow">Microsoft SharePoint Team Blog</a></li> </ul> <p>I didn't find any information on the config xml tags yet.</p>
Using MSMQ for interprocess(inter application) communication on Windows Mobile 5.0 <p>We have a Native Embedded VC (EVC4.0) application running on a Windows Mobile 5 device. Now there is a requirement to get this application to talk with a new mobile application to be developed using either EVC4.0 or .Net CF. We were thinking of using MSMQ on the Windows Mobile device for inter process communication between these 2 apps. </p> <p>Has anyone used MSMQ for this kind of reason before?</p> <p>Thanks, -Sid</p>
<p>WM_COPYDATA, sockets, memory-mapped files and point-to-point message queues are all IPC mechanisms for CE (well named events are also available). I tend to lean toward point-to-point queues or memory-mapped files. Which one depends on the nature of the data I want to share.</p>
Code reusability - App_Code or BIN or UserControls? <p>I recently had a discussion on another forum with another developer and the topic was Code Reuse in ASP.NET. The stated scenario was that he needs to update code frequently on Production servers during server uptimes, and this results in Session getting reset for all users. He is avoiding putting shared code or classes into the App_Code folder or precompiled DLL's into the Bin folder because any updates will also refresh the Session.</p> <p>The solution he has come up with is to put his shared code into UserControls and reference them wherever required. This enables him to update only the UserControl files which would be recompiled dynamically on next request without forcing a Session restart. Note that the Usercontrols are not intended to have any UI, they probably only house some business logic.</p> <p>I tried to convince him against this because it felt intrinsically wrong to me - but I could not provide any hard facts to support my claim that this was a very bad way of doing things. The only thing I could think of is that it violates the principle of separation of business logic from UI. Am I grossly mistaken or are there concrete reasons why this should not be done? Links or examples would be helpful.</p> <p>Note: <em>Using out-of-process Session state is not an option at present, nor have they been able to decide on scheduled downtimes. Also, since this is a site under active development, they don't seem to be using any sort of professional deployment model yet.</em></p> <p>Thanks in advance.</p> <p>Edit: Additionally, it would be helpful if someone could clarify exactly why the Session restarts in the above mentioned cases.</p>
<p>It sounds like the main problem is that he's updating production code too frequently. Other than that, UserControls seem like a perfectly reasonable place to put business logic, especially if you have a good naming convention for them or can put them in a common folder.</p>
How do I get Team Build to show test results and coverage for xUnit.net test suite? <p>Has anybody had any success getting Team Build to show xUnit.net test results and code coverage in the build report? The MSBuild runner is running the tests just fine and the results are in the log file, but the test results and code coverage results areas of the build report say "No test result" and "No coverage result" respectively. Is Team Build looking for a certain location / format for the test results to be exported by the xUnit.net runner?</p>
<p>TFS/TeamBuild definitely requires the test results in a particular format, they also need to be specifically published to TFS as well.</p> <p>I'm currently looking at this problem for the Gallio test runner, and can offer two potential options:</p> <ol> <li>Try wrapping the xUnit tests inside the 'Generic Test' project type that VSTS offers - this is where MSTest executes the xUnit test runner.</li> <li>Come up with an XSLT transform (or similar) that can map the xUnit results to the MSTest schema (see <a href="http://www.codeplex.com/nunit4teambuild" rel="nofollow">http://www.codeplex.com/nunit4teambuild</a> for an example of this approach for NUnit tests).</li> </ol>
Library resolution with autoconf? <p>I'm building my first autoconf managed package.</p> <p>However I can't find any simple examples anywhere of how to specify a required library, and find that library where it might be in various different places.</p> <p>I've currently got:</p> <pre><code>AC_CHECK_LIB(['event'], ['event_init']) </code></pre> <p>but:</p> <ol> <li>It doesn't find the version installed in <code>/opt/local/lib</code></li> <li>It doesn't complain if the library isn't actually found</li> <li>I need to set the include path to <code>/opt/local/include</code> too</li> </ol> <p>any help, or links to decent tutorials much appreciated...</p>
<p>autoconf script cannot guess the "optional" library locations, which may vary from one platform to another. So you can say</p> <pre><code>CPPFLAGS="-I/opt/local/include" LDFLAGS="-L/opt/local/lib" ./configure </code></pre> <p>For <code>AC_CHECK_LIB()</code> you need to specify the fail condition explicitly in "action-if-false" argument:</p> <pre><code>dnl This is simply print "no" and continue: AC_CHECK_LIB([m], [sqrt123]) dnl This will stop: AC_CHECK_LIB([m], [sqrt123], [], [AC_MSG_ERROR([sqrt123 was not found in libm])]) </code></pre> <p>Output:</p> <pre><code>checking for sqrt123 in -lm... no checking for sqrt123 in -lm... no configure: error: sqrt123 was not found in libm </code></pre> <p><code>AC_CHECK_LIB()</code> does not fail by default on obvious reasons: one may check for several different libraries that provide similar functionality and choose one of them :)</p> <p>Also have a look at <a href="http://stackoverflow.com/questions/1596536/what-is-the-best-way-to-auto-detect-library-dependencies-in-a-c-c-project">this post</a> for similar topic.</p>
When NOT to use the Entity Framework <p>I have been playing around with the EF to see what it can handle. Also many articles and posts explain the various scenarios in which the EF can be used, however if miss the "con" side somehow. Now my question is, <strong>in what kind of scenarios should I stay away from the Entity Framework</strong> ?</p> <p>If you have some experience in this field, tell me what scenarios don't play well with the EF. Tell me about some downsides you experienced where you whished you would have chosen a different technology.</p>
<p>The <a href="http://efvote.wufoo.com/forms/ado-net-entity-framework-vote-of-no-confidence/">Vote of No Confidence</a> lists several missteps and/or missing bits of functionality in the eyes of those who believe they know what features, and their implementations, are proper for ORM/Datamapper frameworks. </p> <p>If none of those issues are a big deal to you, then I don't see why you shouldn't use it. I have yet to hear that it is a buggy mess that blows up left and right. All cautions against it are philosophical. I happen to agree with the vote of no confidence, but that doesn't mean you should. If you happen to like the way EF works, then go for it. At the same time I'd advise you to at least read the vote of no confidence and try to get a rudimentary understanding of each of the issues in order to make an informed decision. </p> <p>Outside of that issue and to the heart of your question - You need to keep an eye on the Sql that is being generated so you can make tweaks before a performance problem gets into production. Even if you are using procs on the backend, I'd still look for scenarios where you may be hitting the database too many times and then rework your mappings or fetching scenarios accordingly. </p>
URLLoader annoying problem <p>i am trying to load a variable through php from a sql database but i get nothing</p> <p>here is the code</p> <pre><code>var Idfield; var loader:URLLoader = new URLLoader(); // data will come as URL encoded variables loader.dataFormat = URLLoaderDataFormat.VARIABLES; loader.load(new URLRequest("pull.php")); loader.addEventListener(Event.COMPLETE,dataload); function dataload(e:Event){ Idfield =e.target.data["id"]; trace(Idfield); } </code></pre> <p>here is the php code</p> <pre><code> $query = "SELECT max(id) from $tablename"; $result = mysql_query($query) or die("no rows selected"); $row = mysql_fetch_row($result); // extracts one row echo "id=$row[0]"; </code></pre>
<p>I believe the variables format expects the variables in the name=value format so try something like:</p> <pre><code>echo 'id=' . $row[0]; </code></pre>
Refactor "using" directives over an entire codebase? <p>One of the things I love about Visual Studio 2008 is the ability to refactor and reorganize the "using" directives in source code files (this may have been in 2005 as well, I don't remember).</p> <p>Specifically, I'm talking about how you can have it both reorganize the directives to be alphabetical (though with the core FCL libraries floating to the top) and removing any directives which don't need to be there (either never used or no longer used).</p> <p>Is there any way to automate this refactoring (the sorting and trimming) across an entire old codebase? Either through all of the files in a solution or across multiple solution files.</p>
<p>I believe you can do it solution wide using <a href="http://code.msdn.microsoft.com/PowerCommands" rel="nofollow">Power Commands</a></p> <p>From PowerCommands Documentation:</p> <blockquote> <p>Remove and Sort Usings This command removes and sort using statements for all classes given a project. It is useful, for example, in removing or organizing the using statements generated by a wizard. This command can be executed from a solution node or a single project node.</p> </blockquote>
How to order categories in WordPress? <p>I use <code>wp_list_categories()</code> to get the list of all the categories and generate the navigation bar. Is there a way to order these categories in a particular order other than alphabetical ordering. </p> <p>eg: Connect, News &amp; Views, Q&amp;A, Hello Startup, Startup 101...</p>
<p>If you don't use the Description field of the categories, ordering can also be done by entering a number in each Description field, and subsequently use Javascript / jQuery to order based on this numbering.</p> <p>The wp_list_categories function has a <strong>use_desc_for_title</strong> argument which you can set to true:</p> <pre><code>wp_list_categories('use_desc_for_title=1'); </code></pre> <p>The category description is now set to the <code>&lt;a&gt;</code> tags's title attribute in the resulting html.</p> <p>So if you use numbers in the description field, the resulting category listing may look like this:</p> <pre><code> &lt;ul id="category_list"&gt; &lt;li&gt;&lt;a href="#" title="3"&gt;Category C&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" title="1"&gt;Category A&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" title="2"&gt;Category B&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Now you can sort the list, for example with jQuery at the document.ready event. If you use subcategories in a hierarchical way, use a recursive function like this:</p> <pre><code>$( document ).ready( function() { sort_list_recursive( $( '#category_list' ) ); } ); function sort_list_recursive( parent ) { var lst = parent.children( 'li' ); lst.sort( function( a, b ) { var _a = a.getElementsByTagName( 'a' )[0].title; var _b = b.getElementsByTagName( 'a' )[0].title; return _a &gt; _b ? 1 : -1; } ).appendTo( parent ); lst.each( function() { $( this ).children( 'ul' ).each( function() { sort_list_recursive( $( this ) ); }); }); } </code></pre> <p>N.B.</p> <ul> <li>Don't use a 0 (zero) in the description field, it will be ignored and set to null</li> <li>After sorting you might want to get rid of the title attributes which are set to numbers, this can easily be done with jQuery.</li> </ul>
COM C# Memory leak Tracing <p>Is there a way to find out the memory usage of each dll within a c# application using com dll's? Or what would you say is the best way to find out why memory grows exponentially when using a com object (IE. Whether the COM object has a memory leak, or whether some special freeing up of objects passed to managed code has to occur(and/or how to do that)).</p>
<p>Are you releasing the COM object after usage(<code>Marshal.ReleaseComObject</code>)? </p> <p>What type of parameters are you passing in/out of the calls?</p> <p>If you don't have the COM object source code and want to determine why its 'leaking', Run the COM object outa proc, attach WinDBG to the process and set breakpoints on memory allocation APIs(HeapAlloc,etc...). Look at the call stack and allocation patterns. Sure you can use profilers on the managed side but if you want to know what is going on you are going to have to get your hands dirty...</p>
How to clear python interpreter console? <p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
<p>As you mentioned, you can do a system call:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; clear = lambda: os.system('cls') &gt;&gt;&gt; clear() </code></pre> <p>I am not sure of any other way in Windows.</p>
Is JavaScript a pass-by-reference or pass-by-value language? <p>The primitive types (Number, String, etc.) are passed by value, but Objects are unknown, because they can be both passed-by-value (in case we consider that a variable holding an object is in fact a reference to the object) and passed-by-reference (when we consider that the variable to the object holds the object itself).</p> <p>Although it doesn't really matter at the end, I want to know what is the correct way to present the arguments passing conventions. Is there an excerpt from JavaScript specification, which defines what should be the semantics regarding this?</p>
<p>It's interesting in Javascript. Consider this example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function changeStuff(a, b, c) { a = a * 10; b.item = "changed"; c = {item: "changed"}; } var num = 10; var obj1 = {item: "unchanged"}; var obj2 = {item: "unchanged"}; changeStuff(num, obj1, obj2); console.log(num); console.log(obj1.item); console.log(obj2.item);</code></pre> </div> </div> </p> <p>This produces the output:</p> <pre><code>10 changed unchanged </code></pre> <p>If it was pure pass by value, then changing <code>obj1.item</code> would have no effect on the <code>obj1</code> outside of the function. If it was pure pass by reference, then everything would have changed. <code>num</code> would be <code>100</code>, and <code>obj2.item</code> would read <code>"changed"</code>.</p> <p>Instead, the situation is that the item passed in is passed by value. But the item that is passed by value is <em>itself</em> a reference. Technically, this is called <a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing">call-by-sharing</a>.</p> <p>In practical terms, this means that if you change the parameter itself (as with <code>num</code> and <code>obj2</code>), that won't affect the item that was fed into the parameter. But if you change the INTERNALS of the parameter, that will propagate back up (as with <code>obj1</code>).</p>
How to control the target frame of reporting services (SSRS) drill down <p>I am using SQL 2005 reporting services (SSRS) with the web report viewer control. It is showing the report inside an IFRAME on the web page. If I implement a drill down functionality, by attaching a URL action to a chart elements, the navigation will happen only inside the IFRAME. I know how to set the target frame for navigation on a normal HTML page. But in the report definition (RDL) I can't find any property to select the target frame. Any solution or workaround?</p>
<p>hmm it appparently didnt post my last reply. You might try adding the rc:LinkTarget querystring parameter to the IFRAME src. I use "&amp;rc:LinkTarget=_blank" on some charts displayed in an IFRAME and they open the full report correctly.</p> <p><a href="http://msdn.microsoft.com/en-us/magazine/cc188712.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/magazine/cc188712.aspx</a></p>
How can I set a form to have a transparent background <p>I am struggling to get my form to have a transparent background in vb.net </p> <p>Currently in the form New I set </p> <pre><code>Me.SetStyle(ControlStyles.SupportsTransparentBackColor, true) </code></pre> <p>But still the form shows up as having the default grey background</p> <p>Can anyone help??</p> <p>EDIT: I need the controls on the form to be visible so I don't think setting the opacity to 0 will work</p> <p>EDIT: I tried the transparency key solution but it doesn't work. I have a circular image with a black background. OnPaint I set the transparency key to the img pixel at 0,0, this then leaves me with circular image (which I want ) It hides the black background but I am still left with the default grey rectangle of the form. </p> <p>below is the code I have - </p> <pre><code>Public Sub New() Me.SetStyle(ControlStyles.SupportsTransparentBackColor, True) Me.BackColor = Color.Transparent ' This call is required by the Windows Form Designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. Me.Timer1.Start() End Sub Private Sub frmWoll_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint Dim img As Bitmap = CType(Me.BackgroundImage, Bitmap) img.MakeTransparent(img.GetPixel(2, 2)) Me.TransparencyKey = img.GetPixel(2, 2) End Sub </code></pre>
<p>Use TransparencyKey for transparent form.</p> <p>eg.</p> <pre><code>TransparencyKey = Color.Red Button1.BackColor = Color.Red </code></pre> <p>Now run the form you will find that the button1 has a hole in it.</p> <p>So using this method you can create a mask image in paint for which part has to be transparent and apply that image to form and voila the form is now transparent.</p> <p>Edit: Sorry for late reply.</p> <p><strong>Following is your code modified to suit your requirement</strong></p> <pre><code>Public Sub New() Me.SetStyle(ControlStyles.SupportsTransparentBackColor, True) Me.BackColor = Color.Transparent ' This call is required by the Windows Form Designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. Dim img As Bitmap = CType(Me.BackgroundImage, Bitmap) 'img.MakeTransparent(img.GetPixel(2, 2)) Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None Me.TransparencyKey = img.GetPixel(2, 2) End Sub </code></pre>
When is it time to have a QA department? <p>The Quality Assurance (QA) department is roughly a bunch of testers debunking your app(s) all day, giving the green light for releases, handling Alpha / Beta programs. And much more.</p> <p>But without a QA department in a software company, issues arises too often in the field, and problems costs more to fix. However, most companies starts in a garage, with 1 employee being yourself, and then grows into a software company.</p> <p>When do you tell it's to create such department ? Anything to do with the size of the company, the problems it encounters ? </p>
<p>As soon as you can afford it. You will never have a product which will be as reliable without a qa department than with one. Programmers don't make good QA people, and it is always better to have a second person (or more) reviewing how the app works.</p> <p>All good software companies, and organizations with a good IT departments which create programs have a qa team. It's vital to software development. </p>
Where is a good Address Parser <p>I'm looking for a good tool that can take a full mailing address, formatted for display or use with a mailing label, and convert it into a structured object.</p> <p>So for instance:</p> <pre><code>// Start with a formatted address in a single string string f = "18698 E. Main Street\r\nBig Town, AZ, 86011"; // Parse into address Address addr = new Address(f); addr.Street; // 18698 E. Main Street addr.Locality; // Big Town addr.Region; // AZ addr.PostalCode; // 86011 </code></pre> <p>Now I could do this using RegEx. But the tricky part is keeping it general enough to handle any address in the world!</p> <p>I'm sure there has to be something out there that can do it.</p> <p>If anyone noticed, this is actually the format of the <a href="http://code.google.com/apis/opensocial/docs/0.8/reference/#opensocial.Address">opensocial.address</a> object.</p>
<p>The Googlemaps API works pretty well for this. E.g., suppose you are given the string "120 w 45 st nyc". Pass it into the Googlemaps API like so: <code>http://maps.google.com/maps/geo?q=120+w+45+st+nyc</code> and you get this response:</p> <pre><code>{ "name": "120 w 45 st nyc", "Status": { "code": 200, "request": "geocode" }, "Placemark": [ { "id": "p1", "address": "120 W 45th St, New York, NY 10036, USA", "AddressDetails": {"Country": {"CountryNameCode": "US","CountryName": "USA","AdministrativeArea": {"AdministrativeAreaName": "NY","Locality": {"LocalityName": "New York","Thoroughfare":{"ThoroughfareName": "120 W 45th St"},"PostalCode": {"PostalCodeNumber": "10036"}}}},"Accuracy": 8}, "ExtendedData": { "LatLonBox": { "north": 40.7603883, "south": 40.7540931, "east": -73.9807141, "west": -73.9870093 } }, "Point": { "coordinates": [ -73.9838617, 40.7572407, 0 ] } } ] } </code></pre>
Possible to do a glow/shadow using partial transparency in HTML/CSS? <p>Well I guess this is a two part question.</p> <p>Firstly how can I make an image have partial transparency (I think you can do this with PNGs but don't know how -- I have photoshop just need instructions?)</p> <p>Secondly how do I use that image in a layout using CSS? I think I need some kind of "PNG Hack"</p>
<ol> <li>Create a new photoshop document</li> <li>Add new layers and draw on them</li> <li>Delete the layer named <em>Background</em></li> <li>File > Save for Web</li> <li>Choose a 24 bit PNG format.</li> </ol> <p>Getting it to work well in IE6 is going to be the issue. You should use a separate stylesheet that only ie6 loads via conditional comments that loads the backgorund image like this:</p> <pre><code>filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="my_trans_image.png", sizingMethod="crop"); </code></pre> <p>And in your standard style sheet use it like any other image:</p> <pre><code>background-image: url(/path/to/my_trans_image.png); </code></pre> <p>Load a stylesheet with IE6 specific rules in it like so:</p> <pre><code>&lt;!--[if lt IE 7]&gt; &lt;link rel="stylesheet" href="/css/ie6.css" type="text/css" charset="utf-8" /&gt; &lt;![endif]--&gt; </code></pre> <p>This will only load in IE and if the version is less than 7.</p> <p>Final note: IE6 is rapidly fading out. If you dont need to support IE6 then setting the PNG as a background image in plain old CSS will work in all modern browsers without any real problems.</p>
How do I control repeated Ajax 'post' submissions? <p>I do not want to stop the user from clicking the same ajax button many times, but I want to exercise some control to prevent someone from maliciously clicking the button repeatedly which would cause repeated database requests. What is simple way to handle this on a jquery .post in asp.net mvc? If I put in a time delay, the experience client side will be ruined (?) </p>
<p>Why not disable the button after it is clicked, and then re-enable it once you have received the response from the server?</p>
Google Adwords API 'getKeywordVariations' not working properly <p>I'm trying to use the 'GetKeywordVariations' method of the google adwords API, documentation at <a href="http://code.google.com/apis/adwords/docs/developer/KeywordToolService.html#getKeywordVariations" rel="nofollow">this page. According to the documentation, it should return these fields</a>, including lastMonthSearchVolume. When I try this, i get all the fields except for lastMonthSearchVolume. Does anyone know why?</p>
<p>I found the answer. i was using the older version of the API. Updating to the latest version fixed it .</p>
rotate a UIView around its center but several times <p>I'm trying to rotate some <code>UIView</code> around its center, so the simple code goes something like (in pseudocode):</p> <pre><code>[UIView beginAnimations:@"crazyRotate" context:nil]; [UIView setAnimationDuration:1.0]; someview.transform = CGAffineTransformMakeRotation(angle); [UIView commitAnimations] </code></pre> <p>now if I set angle to say M_PI/2 the thing rotates nicely. if I set it to 2*M_PI, well it does "nothing". I can understand that the matrix translates to something that does nothing (rotating 360 means "stay" in a sense), yet, I want to rotate it 5 times (think of a newspaper rotate scale coming at you effect -- I'm not great at describing, hope someone understands). So, I tried adding setting angle to 180 deg (M_PI) and add a nested <code>animatationBlock</code>. but I guess that since I'm setting the same property (<code>someview.transition</code>) again it ignores it somehow). I tried setting repeat count of the animation to 2 with angle M_PI but it seems to simply rotate 180, going back to straight position and then initiating the rotate again.</p> <p>So, I'm a little out of ideas, any help appreciated! --t</p>
<p>You can use the following animation on your UIView's layer property. I've tested it.</p> <pre><code>UIView *viewToSpin = ...; CABasicAnimation* spinAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; spinAnimation.toValue = [NSNumber numberWithFloat:5*2*M_PI]; [viewToSpin.layer addAnimation:spinAnimation forKey:@"spinAnimation"]; </code></pre>
C# Settings Rembering Settings <p>How do I get my program to remember the users settings?</p>
<p>You can either:</p> <ul> <li>write the settings to a file</li> <li><p>Create setting in VS with Project->Properties->Settings... then by using</p> <p>Properties.Settings.Default.SettingName = "something"; // Set setting</p> <p>this.Text = Properties.Settings.Default.SettingName; // Use setting</p></li> </ul>
Problem with simple full-text search on SQL Server 2005 <p>I just setup full-text search on my development database. I setup a new full-text index on a table and included 2 columns in the index. The first column is called 'description' and is a 'varchar(100)' and the other column is called 'notes' and is a 'text' column.</p> <p>I am trying to perform a simple search like this:</p> <pre><code>select * from myTable where freetext(description, 'another') </code></pre> <p>I know for sure that there is at least one row where the 'description' column contains the word 'another' as the first word. However, the search produces 0 results. Searching for other words seems to work fine.</p> <p>Also, when I setup my full-text index I told it to automatically update the index and to go ahead and build the index right away. The database hasn't changed at all since I did that.</p>
<p>SQL Server considers 'another' to be a stopword (noise word). So for all intents and purposes, it is ignored when performing a <code>FULLTEXT</code> search.</p> <p>See <code>C:\WINDOWS\system32\noise.eng</code> (that is where it is installed on my system) for a full list of noise/stop words.</p>
Select Users by Total Submissions <p>I know this is an easy one, but it's driving me nuts...</p> <p>I have a users table, comments table, and pictures table.</p> <p>I want a list of the top 10 users based on submissions (total of their comments and their submitted photos).</p> <p>That's it.</p> <p>Shame me.</p> <p><hr /></p> <p>UPDATE: based on Ed's answer.</p> <p>here's my setup:</p> <ul> <li>users table (user_id, username)</li> <li>images table (img_id, submittedby_id = users.user_id) </li> <li>comments table (id, submittedby_id = users.user_id)</li> </ul> <p>and the final query:</p> <pre><code> select submittedby_id, sum(total) from (select submittedby_id, count(img_id) as total from images group by submittedby_id union select submittedby_id, count(id) as total from comments group by submittedby_id ) as x group by submittedby_id order by sum(total) desc limit 10; </code></pre>
<p>Maybe something kind of like this:</p> <pre><code>select username, sum(submissions) from (select username, count(picture_id) from pictures group by username union select username, count(comment_id) from comments group by username ) group by username order by sum(submissions) desc limit 10; </code></pre> <p>To overview conceptually:</p> <ol> <li>Count the submissions of the user in each table</li> <li>Union those, so each user will have between 0 and 2 counts from the subquery.</li> <li>Group one more time, summing the two counts, and then order so that the highest amount is on top.</li> </ol> <p>Hope this helps.</p>
Make async event synchronous in JavaScript <p>I'm using the WPF 3.5SP1 WebBrowser control to display a page containing some javascript functions. My program then needs to invoke a javascript function which will make an asynchronous call. I need a way to get the result of that asynchronous call back to C# so I can process the result.</p> <p>Is there a way I can make the first javascript function sleep until something happens (with out locking up the browser)?</p> <p><strong>edit:</strong> I am already using a call back - the 2nd function is actually called "some-async-function-complete". It gets called when the async event finishes. Now I need a way to get the result into C#.</p> <p>For further clarification: C#</p> <pre><code>var result = WebBrowser.InvokeScript("myscript") </code></pre> <p>JavaScript</p> <pre><code>var result; function myscript() { some-async-function(); /* what goes here? */ /* wait until result != null */ return result; } function some-async-function-complete(retval) { result = retval; } </code></pre>
<blockquote> <p>Is there a way I can make the first javascript function sleep until something happens (with out locking up the browser)?</p> </blockquote> <p>Yes - you can use the asynchronous function as it was intended to be used: pass it a callback, and let it do its thing. You should be able to pass a callback from C# into your JS function, which can then either pass it to your asynchronous function directly, or wrap it in another function if post-processing is required.</p> <p><hr /></p> <p>An example of the implementation of a callback - this works with the WinForms WebBrowser control, i haven't tested it with WPF but they should be pretty much the same:</p> <pre><code>[System.Runtime.InteropServices.ComVisibleAttribute(true)] public class Callback { // allows an instance of Callback to look like a function to the script // (allows callback() rather than forcing the script to do callback.callMe) [System.Runtime.InteropServices.DispId(0)] public void callMe(string url) { // whatever you want to happen once the async process is complete } } </code></pre> <p>...</p> <pre><code>Callback cb = new Callback(); WebBrowser.InvokeScript("myscript", new object[] { cb }) </code></pre> <p>...</p> <pre><code>function myscript(callback) { some_async_function(function() { // script-specific completion code if ( callback ) callback(); }); } </code></pre>
Getting the status of a stream from FMS in ActionScript <p>I'm looking for a way to get the status of a stream from Flash Media Server to action script. I need to know if a stream has any publishers/listeners from flex/ActionScript.</p>
<p>Take a look at the Adobe Flash Media Server Administration API. There are calls that might help you, such as getNetStreams() and get NetStreamStats(). You could try writing a server-side action script class that makes these calls to the admin API, then pushes the results back to your Flex application through a callback on your NetConnection.</p>
Setting the width of a menu in the Windows API <p>I'm creating a custom control in wxWidgets that displays a menu as part of it, and currently working on the Windows side of things. wxWidgets doesn't have a way of setting the width of a menu. It just makes the window as wide as the longest string plus a few pixels on either side.</p> <p>In the API, there is a way to get the actual Windows API menu handle. Does the Windows API have a method of setting the width of a menu other than just calculating it on its own based on the width of the string?</p>
<p>With the handle of the menu, you can cycle through the menu items and call SetMenuItemInfo, indicating that you want to owner-draw the menu items. When you do this, the window that the menu is attached to will receive the <code>WM_MEASUREITEM</code> message, which you would then respond to by setting the dimensions required for the menu. It is here you can set your width.</p> <p>Of course, this means you have to subclass the windows message handler for the window that contains the menu.</p>
Compare subselect value with value in master select <p>In MS Access, I have a query where I want to use a column in the outer query as a condition in the inner query:</p> <pre><code>SELECT P.FirstName, P.LastName, Count(A.attendance_date) AS CountOfattendance_date, First(A.attendance_date) AS FirstOfattendance_date, (SELECT COUNT (*) FROM(SELECT DISTINCT attendance_date FROM tblEventAttendance AS B WHERE B.event_id=8 AND B.attendance_date &gt;= FirstOfattendance_date) ) AS total FROM tblPeople AS P INNER JOIN tblEventAttendance AS A ON P.ID = A.people_id WHERE A.event_id=8 GROUP BY P.FirstName, P.LastName ; </code></pre> <p>The key point is <code>FirstOfattendance_date</code> - I want the comparison deep in the subselect to use the value in each iteration of the master select. Obviously this doesn't work, it asks me for the value of <code>FirstOfattendance_date</code> when I try to run it.</p> <p>I'd like to do this without resorting to VB code... any ideas?</p>
<p>How about:</p> <pre><code>SELECT p.FirstName, p.LastName, Count(a.attendance_date) AS CountOfattendance_date, First(a.attendance_date) AS FirstOfattendance_date, c.total FROM ( tblPeople AS p INNER JOIN tblEventAttendance AS a ON a.people_id = p.ID) INNER JOIN (SELECT people_id, Count (attendance_date) As total FROM ( SELECT DISTINCT people_id,attendance_date FROM tblEventAttendance) Group By people_id) AS c ON p.ID = c.people_id GROUP BY p.ID, c.total; </code></pre>
Upgrade to 3.5 SP1 & 3.5 Family Update on client systems can break my code? <p>I have a server hosting a remoting application using .NET 3.5. It has been running fine. In the last couple of days I have had numerous reports of users not being able to access the application after running the "Microsoft .NET Framework 3.5 Service Pack 1 and .NET Framework 3.5 Family Update (KB951847) x86" update.</p> <p>I am tempted to run this update on the server - but don't want to cause any problems with my users that have not run this Windows Update. </p> <p>I can update my application, but I see from other questions on SO that this shouldn't be an issue - as my dev machine does not have SP1 on it, so the app is not using anything that is dependent on SP1.</p> <p>Any thoughts on what might be happening? </p>
<p>SP1 for .NET 3.5 includes bug fixes and a lot new functionality.<BR> From my experience upgrading from any of the frameworks .NET 2.0 SP1 to 3.0, 3.0 SP1, 3.5<BR> to any higher framework (up to 3.5 SP1 - haven't tried the 4.0 beta) does not break anything.<BR> In fact, .NET 3.5 SP1 is actually based on .NET 2.0 SP1 and adds functionality to it.</p>
How do I get a simple, Hello World Java applet to work in a browser in Mac OS X? <p>I'm using Java SE 1.6 on Mac OS X 10.5.6. The code for my applet is as follows:</p> <pre><code>import java.awt.Graphics; import javax.swing.JApplet; public class HelloWorld extends JApplet { public void paint( Graphics g ) { super.paint( g ); g.drawString( "Hello World!", 25, 25 ); } } </code></pre> <p>I compiled this to a <em>.class</em> file. The code for my HTML file is as follows:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Hello World&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;applet code="HelloWorld.class" height="300" width="300"&gt; Your browser is ignoring the applet tag. &lt;/applet&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>If I run the applet with <em>appletviewer</em>, it works fine. However, if I open the HTML file in a browser, a square appears for the applet space, but the applet doesn't load. (The "Your browser is ignoring the applet tag." doesn't appear either.) The browser status bar shows two messages: <strong>Applet HelloWorld notloaded</strong> and <strong>Loading Java Applet Failed...</strong> I tried the applet with Firefox 3.0.6, Safari 3.2.1, and Opera 9.6.3. None of them could load the applet.</p> <p>If I try opening the HTML for one of the Java demo applets in <em>/Developer/Examples/Java/Applets</em>, it loads fine in all three browsers.</p> <p>Is there something I'm missing here, in trying to get this simple applet to load in a browser?</p>
<p>You do not specify a codebase property in the applet tag, so I'd guess your class can not be found.</p> <p>Try to enable the java console output window. You can do this in "Java Settings" (use spotlight) under the extended options tab (the one with the tree and many checkboxes). Maybe you can see some more information (like ClassNotFoundException) there. Set the setting to "Enable/Show console". Then it should show up when you start the applet.</p>
How are web servers best loaded <p>If a web server is going to serve out say 100GB per day would it be better for it to do so in 10,000 10MB sessions or 200,000 500kB sessions.</p> <p>The reason for this question is I'm wondering if there would be any advantage, disadvantage or neither to sites that mirror content to allow clients to exploit HTTP's start-in-the-middle feature to download files in segments from many servers. (IIRC this is a little like bit torrent works) </p>
<p>I suppose that not only the size of the session matters, but the duration of it is very important. I would guess that 200,000 small sessions will live shorter than 10,000 big ones. As soon as a session is completed, resources are freed to be used again. I would optimize it so that a session lasts as short as possible.</p> <p>Have also in mind that a single server can't have more than a couple of hundred of sessions at the same time (100 - 200 is a safe number).</p>
C++ function that returns string doesn't work unless there's an endl involved...? <p>I've got a function inside of a class that returns a string. Inside this function, I can only get it to work when I add <code>cout&lt;&lt;endl</code> to the function before the return statement. Any idea why this is, or how I can fix it? I'm running this in Eclipse on a Mac</p> <p>In "main.cpp":</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;cstdlib&gt; #include "Braid.h" using namespace std; static int size=3; int main(){ Braid * b1 = new Braid(size); b1-&gt;setCanon();//creates canonical braid. cout&lt;&lt;"a "; cout&lt;&lt;b1-&gt;getName()&lt;&lt;endl; cout&lt;&lt;" b "; } </code></pre> <p>In "Braid.h" : </p> <pre><code> public: Braid(int); void setCanon(); string getName(); }; </code></pre> <p>And in "Braid.cpp": </p> <pre><code>string Braid::getName(){ string sName=""; /* body commented out for(int i=0; i&lt;height; i++) { for(int j=2; j&lt;(width-2); j++) { sName += boxes[i][j]; sName += "|"; } } */ //cout&lt;&lt;endl; return sName; } </code></pre> <p>When I run my main code, without the body of that function commented, the output I get is<br /> <strong>"a 0|0|12|12|0|0|2|1|1|1|1|2|"</strong> </p> <p>The "name" it returns is correct, but it's not making it past the function call. If I uncomment the <code>//cout&lt;&lt;endl</code> line, the function works and my output is<br /> <strong>"a 0|0|12|12|0|0|2|1|1|1|1|2|<br /> b "</strong></p> <p>After commenting out the body of the function, so that it only creates an empty string, and returns it, my output is only "a" then if I add the endl back, I get the "a b" that is expected.</p> <p>What am I doing wrong? Is there something that comes with endl that I'm missing?</p>
<p>actually <em>getName()</em> function is probably working correctly. However, the cout 'caches' the output (i.e. it prints the output on screen when it's internal text buffer is full). 'endl' flushes the buffer and forces cout to dump the text (in cache) to screen. </p> <p>Try cout.flush() in main.cpp</p>
Beginner's guide to 3D graphics programming <p>What are the best guides / tutorials / books / websites for someone with minimal experience (or none) in the world of 3D graphics programming?</p> <p>I realize that the fundamentals of 3D graphics and mathematics apply across platform specific 3D library implementations such as OpenGL, DirectX, WPF etc..</p> <p>Therefore it would be useful if answers would explain if they focus on a specific library implementation, on the fundamentals, or maybe both.</p> <p>Rationale for for asking this question: </p> <p>With Windows Presentation Foundation (WPF) 3D on the scene, it's realistic for many programmers to now seriously consider using 3D for their applications, where this would have been almost impossible even a few years ago. </p> <p>I'm sure there are many programmers out there, like me, who find the leap from 2D to 3D a very big one.</p>
<p>I recommend that you implement a simple software based 3d rendering engine. Simple stuff like line, quads, lighting etc. You will learn a whole lot more about 3d programming in general, and it will give you a good prescriptive on 3d graphics and it's limitations.</p> <p>This should get you started: <a href="http://www.devmaster.net/articles/software-rendering/part1.php">http://www.devmaster.net/articles/software-rendering/part1.php</a></p>
MSSQL Paging is returning random rows when not supposed too <p>I'm trying to do some basic paging in MSSQL. The problem I'm having is that I'm sorting the paging on a row that (potentially) has similar values, and the ORDER BY clause is returning "random" results, which doesn't work well.</p> <p>So for example.</p> <p>If I have three rows, and I'm sorting them by a "rating", and all of the ratings are = '5' - the rows will seemingly "randomly" order themselves. How do I make it so the rows are showing up in the same order everytime?</p> <p>I tried ordering it by a datetime that the field was last edited, but the "rating" is sorted in reverse, and again, does not work how i expect it to work.</p> <p>Here is the SQL I'm using thus far. I know it's sort of confusing without the data so.. any help would be greatful.</p> <pre><code>SELECT * FROM ( SELECT CAST(grg.defaultthumbid AS VARCHAR) + '_' + CAST(grg.garageid AS VARCHAR) AS imagename, ( SELECT COUNT(imageid) FROM dbo.images im (nolock) WHERE im.garageid = grg.garageid ) AS piccount, ( SELECT COUNT(commentid) FROM dbo.comments cmt (nolock) WHERE cmt.garageid = grg.garageid ) AS commentcount, grg.GarageID, mk.make, mdl.model, grg.year, typ.type, usr.username, grg.content, grg.rating, grg.DateEdit as DateEdit, ROW_NUMBER() OVER (ORDER BY Rating DESC) As RowIndex FROM dbo.garage grg (nolock) LEFT JOIN dbo.users (nolock) AS usr ON (grg.userid = usr.userid) LEFT JOIN dbo.make (nolock) AS mk ON (grg.makeid = mk.makeid) LEFT JOIN dbo.type (nolock) AS typ ON (typ.typeid = mk.typeid) LEFT JOIN dbo.model (nolock) AS mdl ON (grg.modelid = mdl.modelid) WHERE typ.type = 'Automobile' AND grg.defaultthumbid != 0 AND usr.username IS NOT NULL ) As QueryResults WHERE RowIndex BETWEEN (2 - 1) * 25 + 2 AND 2 * 25 ORDER BY DateEdit DESC </code></pre>
<p>Try ordering by both, e.g.: ORDER BY Rating DESC, DateEdit ASC</p>
Find the path of notepad.exe and mspaint.exe <p>What is the best way to find out where notepad.exe and mspaint.exe are that will work across various versions of Windows?</p> <p>Should I get the Windows directory via <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb762181(v=vs.85).aspx" rel="nofollow"><code>SHGetFolderPath(NULL, CSIDL_WINDOWS, NULL, SHGFP_TYPE_CURRENT, dir)</code></a>, and then traverse through all the subdirectories to look for the two files?</p> <p>(Assume that I am not interested in anything outside the Windows folder.)</p>
<p>This works on every Windows box I've got access to (XP+).</p> <pre><code>c:\&gt; for %i in (cmd.exe) do @echo %~$PATH:i C:\WINDOWS\system32\cmd.exe c:\&gt; for %i in (python.exe) do @echo %~$PATH:i C:\Python25\python.exe </code></pre> <p>The great thing is, you don't <em>have</em> to use the actual <code>%PATH%</code>, you can substitute your own search path by using a different environment variable.</p>
Difference between static class and singleton pattern? <p>What real (i.e. practical) difference exists between a static class and a singleton pattern?</p> <p>Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?</p>
<p>What makes you say that either a singleton or a static method isn't thread-safe? Usually both <em>should</em> be implemented to be thread-safe.</p> <p>The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.</p>
X connection to localhost:10.0 broken (explicit kill or server shutdown) <p>why is this error comes. I started the jboss server and when i try to open the application in IE i am getting this error</p>
<p>I just had this exact problem because I was connected to my linux jboss server with putty and X forwarding activated. In putty, I unchecked the option "Connection > SSH > X11 > Enable X11 forwarding" and now it works. Hope this will help someone.</p>
Is it possible to pass a method as an argument in Objective-C? <p>I have a method that varies by a single method call inside, and I'd like to pass the method/signature of the method that it varies by as an argument... is this possible in Objective C or is that too much to hope for?</p>
<p>NSInvocation is a class for wrapping up a method calls in an object. You can set a selector (method signature), set arguments by index. You can then set a target and call invoke to trigger the call, or leave the target unset and use invokeWithTarget: in a loop of some sort to call this on many objects.</p> <p>I think it works a little like this:</p> <pre><code>NSInvocation *inv = [[NSInvocation alloc] init]; [inv setSelector:@selector(foo:bar:)]; [inv setArgument:123 atIndex:0]; [inv setArgument:456 atIndex:1]; for (MyClass *myObj in myObjects) { [inv invokeWithTarget:myObj]; } </code></pre> <p>Or if you dont want to pass invocation objects into this method you can use the SEL type to accept a selector (method signature).</p> <pre><code>-(void)fooWithMethod:(SEL)selector; </code></pre> <p><em>Then</em> assign the selector to an invocation object in order to call it on objects.</p>
Regular Exp instead of string split <p>hi I had an exam two days before one of the questions was to replace the letters before the @ with a new names</p> <p>so in the exam paper the we had array = "toto@yahoo.com","mimi@yahoo.com".soso@yahoo.com" so we sholud take the toto mimi soso and replace them with diffrent names what i did is to split the string and take the first four letters and thank god i got the mark .</p> <p>I was thinking what if the number of letters befor the @ was not fixed what other ways i can do ? Reg Exp or is there a diffrent way.</p>
<p>You could use RegEx or you could do string manipulation based on Substring, IndexOf and concatenation. </p>
How can I play a youtube video in swfloader? <p>I embed a youtube video in my air application. It loaded and played well, but I cannot play more than one video at the time, only one video is played at the time, do you know why? The code is:</p> <pre><code>url:String = "http://in.youtube.com/v/fVGk5qm6Mac&amp;hl=en&amp;fs=1"; //texturl.text=url; swfloader.load(url) </code></pre>
<p>I'm not sure, but I guess that if you create separate SWFLoader instances for each video you want to play, it shouldn't be a problem. It's hard to tell from the code you provide if you are using 1 or more SWFLoader objects.</p>
Keeping same session with different user-agents <p>Is there a way to use the same session on different user-agents. I have a flash app that is generating a new session id on posting data to myHandler.ashx ( same happens on aspx ). Am i missing a trick here?</p>
<p>I have no experience from c# or anything like that, but when doing remoting using amfphp you will sometimes need to supply the session_id variable in your call manually, as the server will for some reason consider you two different users even though it's all going through the same browser. </p> <p>Often, the simplest way to do this is to supply your swf with the id in a flashvar when loading it. This will require you to print the session_id in the html source, which isn't ideal, but it's not that big of a deal since it can be sniffed very easily anyway.</p>
Does anybody actually use the PSP (Personal Software Process)? <p>I've been reading a bit about this recently but it looks to be a bit heavy. Does anybody have real world experience using it?</p> <p>Are there any light weight alternatives?</p>
<p>The Personal Software Process is a personal improvement process. The full-blown PSP is quite heavy and there are several forms, templates, and documents associated with it. However, a key point is that you are supposed to tailor the PSP to your specific needs.</p> <p>Typically, when you are learning about the PSP (especially if you are learning it in a course), you will use the full PSP with all of its forms. However, as Watts S. Humphrey says in "PSP: A Self-Improvement Process for Software Engineers", it's important to "use a process that both works for you and produces the desired results". Even for an individual, multiple projects will probably require variations on the process in order to achieve the results you want to.</p> <p>In the book I mentioned above, "PSP: A Self Improvement Process for Software Engineers", the steps that you should follow when defining your own process are:</p> <ul> <li>Determine needs and priorities</li> <li>Define objectives, goals, and quality criteria</li> <li>Characterize the current process</li> <li>Characterize the target process</li> <li>Establish a strategy to develop the process</li> <li>Validate the process</li> <li>Enhance the process</li> </ul> <p>If you are familiar with several process models, it should be fairly easy to take pieces from all of them and create a process or workflow that works on your particular project. If you want more advice, I would suggest picking up the book. There's an entire chapter dedicated to extending and modifying the PSP as well as creating your own process.</p>
ASP.NET AJAX - Check for async postback via JavaScript <p>Does anyone know the script necessary to check to see if you are in a anync postback via JavaScript?</p> <p>Thanks.</p>
<p>In the end I used the following which gave me the functionality I required:</p> <p>Sys.WebForms.PageRequestManager.getInstance()._postBackSettings.async</p>
Newsletter: How is it possible to determine how many people opened the e-mail? <p><strong>Exact duplicate of <a href="http://stackoverflow.com/questions/185204/is-there-a-way-to-determine-whether-an-e-mail-reaches-its-destination">http://stackoverflow.com/questions/185204/is-there-a-way-to-determine-whether-an-e-mail-reaches-its-destination</a></strong></p> <p>Hi all,</p> <p>I heard that it's possible to determine how many people opened a newsletter and analyze WHEN they opened the mail.</p> <p>I just wanted to know how that's possible... is it necessary to generate a "read confirmation" or is such an analysis possible without letting the recipient know?</p> <p>Thanks a lot for your input...</p>
<p>See also <a href="http://stackoverflow.com/questions/185204/is-there-a-way-to-determine-whether-an-e-mail-reaches-its-destination">Is there a way to determine whether an e-mail reaches its destination?</a>, my answer repeated below:</p> <blockquote> <p>If you make the email HTML based, you can include images in it which contain URLs with information unique to the recipient. You could structure your application so that these URLs trigger some code to mark that particular email as read before returning the required image data.</p> <p>To be totally effective, the images would have to form a key part of the email, so that the recipient has to make their email client grab the images. You could also make the plain text part of the email just contain a URL to retrieve the full message, again allowing you to track receipt.</p> <p><em>How far you take these ideas depends on why you need to know it's been read and to what extent you want to potentially annoy the recipient with an email they can't cut'n'paste, read easily on mobile device, listen to with a screenreader, etc...</em></p> </blockquote>
Network Programming: to maintain sockets or not? <p>I'm currently translating an API from C# to Java which has a network component.</p> <p>The C# version seems to keep the input and output streams and the socket open for the duration of its classes being used.</p> <p>Is this correct?</p> <p>Bearing in mind that the application is sending commands and receiving events based on user input, is it more sensible to open a new socket stream for each "message"?</p> <p>I'm maintaining a ServerSocket for listening to the server throwing events but I'm not so sure that maintaining a Socket and output stream for outbound comms is such a good idea.</p> <p>I'm not really used to Socket programming. As with many developers I usually work at the application layer when I need to do networking and not at the socket layer, and it's been 5 or 6 years since I did this stuff at university.</p> <p>Cheers for the help. I guess this is more asking for advice than for a definitive answer.</p>
<p>There is a trade off between the cost of keeping the connections open and the cost of creating those connections.</p> <p><strong>Creating connections</strong> costs time and bandwidth. You have to do the 3-way TCP handshake, launch a new server thread, ...</p> <p><strong>Keeping connections open</strong> costs mainly memory and connections. Network connections are a resource limited by the OS. If you have too many clients connected, you might run out of available connections. It will cost memory as you will have one thread open for each connection, with its associated state.</p> <p>The right balanced will be different based on the usage you expect. If you have a lot of clients connecting for short period of times, it's probably gonna be more efficient to close the connections. If you have few clients connecting for long period of time, you should probably keep the connections open ...</p>
How to assign alt + f1 key to an opened Windows application <p>I usually have more then 10 opened application windows. When I write code I need to switch fast between a browser, an IDE and terminal windows. Alt + tab is too slow, too many windows to choose from.</p> <p>Virtual desktop is a work around for me. On a first desktop I keep browser, on a second IDE, etc. So I am able to switch fast between my most important applications.</p> <p>And the question. Is there an utility for Windows XP / Vista which allows to assign a keyboard shortcut like alt + f1 .. f10 to an opened application window? </p> <p>UPDATE: All programs I've found allow to define a shortcut to an application. E.g. they will open new instance of Firefox instead of switch to an opened one. Closest to what I need is <a href="http://insentient.net/" rel="nofollow">Switcher</a>. It displays big thumbnails of all open windows with assigned numbers to press.</p>
<p><a href="http://www.autohotkey.com/" rel="nofollow">Autohotkey</a> I've found to be very powerful. Here is a part of my test script.</p> <pre><code>SetTitleMatchMode, 2 #z::Run http://stackoverflow.com/ ^!n:: IfWinExist Notepad WinActivate else Run Notepad return !F1:: IfWinExist Firefox WinActivate else Run Firefox return !F2:: IfWinExist Commander WinActivate return !F3:: IfWinExist Carbide WinActivate return </code></pre>
screen scraping technique using php <p>How to screen scrape a particular website. I need to log in to a website and then scrape the inner information. How could this be done? </p> <p>Please guide me. </p> <p><strong>Duplicate: <a href="http://stackoverflow.com/questions/26947/how-to-implement-a-web-scraper-in-php">How to implement a web scraper in PHP?</a></strong></p>
<pre><code>Zend_Http_Client and Zend_Dom_Query </code></pre>
DQL return files in a Cabinet <p>Using DQL I want to return all the documents under the Cabinet <em>test</em>. How would I go about writing a query to do this?</p>
<pre><code>select r_object_id, object_name from dm_document(all) where folder('/NameOfCabinet', descend); </code></pre>
Why is there no Linq method to return distinct values by a predicate? <p>I want to get the distinct values in a list, but not by the standard equality comparison.</p> <p>What I want to do is something like this:</p> <pre><code>return myList.Distinct( (x, y) =&gt; x.Url == y.Url ); </code></pre> <p>I can't, there's no extension method in Linq that will do this - just one that takes an <code>IEqualityComparer</code>.</p> <p>I can hack around it with this:</p> <pre><code>return myList.GroupBy( x =&gt; x.Url ).Select( g =&gt; g.First() ); </code></pre> <p>But that seems messy. It also doesn't quite do the same thing - I can only use it here because I have a single key.</p> <p>I could also add my own:</p> <pre><code>public static IEnumerable&lt;T&gt; Distinct&lt;T&gt;( this IEnumerable&lt;T&gt; input, Func&lt;T,T,bool&gt; compare ) { //write my own here } </code></pre> <p>But that does seem rather like writing something that should be there in the first place.</p> <p>Anyone know why this method isn't there?</p> <p>Am I missing something?</p>
<p>It's annoying, certainly. It's also part of my "MoreLINQ" project which I must pay some attention to at some point :) There are plenty of other operations which make sense when acting on a projection, but returning the original - MaxBy and MinBy spring to mind.</p> <p>As you say, it's easy to write - although I prefer the name "DistinctBy" to match OrderBy etc. Here's my implementation if you're interested:</p> <pre><code> public static IEnumerable&lt;TSource&gt; DistinctBy&lt;TSource, TKey&gt; (this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector) { return source.DistinctBy(keySelector, EqualityComparer&lt;TKey&gt;.Default); } public static IEnumerable&lt;TSource&gt; DistinctBy&lt;TSource, TKey&gt; (this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector, IEqualityComparer&lt;TKey&gt; comparer) { if (source == null) { throw new ArgumentNullException("source"); } if (keySelector == null) { throw new ArgumentNullException("keySelector"); } if (comparer == null) { throw new ArgumentNullException("comparer"); } return DistinctByImpl(source, keySelector, comparer); } private static IEnumerable&lt;TSource&gt; DistinctByImpl&lt;TSource, TKey&gt; (IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector, IEqualityComparer&lt;TKey&gt; comparer) { HashSet&lt;TKey&gt; knownKeys = new HashSet&lt;TKey&gt;(comparer); foreach (TSource element in source) { if (knownKeys.Add(keySelector(element))) { yield return element; } } } </code></pre>
script to save file as unicode <p>Do you know any way that I could programmatically or via scrirpt transform a set of text files saved in ansi character encoding, to unicode encoding?</p> <p>I would like to do the same as I do when I open the file with notepad and choose to save it as an unicode file.</p>
<p>This could work for you, but notice that it'll grab <strong>every</strong> file in the current folder:</p> <pre><code> Get-ChildItem | Foreach-Object { $c = (Get-Content $_); ` Set-Content -Encoding UTF8 $c -Path ($_.name + "u") } </code></pre> <p>Same thing using aliases for brevity:</p> <pre><code> gci | %{ $c = (gc $_); sc -Encoding UTF8 $c -Path ($_.name + "u") } </code></pre> <p><a href="#520433">Steven Murawski</a> suggests using <code>Out-File</code> instead. The differences between both cmdlets are the following:</p> <ul> <li><code>Out-File</code> will attempt to format the input it receives.</li> <li><code>Out-File</code>'s default encoding is Unicode-based, whereas <code>Set-Content</code> uses the system's default.</li> </ul> <p>Here's an example assuming the file <code>test.txt</code> doesn't exist in either case:</p> <pre><code> PS> [system.string] | Out-File test.txt PS> Get-Content test.txt IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object # test.txt encoding is Unicode-based with BOM </code></pre> <pre><code> PS> [system.string] | Set-Content test.txt PS> Get-Content test.txt System.String # test.txt encoding is "ANSI" (Windows character set) </code></pre> <p>In fact, if you don't need any specific Unicode encoding, you could as well do the following to convert a text file to Unicode:</p> <pre><code> PS> Get-Content sourceASCII.txt > targetUnicode.txt </code></pre> <p><code>Out-File</code> is a "redirection operator with optional parameters" of sorts.</p>
How to handle null objects in XML coming from SQL Server? <p>I have a stored procedure that returns an object as XML. How do I handle the case where the object doesn't exist?</p> <p>I can't return null or empty string as the XmlReader complains that it is not valid XML.</p> <p>If I return an empty Tag, how do I tell if it is just an empty object or no object?</p>
<p>Well, a common approach is some marker attribute, such as <code>xsi:nil="true"</code> (although this is just an example).</p>
In XAML style, how to change solid background to gradient? <p>I've got a MainResources.xaml file in which I have a style that defines how each of my windows in my application look:</p> <pre><code> &lt;Style x:Key="MainBorderStyle" TargetType="{x:Type Border}"&gt; &lt;Setter Property="Background" Value="WhiteSmoke" /&gt; &lt;Setter Property="BorderBrush" Value="LightGray" /&gt; &lt;Setter Property="BorderThickness" Value="1" /&gt; &lt;Setter Property="CornerRadius" Value="5" /&gt; &lt;Setter Property="SnapsToDevicePixels" Value="True" /&gt; &lt;/Style&gt; </code></pre> <p>Instead of "WhiteSmoke" I want my background to be this gradient:</p> <pre><code> &lt;LinearGradientBrush&gt; &lt;GradientStop Color="#ccc" Offset="0"/&gt; &lt;GradientStop Color="#bbb" Offset="1"/&gt; &lt;/LinearGradientBrush&gt; </code></pre> <p>But the following attempt causes VS2008 to tell me "Style setters do not support child elements":</p> <pre><code>&lt;Style x:Key="MainBorderStyle" TargetType="{x:Type Border}"&gt; &lt;Setter Property="Background"&gt; &lt;LinearGradientBrush&gt; &lt;GradientStop Color="#ccc" Offset="0"/&gt; &lt;GradientStop Color="#bbb" Offset="1"/&gt; &lt;/LinearGradientBrush&gt; &lt;/Setter&gt; &lt;Setter Property="BorderBrush" Value="LightGray" /&gt; &lt;Setter Property="BorderThickness" Value="1" /&gt; &lt;Setter Property="CornerRadius" Value="5" /&gt; &lt;Setter Property="SnapsToDevicePixels" Value="True" /&gt; &lt;/Style&gt; </code></pre> <p>What is the correct way to put a gradient color as the background for this style?</p>
<p>You are missing the <code>&lt;Setter.Value&gt;</code></p> <pre><code>&lt;Style ...&gt; &lt;Setter Property="..."&gt; &lt;Setter.Value&gt; &lt;LinearGradientBrush /&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre>
Where is Python used? I read about it a lot on Reddit <p>I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.</p>
<p>Everywhere. It's used <a href="http://panela.blog-city.com/python_at_google_greg_stein__sdforum.htm">extensively by google</a> for one.</p> <p>See <a href="http://en.wikipedia.org/wiki/Python_software">list of python software</a> for more info, and also <a href="http://www.python.org/doc/essays/ppt/www8-py-www/sld010.htm">who uses python on the web?</a></p>
Disable messages in SQL2008 result set <p>further to <a href="http://stackoverflow.com/questions/483787/is-there-a-bug-in-sqldatareader-hasrows-when-running-against-sql-server-2008" rel="nofollow" title="these">these</a> <a href="http://stackoverflow.com/questions/197220/sqldatareader-hasrows-returns-false-since-sql-2008-upgrade">two</a> questions, is there a way to disable the messages that may get sent along with the resultset in SQL2008?</p> <p>(please note this is nothing to do with the ANSI_WARNINGS setting. <strong>Or NOCOUNT</strong>.)</p> <p>Thanks for any help.</p> <p>Edit: It's not a problem with compatibility settings or table owners. <strong>And it's nothing to do with NOCOUNT</strong>. Trust me.</p>
<p>No, there's not a way to disable all messages that get sent along with the result sets. Set nocount on/off doesn't have an effect on these types of messages.</p>
jQuery If DIV Doesn't Have Class "x" <p>In jQuery I need to do an if statement to see if $this doesn't contain the class '.selected'.</p> <pre><code>$(".thumbs").hover(function(){ $(this).stop().fadeTo("normal", 1.0); },function(){ $(this).stop().fadeTo("slow", 0.3); }); </code></pre> <p>Basically when this function is run (on hover) I don't want to perform the fades if the class '.selected' has been appended to the div, this will mean that the image will be at full opacity to signify that it's selected. Searched on Google to no luck even though it's a simple question of how to use an IF statement...</p>
<p>Use the <a href="http://docs.jquery.com/Selectors/not#selector">"not</a>" selector.</p> <p>For example, instead of:</p> <p><code>$(".thumbs").hover()</code></p> <p>try:</p> <p><code>$(".thumbs:not(.selected)").hover()</code></p>
.NET assemblies spanning multiple files and unit testing <p>Can anyone point me to some information on .NET assemblies spanning multiple files?</p> <p>I've found this remark on MSDN (<a href="http://msdn.microsoft.com/en-us/library/ms973231.aspx#assenamesp_topic4" rel="nofollow">here</a>):</p> <blockquote> <p>Although it's technically possible to create assemblies that span multiple files, you're not likely to use this technology in most situations.</p> </blockquote> <p>I'm asking because I have the business logic and the unit tests for it in separate projects, and I'd like to test some internal classes (which are not accessible from the unit tests) - so I thought I'd try and merge the two into a single assembly.</p>
<p>You can friend two assemblies together. Then one can see the "internal" in the other. Still can't see private.</p> <p>MSDN - <a href="http://msdn.microsoft.com/en-us/library/0tke9fxk(VS.80).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/0tke9fxk(VS.80).aspx</a></p>
How can I get the default value of a type in a non-generic way? <p>I know the "default" keyword returns the default value of a statically determined type, as shown for instance in <a href="http://stackoverflow.com/questions/367378/returning-a-default-value-c">this question</a>.</p> <p>However, given an instance of a type, is there a simple way to get the default value of this type, dynamically ? The only way I found while googling is <a href="http://weblogs.asp.net/avnerk/archive/2006/05/21/Non_2D00_generic-default-values-in-C_23003F00_-Why-not_3F002100_.aspx" rel="nofollow">this</a> :</p> <pre><code>static object DefaultValue(Type myType) { if (!myType.IsValueType) return null; else return Activator.CreateInstance(myType); } </code></pre> <p>But I'd like to avoid the Activator class if possible.</p>
<p>Why do you want to avoid Activator? Basically that <em>is</em> the way of doing it.</p> <p>I mean, you could write a generic method and then call that via reflection, but that's a pretty hideous "long cut" just to avoid Activator.</p>
Is there a downloadable document available that encapsulates the core rules enforced by StyleCop? <p>Is there a downloadable document available that encapsulates the core rules enforced by StyleCop? </p> <p>We've settled on C#, and we're going to be using FxCop and StyleCop to enforce design and style guidelines. To help get folks ramped up to speed, we'd like to make sure they have printed versions of the reference materials on hand as <em>casual reading material,</em> so I was hoping that there were PDF versions of the rules references around.</p> <p>My searches so far for the StyleCop rules reference have been fruitless. If anyone knows if these rules are available as a consolidated document (either as PDF, XPS, or some other single downloadable reference), I'd very much appreciate it.</p>
<p>The rule list is available as a <a href="http://en.wikipedia.org/wiki/HTML_help" rel="nofollow">.chm</a> file on codeplex: <a href="http://code.msdn.microsoft.com/sourceanalysis/Release/ProjectReleases.aspx?ReleaseId=1425" rel="nofollow">StyleCop 4.3 Rules Documentation</a> </p>
How can I determine property types using reflection? <p>How would I test a property of a type to see if it is a specified type?</p> <p>EDIT: My goal is to examine an assembly to see if any of the types in that assembly contain properties that are MyType (or inherited from MyType).</p> <p>Here is the track I've gone down...</p> <pre><code>AssemblyName n = new AssemblyName(); n.CodeBase = "file://" + dllName; Assembly a = AppDomain.CurrentDomain.Load(n); foreach (Type t in a.GetTypes()) foreach (PropertyInfo pi in t.GetProperties()) if ( pi.PropertyType is MyType ) // warning CS0184 Console.WriteLine("Found a property that is MyType"); </code></pre> <p>This compiles with warning CS0184: The given expression is never of the provided ('MyType') type</p>
<p>What type are you interested in? The return type of the method/property/event etc?</p> <p>If so, I don't think there's anything in <code>MemberInfo</code> to let you get at it directly - you'll need to cast and use <code>MethodInfo.ReturnType</code>, <code>PropertyInfo.PropertyType</code>, <code>FieldInfo.FieldType</code>, <code>EventInfo.EventHandlerType</code> and any others I've forgotten. (Remember that types themselves can be members. Not sure what you'll want to do with them!)</p> <p>EDIT: If you're interested in whether a specific Type represents either MyType or some subclass, then use <a href="http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx">Type.IsAssignableFrom</a>:</p> <pre><code>if (typeof(MyType).IsAssignableFrom(type)) </code></pre> <p>EDIT: Now that we know you want properties, it's easy - use GetProperties instead of GetMembers. I like doing reflection with LINQ:</p> <pre><code>var query = from type in assembly.GetTypes() from property in type.GetProperties() where typeof(MyType).IsAssignableFrom(property.PropertyType) select new { Type=type, Property=property }; foreach (var entry in query) { Console.WriteLine(entry); } </code></pre> <p>If you're not a fan of LINQ:</p> <pre><code>foreach (Type t in a.GetTypes()) foreach (PropertyInfo pi in t.GetProperties()) if (typeof(MyType).IsAssignableFrom(pi.PropertyType)) Console.WriteLine("Found a property that is MyType"); </code></pre> <p>Note that you might want to specify binding flags to get non-public properties etc.</p>
Hook application with .NET to capture double click events <p>How can I hook an application so that I can find out when the mouse is double clicked within it?</p> <p>Can this be done in .NET?</p> <p>Are there anythings I should be careful about? (crashing the other application, for instance)</p>
<p>The article "<a href="http://www.codingthewheel.com/archives/how-to-inject-a-managed-assembly-dll" rel="nofollow">How to inject a managed .NET assembly into a managed process</a>" will give you all you need to know to set the hook.</p> <p>The article "<a href="http://www.codingthewheel.com/archives/how-i-built-a-working-online-poker-bot-4" rel="nofollow">How I Built a Working Poker Bot: Part 4</a>" will give you all you need for capturing the double clicks. </p> <p>The code for both articles can be fairly domain specific, but you shouldn't have much trouble pulling out the golden nuggets to get up and running.</p>
Will there ever be a solution for global events in .NET applications <p>In our program we use Microsoft's UserActivityHook.dll to determine when a user of our Windows Forms app has been idle for more than X seconds. This allows us to replicate an 'auto-away' behavior much like MSN/Live Messanger when there has been no keyboard or mouse events after a certain amount of time.</p> <p>Ive always wondered why .NET (to my knowledge) has not implemented a way to interact with such global events. It seems that the FileSystemWatcher class is similar, in that it notifies the program of file changes that occur outside the program, why not a similar function for mouse/keyboard events?</p>
<p>You may consider the library provided in this article.</p> <p><a href="http://www.codeproject.com/KB/cs/globalhook.aspx?display=PrintAll&amp;fid=57596&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2857159" rel="nofollow">http://www.codeproject.com/KB/cs/globalhook.aspx?display=PrintAll&amp;fid=57596&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2857159</a></p>
Return background color of selected cell <p>I have a spreadsheet which cells in are colored meaningfully.</p> <p>Does any body know how i can return the background color value of a current cell in Excel sheet?</p>
<p>You can use <code>Cell.Interior.Color</code>, I've used it to count the number of cells in a range that have a given background color (ie. matching my legend).</p>
T-SQL 2005: Suppress the output of the results set <p>I have some stored procedures which are used for generating Reports. I am trying to build a report dashboard that will show how many records are on each report.</p> <p>The SPs are detailed in a table which details in which order they should be run.</p> <p>I have a dashboard SP in which I am using Cursor to go through the database table, execute each report SP and then saving the @@rowcount into a temp table which forms the basis of the dashboard.</p> <p>I can turn off the row count using set rowcoun off at the top of each SP, but I can't find a way to stop the results set being retured from the EXEC sp_my_sp command.</p> <p><PRE> WHILE @@FETCH_STATUS = 0 BEGIN declare @x as int exec @SP_name @x OUT select @x insert into @results (Short___name,Records) values (@shortname,@x) FETCH NEXT FROM myCursor INTO @ShortName, @SP_Name,@Group,@Order END </PRE></p> <p>Somewhere in there I need to suppress or redirect the output. I don't want to do it inside the actual report SP.</p> <p>The only solution I have come up with so far is to add an input parameter to each SP to say whether it is being run for the dashboard or for the report. Instead of returning the results set directly, insert it into an in-memory table and and then report the in-memory table <B>ONLY</B> if we are running for reports - not nice as someone has to remember to do it for each new SP</p> <p>TIA</p> <p>Obiron</p>
<p>I can think of one possible solution but I'm not sure if it's particularly elegant (or what you're looking for).</p> <p>Expanding on the idea of an input parameter to the SP, could you not just add some logic (CASE or IF statement) to call a Select Count() over the script when it comes from the dashboard?</p> <p>It would need adding to each SP but as long as it's documented it shouldn't cause too many problems for future developers.</p>
Classic database insert problem <p>I have a SQL database which i use to store some info and every record has a unique id generated by the database. MY program is written in flash and runs over the web, the program runs fine and it inserts records into the database and pulls the idnumber of the last record and displays it for user, my question is though how do i handle multiple concurrent entries because the program will be used by multiple users and chances are there will be concurrent inserts into the database so how would i be able to identify the correct unique id numbers for users</p> <p>here is the code for inserting into the database</p> <pre><code>$query = "INSERT into $tablename (grade,school,country) VALUES ('$datarray[0]','$datarray[1]','$datarray[2]')"; $result = mysql_query($query) or die("no rows selected"); </code></pre> <p>and after that i load another php file on the second in my flash file to pull the id for that record and display it here is the code</p> <pre><code>$query = "SELECT max(id) from $tablename"; $result = mysql_query($query) or die("no rows selected"); $row = mysql_fetch_array($result); // extracts one row echo "id=$row[0]"; </code></pre> <p>what do i need to do to get the correct id for that record?</p>
<p>PHP has <a href="http://us3.php.net/manual/en/function.mysql-insert-id.php" rel="nofollow"><code>mysql_insert_id()</code></a> to return </p> <blockquote> <p>The ID generated for an <code>AUTO_INCREMENT</code> column by the previous INSERT query on success, 0 if the previous query does not generate an <code>AUTO_INCREMENT</code> value, or <code>FALSE</code> if no MySQL connection was established.</p> </blockquote>
Google's Imageless Buttons <p>There have been a few articles recently about Google's new imageless buttons:</p> <ul> <li><a href="http://stopdesign.com/archive/2009/02/04/recreating-the-button.html">http://stopdesign.com/archive/2009/02/04/recreating-the-button.html</a></li> <li><a href="http://stopdesign.com/eg/buttons/3.0/code.html">http://stopdesign.com/eg/buttons/3.0/code.html</a></li> <li><a href="http://stopdesign.com/eg/buttons/3.1/code.html">http://stopdesign.com/eg/buttons/3.1/code.html</a></li> <li><a href="http://gmailblog.blogspot.com/2009/02/new-ways-to-label-with-move-to-and-auto.html">http://gmailblog.blogspot.com/2009/02/new-ways-to-label-with-move-to-and-auto.html</a></li> </ul> <p>I really like how these new buttons work in Gmail. How can I use these or similar buttons on my site? Are there any open source projects with a similar look &amp; feel?</p> <p>If I wanted to roll my own button package like this using JQuery/XHTML/CSS, what elements could I use? My initial thoughts are:</p> <ol> <li><p>Standard <code>&lt;input type="button"&gt;</code> with css to improve the look (the design article talked mostly about the css/imges involves.)</p></li> <li><p>Jquery javascript to bring up a custom dialog rooted to the button on the "onclick" event which would have <code>&lt;a&gt;</code> tags in them and a search bar for filtering? Would a table layout for that popup be sane?</p></li> </ol> <p>I'm terrible at reverse engineering things on the web, what are some of the tools that I could use to help reverse engineer these buttons? Using Firefox's web developer toolbar I can't really see the css or javascript (even if it is minified) that is used on the buttons popup dialogs. What browser tool or other method could I use to peek at them and get some ideas?</p> <p>I'm not looking to steal any of Google's IP, just get an idea of how I could create similar button functionality.</p>
<p>-- EDIT -- I didn't see the link in the original post. Sorry! Will try and re-write to reflect actual question</p> <p>StopDesign has an excellent post on this <a href="http://stopdesign.com/archive/2009/02/04/recreating-the-button.html">here</a>. <strong>[edit 20091107] These were released as part of the <a href="http://code.google.com/closure/">closure library</a>: see the <a href="http://closure-library.googlecode.com/svn/trunk/closure/goog/demos/button.html">button demo</a>.</strong></p> <p>Basically the custom buttons he <a href="http://stopdesign.com/eg/buttons/3.0/code.html">shows</a> are created using a simple bit of CSS.</p> <p>He originally used 9 tables to get the effect: <img src="http://stopdesign.com/img/archive/2009/02/9-cell.png" alt="9 Tables"></p> <p>But later he used a simple 1px left and right margin on the top and bottom borders to achieve the same effect.</p> <p>The gradient is faked by using three layers: <img src="http://stopdesign.com/img/archive/2009/02/bands-spec.png" alt="Button Gradient"></p> <p>All of the code can be found at the <a href="http://stopdesign.com/eg/buttons/3.1/code.html">Custom Buttons 3.1</a> page. (although the gradient without the image is only working in Firefox and Safari)</p> <h2>Step by Step Instructions</h2> <p>1 - Insert the following CSS:</p> <pre><code>/* Start custom button CSS here ---------------------------------------- */ .btn { display:inline-block; background:none; margin:0; padding:3px 0; border-width:0; overflow:visible; font:100%/1.2 Arial,Sans-serif; text-decoration:none; color:#333; } * html button.btn { padding-bottom:1px; } /* Immediately below is a temporary hack to serve the following margin values only to Gecko browsers Gecko browsers add an extra 3px of left/right padding to button elements which can't be overriden. Thus, we use -3px of left/right margin to overcome this. */ html:not([lang*=""]) button.btn { margin:0 -3px; } .btn span { background:#f9f9f9; z-index:1; margin:0; padding:3px 0; border-left:1px solid #ccc; border-right:1px solid #bbb; } * html .btn span { padding-top:0; } .btn span span { background:none; position:relative; padding:3px .4em; border-width:0; border-top:1px solid #ccc; border-bottom:1px solid #bbb; } .btn b { background:#e3e3e3; position:absolute; z-index:2; bottom:0; left:0; width:100%; overflow:hidden; height:40%; border-top:3px solid #eee; } * html .btn b { top:1px; } .btn u { text-decoration:none; position:relative; z-index:3; } /* pill classes only needed if using pill style buttons ( LEFT | CENTER | RIGHT ) */ button.pill-l span { border-right-width:0; } button.pill-l span span { border-right:1px solid #ccc; } button.pill-c span { border-right-style:none; border-left-color:#fff; } button.pill-c span span { border-right:1px solid #ccc; } button.pill-r span { border-left-color:#fff; } /* only needed if implementing separate hover state for buttons */ .btn:hover span, .btn:hover span span { cursor:pointer; border-color:#9cf !important; color:#000; } /* use if one button should be the 'primary' button */ .primary { font-weight:bold; color:#000; } </code></pre> <p>2 - Use one of the following ways to call it (more can be found in the links above)</p> <pre><code>&lt;a href="#" class="btn"&gt;&lt;span&gt;&lt;span&gt;&lt;b&gt;&amp;nbsp;&lt;/b&gt;&lt;u&gt;button&lt;/u&gt;&lt;/span&gt;&lt;/span&gt;&lt;/a&gt; </code></pre> <p>or </p> <pre><code>&lt;button type="button" class="btn"&gt;&lt;span&gt;&lt;span&gt;&lt;b&gt;&amp;nbsp;&lt;/b&gt;&lt;u&gt;button&lt;/u&gt;&lt;/span&gt;&lt;/span&gt;&lt;/button&gt; </code></pre>
Make an existing Git branch track a remote branch? <p>I know how to make a new branch that tracks remote branches, but <strong>how do I make an existing branch track a remote branch?</strong></p> <p>I know I can just edit the <code>.git/config</code> file, but it seems there should be an easier way.</p>
<p>Given a branch <code>foo</code> and a remote <code>upstream</code>:</p> <p><strong>As of Git 1.8.0:</strong></p> <pre><code>git branch -u upstream/foo </code></pre> <p>Or, if local branch <code>foo</code> is not the current branch:</p> <pre><code>git branch -u upstream/foo foo </code></pre> <p>Or, if you like to type longer commands, these are equivalent to the above two:</p> <pre><code>git branch --set-upstream-to=upstream/foo git branch --set-upstream-to=upstream/foo foo </code></pre> <p><strong>As of Git 1.7.0:</strong></p> <pre><code>git branch --set-upstream foo upstream/foo </code></pre> <p><strong>Notes:</strong></p> <p>All of the above commands will cause local branch <code>foo</code> to track remote branch <code>foo</code> from remote <code>upstream</code>. The old (1.7.x) syntax is deprecated in favor of the new (1.8+) syntax. The new syntax is intended to be more intuitive and easier to remember.</p> <hr> <p>See also: <a href="http://stackoverflow.com/q/6089294/95706">Git: Why do I need to do `--set-upstream` all the time?</a></p>
IE and Memory accumulation in Javascript <p>Here is the test URL</p> <p><a href="http://edventures.com/temp/divtest.php" rel="nofollow">http://edventures.com/temp/divtest.php</a></p> <p>Procedure:</p> <ol> <li>Close all IE instances.</li> <li>Open the URL in IE7</li> <li>Open the task manager, look for memory consumed by IE</li> <li>Now click on Create button,</li> <li>Watch the memory it will jump up by about 2K</li> <li>Now click on Destroy button and the DIV will be destroyed but the memory remains the same.</li> <li>You can try it repeatedly and memory just adds up.</li> </ol> <p>Is there any way to fix this? Any way to call Garbage collector forcefully without reloading the window?</p> <p>I am under assumption that when I remove DIV the memory will be freed but does not seem to work that way.</p> <p>Please let me know any fix to this.</p> <p>Thanks for your help.</p> <p>Suhas</p>
<p>Here's how to create DOM elements and prevent memory leaks in IE.</p> <pre><code>function createDOMElement(el) { var el = document.createElement(el); try { return el; } finally { el = null; } } </code></pre> <p>You can use variations of the try/finally trick to prevent the leaks when doing other DOM operations.</p>
CSS max-height not working <p>I have a very simply problem where I need a div to expand to fit its contents unless the height reaches a certain size, when I want the div to scroll vertically instead. As a test, I created a page containing:</p> <pre><code>&lt;div style="width:300px;max-height:25px;background-color:green;overflow:auto;"&gt; 1&lt;br /&gt; 2&lt;br /&gt; 3&lt;br /&gt; 4&lt;br /&gt; 5 &lt;/div&gt; </code></pre> <p>Unfortunately, the max-height doesn't seem to work. What am I doing wrong?</p> <p>I am using IE7.</p>
<p>The problem is your browser. Maybe you could wrap this div in another div that has the fixed height of 25px. Of course this wouldn't be exactly the same as max-height.</p> <p><a href="http://perishablepress.com/press/2007/01/16/maximum-and-minimum-height-and-width-in-internet-explorer/">An article about a solution.</a></p> <p><strong>Edit:</strong> <a href="http://msdn.microsoft.com/en-us/library/cc351024(VS.85).aspx#positioning">According to Microsoft</a> it should work in IE7+.</p> <p>Have you set an appropriate doctype? If not IE7 uses an old layout engine. You should use HTML 4 or XHTML.</p>
Does R have quote-like operators like Perl's qw()? <p>Anyone know if R has quote-like operators like Perl's <code>qw()</code> for generating character vectors? </p>
<p>No, but you can write it yourself:</p> <pre><code>q &lt;- function(...) { sapply(match.call()[-1], deparse) } </code></pre> <p>And just to show it works:</p> <pre><code>&gt; q(a, b, c) [1] "a" "b" "c" </code></pre>
Type of Projects where Unit Testing is useless <p>Do you believe that Unit Testing (and test driven development) must be done under any set of circumstances or should there be some exceptions. I've been working on the type of projects lately where I can't see how Unit Testing would be useful or improve design, quality of code, etc. One type of project is PDF reports generator which takes aggregate data (values already calculated and QAed) and outputs it to a PDF report file. Another type is straight-forward CRUD applications using 3rd party ORM tool. I can see how someone could make an argument for using Unit Testing for CRUD application, but it's a lot of unnecessary and time consuming setup work, like stabbing out all the calls to a database and mocking business objects, etc. when at the end all you need to know if something happened to the DB. So when one should use or avoid Unit Testing?</p> <p>Thanks</p>
<p>Please don't conflate unit testing (UT), which is a tool, with test-driven design (TDD), which is a methodology. <a href="http://stackoverflow.com/questions/517977/what-do-you-test-with-your-unit-tests/518165#518165">see this for more</a></p> <p>Also, remember that one of the benefits of unit tests is for regression testing, i.e. as insurance against future breaking changes (and to help verify that fixed bugs do not become un-fixed).</p> <p>In your first example, I would unit-test the PDF conversion as follows:</p> <ul> <li>start with a known set of sample data, and generate the PDF document</li> <li>manually verify that the generated PDF is correct</li> <li>retain the sample data and correct PDF document as part of the test suite</li> <li>write a function to compare two PDF documents for differences (at the binary or content level, as appropriate)</li> <li>automate this unit test to compare the PDF document generated from the sample data with the verified-correct document from the first step</li> </ul> <p>Now, whenever you change the PDF generation code, you have an automated unit test to verify that you did not break document generation <em>at least</em> for the sample data and output format.</p> <p>I have used the same technique for verifying HTML-rendered pages, GUI screens, etc. Manually verify the baseline, then automate the comparison after that. This provides insurance against future breaking changes.</p> <p>Of course if your output formats change frequently this may not be as useful, but a baseline test of the basic output formatting is likely to have a long lifespan.</p> <p>In your second example it sounds like you would be testing the 3rd-party ORM tool, which is probably pointless. However, again some baseline tests may be useful as insurance against future breaking changes, depending on how you are using the tool. For example, instead of mocking up the entire n-tier chain (I'm not a fan of mocking when it is not necessary), just use the ORM tool to create, read, update, and delete a typical object/record, and verify the operation using direct SQL statements on the (test) database. That way if the 3rd-party vendor later updates something that breaks the basic functionality you'll know about it, and new developers to your project can easily see how to use the ORM tool from the unit test examples.</p>
Passing a work item between threads (Java) <p>I have two threads. The producer is producing pieces of data (String objects), where the consumer processes these strings. The catch is that my application only needs the most recent data object to be processed. In other words, if the producer managed to produce two strings "s1" and then "s2" then I want the consumer to process only "s2". "s1" can be safely discarded.</p> <p>Of course there's no problem implementing a class that realizes this behavior, but I want to use a standard mechanism from java.util.concurrent (if such a mechanism exists). Note that SynchronousQueue is not a good solution: the consumer will block when enqueueing "s1" and will not get the chance to produce "s2".</p> <p>(In short, I am looking for a single-element collection with a blocking remove operation and a non-blocking set operation)</p> <p>Any ideas?</p>
<p>I think your best answer is probably to use ArrayBlockingQueue, where the producer (you only have one producer, right?) removes any existing element before adding the new element.</p> <p>Sure, there are race conditions in this implementation: the consumer could start processing an element just before the producer removes it. But those race conditions will always exist, no matter what data structure you use.</p>
How to simulate Windows shutdown for debugging? <p>I have an issue with my application when Windows shuts down - my app isn't exiting nicely, resulting in the End Task window being displayed. How can I use the debugger to see what's going on? </p> <p>Is there a way to send the Windows shutdown message(s) to my application so it thinks Windows is shutting down, so I can see exactly how it behaves?</p>
<p>There is a tool named Restart Manager (rmtool.exe) in the Microsoft's Logo Testing Tools for Windows, which can be used to send shutdown and restart messages to a process. Logo testing tools can be downloaded here:</p> <p><a href="http://download.microsoft.com/download/d/2/5/d2522ce4-a441-459d-8302-be8f3321823c/LogoToolsv1.0.msi">http://download.microsoft.com/download/d/2/5/d2522ce4-a441-459d-8302-be8f3321823c/LogoToolsv1.0.msi</a></p> <p>Then you can simulate shutdown for your process:</p> <pre><code>rmtool.exe -p [PID] -S </code></pre> <p>where [PID] is the process ID. According to the Vista Logo Certification Test Cases document,</p> <blockquote> <p>Restart Manager shutdown messages are:</p> <p>a. WM_QUERYENDSESSION with LPARAM = ENDSESSION_CLOSEAPP(0x1): GUI applications must respond (TRUE) immediately to prepare for a restart.</p> <p>b. WM_ENDSESSION with LPARAM = ENDSESSION_CLOSEAPP(0x1): The application must shutdown within 5 seconds (20 seconds for services).</p> <p>c. CTRL_SHUTDOWN_EVENT: Console applications must shutdown immediately.</p> </blockquote>
Calculate final scores in a game relative to previous scores and other players <p>Supposing a multi-player game, what you be the fairest way give final scores based on the previous scores of all players.</p> <p>For example, in a two player match, player A having two times the score of player B. "A" finishing first would not give him a lot of points; finishing last, he would lose quite a lot of points.</p>
<p>Have you ever read about the <a href="http://en.wikipedia.org/wiki/Elo_rating_system" rel="nofollow">Elo Rating System</a>, used in chess?</p> <p>I don't think it's an exact fit for your scenario, but it might give you a few ideas.</p>
How to have favicon / icon set when bookmarklet dragged to toolbar? <p>I've made myself a bookmarklet, and it functions just fine, but when added to a toolbar in Opera or Firefox, it just takes on the default bookmark icon for the browser (a globe and a star, respectively). My site has a favicon, and the window, tab and even [site] bookmark uses the favicon I've specified. Just not my bookmarklet.</p> <p>How can I code my site or bookmarklet so that the bookmarklet gets the favicon, too?</p> <p>I'm aware of various manual hackery techniques users can use to set the favicon after the fact, but those are undesirable solutions.</p>
<p>A bookmarklet uses the <code>javascript://</code> schema and thus do not have a domain from which a favicon may be loaded. </p> <p>So, currently there is no way for you to provide a favicon for a bookmarklet. Think about it like this: remember the whole Javascript sandbox thing - where Javascript may not access anything outside the domain of the web page where it is running? Well a bookmarklet that needs to be tied in to whatever domain for the current page you are watching, cannot be also tied in to a favicon on your own web site.</p> <p>Update: According to Hans Schmucker's answer, there is a possibility to create a bookmarklet that when loaded by the browser into the bookmark menu it will generate an HTML document that has a favicon. The reasoning seems like it may work but I have yet to see something like this in action and my tests have came back negative.</p>
How to stop onkeyup event being fired when an alert box is cleared with the enter key <p>Here's my problem...</p> <p>I have a text field which uses the javascript onkeyup event to do some "quiet" validation with a tick or cross if the value is valid.</p> <p>When the enter key is pressed, it does the same validation, but with an alert box advising of any problems. If the enter key is used to clear the alert box, this press of the enter key refires the onkeyup event, which restarts the validation and the alert boxes again.</p> <p>As soon as I click the OK in the alert box, this naturally stops.</p> <p>Is there any way I can detect that the enter press was from the alert box?</p> <p>This definitely happens in opera, safari and firefox.</p>
<p>Use the <code>keypress</code> event instead when triggering the behavior of the enter-key.</p>
Examples of good Java desktop applications <p>More of a wiki list/collection, I'm looking for a list of good Java desktop apps. I've added a couple below to get started. Please list the framework/widget toolkit being used if it's know as well.</p>
<p><a href="http://www.jetbrains.com/idea/index.html">IntelliJ IDEA</a> (Swing)</p>
Is there a good way to call a CGI script from a PHP script? <p>I saw that there is a <strong>virtual()</strong> function in PHP that will call a CGI script, but is that the best way? Can I pass any parameters to that scripts as well?</p> <p>I saw some examples using <strong><code>file_get_contents()</code></strong> or <strong>include()</strong> and passing in the URL of a CGI script, but that feels like a hack.</p>
<p>Use <strong>exec()</strong> if you can call it locally. If it needs to be invoked as a CGI (as in the script is designed to only work within a CGI environment), then you'll need to call it via <strong>include()</strong> or <strong>file_get_contents()</strong>. <strong>virtual()</strong> will flush your buffers and append the output of the sub-request.</p> <p>You can pass parameters through <strong>include()</strong>, <strong>file_get_contents()</strong>, and <strong>virtual()</strong> as GET parameters: </p> <pre><code>http://localhost/cgi-bin/foo?param1=val1&amp;param2=val2 </code></pre> <p>If possible, go the <strong>exec()</strong> route. Using the other methods may require a config change.</p> <p>When using <a href="http://ca3.php.net/manual/en/function.exec.php" rel="nofollow">exec</a>(), you'll need to pass the arguments like you would for any CLI program.</p> <pre><code>foo val1 val2 foo param1=val1 param2=val2 </code></pre> <p>How you pass the parameters in will depend on how you want to parse them out later in the other program/script. They'll show up in the called program like they would if you called it from the command line.</p>
Decrypting RijndaelManaged Encrypted strings with CryptDecrypt <p>Ok I'm trying to use the Win32 Crypto API in C++ to decrypt a string encrypted in C# (.NET 2) with the RijndaelManaged Class. But I'm having no luck at all i get jibberish or a bad data Win32 error code. All my keys, IV and salt match, I've looked in the watch for both test apps. I've spent all say looking at it and I'm officialy stuck.</p> <p>Anyway here is the C#</p> <pre><code> Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(GetPassPhrase(), salt, 1000); RijndaelManaged rijndael = new RijndaelManaged(); rijndael.BlockSize = 128; rijndael.KeySize = 256; rijndael.Mode = CipherMode.CBC; rijndael.Key = pdb.GetBytes(m_KeySize); rijndael.IV = GetIV(iv); ICryptoTransform encryptor = rijndael.CreateEncryptor(); MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); Byte[] encryptedBytes = null; Byte[] toBeEncrypted = UnicodeEncoding.Unicode.GetBytes(value); csEncrypt.Write(toBeEncrypted, 0, toBeEncrypted.Length); csEncrypt.FlushFinalBlock(); encryptedBytes = msEncrypt.ToArray(); </code></pre> <p>The C++ to decrypt it is:</p> <pre><code> keyBlob.hdr.bType = PLAINTEXTKEYBLOB; keyBlob.hdr.bVersion = CUR_BLOB_VERSION; keyBlob.hdr.reserved = 0; keyBlob.hdr.aiKeyAlg = CALG_AES_256; keyBlob.cbKeySize = KEY_SIZE; keyBlob.rgbKeyData = &amp;byKey[0]; if ( CryptImportKey( hProv, (const LPBYTE) &amp;keyBlob, sizeof(BLOBHEADER) + sizeof(DWORD) + KEY_SIZE, 0, CRYPT_EXPORTABLE, &amp;hKey ) ) { if ( CryptSetKeyParam( hKey, KP_IV, (const BYTE *) &amp;byIV, 0)) { DWORD dwLen = iDestLen; if ( CryptDecrypt( hKey, 0, TRUE, 0, pbyData, &amp;dwLen)) { if ( dwLen &lt; (DWORD) *plOutSize) { memcpy_s(pbyOutput, *plOutSize, pbyData, dwLen); *plOutSize = dwLen; bRet = TRUE; } } else { // Log DWORD dwErr = ::GetLastError(); int y =0; } } } </code></pre> <p>I'm calling CryptAcquireContext successfully and my C++ is executing fine. Can anyone spot the error in my ways. It's starting to depress me know :(</p>
<p>Ok my fault, I didn't include the Struct def for the keyblob in the C++ and it turns out you need a contigous block of data for the key with the header but I was using the MSDN example that had a pointer to the key data. Which is wrong!</p>
Are there any libraries/frameworks for SCons? <p>Each project using SCons seems to be reinventing the wheel. I would be glad to take someones directory layout, and/or solution for variant builds(debug/release), and/or testing framework, and/or best practices.</p> <p>Even several not-too-simple examples would help. </p>
<p>You may be interested in Google's <a href="http://code.google.com/p/swtoolkit/" rel="nofollow">Software Construction Toolkit</a> that was <a href="http://google-opensource.blogspot.com/2009/02/software-construction-toolkit-released.html" rel="nofollow">made open source in February 2009</a>. It adds new features on top of SCons, such as improved Visual Studio project file generation, unit test functions, and distributed builds with distcc or incredibuild.</p>
Best way to implement a stored procedure with full text search <p>I would like to run a search with MSSQL Full text engine where given the following user input: "Hollywood square"</p> <p>I want the results to have both Hollywood and square[s] in them.</p> <p>I can create a method on the web server (C#, ASP.NET) to dynamically produce a sql statement like this:</p> <pre><code>SELECT TITLE FROM MOVIES WHERE CONTAINS(TITLE,'"hollywood*"') AND CONTAINS(TITLE, '"square*"') </code></pre> <p>Easy enough. HOWEVER, I would like this in a stored procedure for added speed benefit and security for adding parameters.</p> <p>Can I have my cake and eat it too?</p>
<p>The last time I had to do this (with MSSQL Server 2005) I ended up moving the whole search functionality over to Lucene (the Java version, though Lucene.Net now exists I believe). I had high hopes of the full text search but this specific problem annoyed me so much I gave up.</p>
Rewriting URLs in ASP.NET? <p>I am using ASP.NET C#.</p> <p>How do I implement URL re-writing procedure that is similar to StackOverflow.com?</p> <pre><code>http://stackoverflow.com/questions/358630/how-to-search-date-in-sql </code></pre> <p>Also, what is the meaning of values such as "358630" in the URL? Is this the question ID (the basis for which they use to fetch the data from the table)? Whatever it is, in my application I am identifying records using an "ID" field. This field is an identity column in an SQL table. Right now, my URLs are like the following:</p> <pre><code>http://myweb.com/showdetails.aspx?id=9872 </code></pre> <p>But I'd like them to appear like:</p> <pre><code>http://myweb.com/showdetails/9872/my_question_title </code></pre> <p>Or:</p> <pre><code>http://myweb.com/9872/my_question_title </code></pre> <p>Or whatever the best way, which will taste good to search bots.</p> <p>My application is hosted on <a href="http://en.wikipedia.org/wiki/Go_Daddy" rel="nofollow">Go Daddy</a>'s shared hosting service, and I feel that no customized ASP.NET "HTTP module" or no customized DLL for URL re-writing is working on their server. I tried many samples but no luck yet!</p> <p>I found that Stack Overflow is hosted on Go Daddy (shared hosting?). Maybe Stack Overflow's method will work for me.</p>
<p>SO is using <a href="http://asp.net/mvc" rel="nofollow">ASP.NET MVC</a>. You really need to read in details how MVC URL rewriting works, but the gist of it is that the 'questions' part in the URL is the name of the Controller class (which roughly corresponds to the 'showdetails' in your URL) and the number is a ID parameter for the default action on that Controller (same as the parameter 'id' in your URL).</p>
Page displays true after running command: 'webby' <p>I'm running though the <a href="http://webby.rubyforge.org/tutorial/" rel="nofollow">webby tutorial</a> and I get to the part where you run the <strong>webby</strong> command for the first time to generate the website in the /output directory. </p> <p>I do that, and next I'm told to open output/index.html. I do so, and the only thing that displays is:</p> <pre><code>true </code></pre> <p>I view the source...and all that is displayed is</p> <pre><code>true </code></pre> <p>This isn't a Budweiser commercial from years past! This is webby!</p> <p>I wrote down the commands I used to install webby <a href="http://leeand00.tiddlyspot.com/#[[Installing%20Webby]]" rel="nofollow">here</a>, but it still doesn't seem to work.</p> <p>According to the <strong>webby -v</strong> command... I was doing it correctly. What did I do wrong?</p>
<p>Just to confirm - did you open output/index.html in a browser? And the "true" that you describe is what you see in your browser...?</p> <p>Before you ran the <code>webby</code> command, did you edit any of the files, especially <code>content/index.txt</code>? Can you paste the contents of <code>content/index.txt</code> here...?</p> <p>Did you install <code>RedCloth</code> as well as <code>Webby</code> or did it install automatically as a dependency? If you run the following command, you can see whether <code>RedCloth</code> is installed.</p> <pre><code>gem list RedCloth </code></pre>
NSNumberFormatter: plusSign vs. positivePrefix <p>The NSNumberFormatter class has <code>plusSign</code> and <code>minusSign</code> properties, but also has <code>positivePrefix</code> and <code>negativePrefix</code>.</p> <p>What is the difference between these two? If I specify both, which one comes first?</p>
<p>plusSign and minusSign are used for the mathematical addition and subtraction operators. positivePrefix and suffix and negativePrefix and suffix are used to describe what characters/strings are used todisplay whether a certain numeric value is positive or negative.</p> <p>To illustrate why they are different: most of the times, when a positive numeric value is displayed anywhere you'll just see numbers, No prefix or suffix. Negative numeric values have a minus in front, or behind them, or, in some styles of accounting they're just enclosed in brackets. Either way we'll still need a + and a - to express mathematical operations. </p>
How do I test if a column equals empty_clob() in Oracle? <p>The naïve <code>FOO = empty_clob()</code> complains about incompatible types. I tried Googling, but (once again) had little success searching for help with Oracle. Thanks.</p>
<p>Are you just wanting to check for a CLOB that doesn't have any length? While not exactly what your asking, it's basically the same thing?</p> <pre><code>select * from bar where dbms_lob.getlength(foo) = 0; </code></pre> <p>Here is the complete test:</p> <pre><code>SQL&gt; create table bar (foo clob); Table created. SQL&gt; insert into bar values (empty_clob()); 1 row created. SQL&gt; select * 2 from bar 3 where dbms_lob.getlength(foo) = 0; FOO -------------------------------------------------------------------------------- </code></pre>
Retrieve file properties <p>When in Windows XP, if I open the properties window for the file and click the second tab, I will find a window where to add attributes or remove them.</p> <p>While developing things, I noticed there was actually something I wanted to know about the file. How to retrieve this data? It's a string with name 'DESCRIPTION'.</p> <p>The actual tab is saying 'Custom'. I think it's called metadata what it shows.</p> <p>I noticed that only the files I'm looking at have that tab. It seems to be specific only for the SLDLFP -file.</p>
<p>Not on an XP machine, but I think this might work</p> <pre><code>FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo("path.txt"); string desc = myFileVersionInfo.FileDescription; </code></pre>
When working with domain models and POCO classes, where do queries go? <p>I am new to domain models, POCO and DDD, so I am still trying to get my head around a few ideas.</p> <p>One of the things I could not figure out yet is how to keep my domain models simple and storage-agnostic but still capable of performing some queries over its data in a rich way.</p> <p>For instance, suppose that I have an entity Order that has a collection of OrdemItems. I want to get the cheapest order item, for whatever reason, or maybe a list of order items that are not currently in stock. What I don't want to do is to retrieve all order items from storage and filter later (too expensive) so I want to end up having a db query of the type "SELECT .. WHERE ITEM.INSTOCK=FALSE" somehow. I don't want to have that SQL query in my entity, or any variation of if that would tie me into a specific platform, like NHibernate queries on Linq2SQL. What is the common solution in that case?</p>
<p>Domain objects should be independent of storage, you should use the Repostiory pattern, or DAO to persist the objects. That way you are enforcing separation of concerns, the object itself should not know about how it is stored.</p> <p>Ideally, it would be a good idea to put query construction inside of the repository, though I would use an ORM inside there. </p> <p>Here's Martin Fowler's definition of the <a href="http://martinfowler.com/eaaCatalog/repository.html" rel="nofollow">Repository Pattern.</a></p>
How can I get only class variables? <p>I have this class definition:</p> <pre><code>class cols: name = 'name' size = 'size' date = 'date' @classmethod def foo(cls): print "This is a class method" </code></pre> <p>With __dict__ I get all class attributes (members and variables). Also there are the "Internal attributes" too (like __main__). How can I get only the class variables without instantiation?</p>
<p>I wouldn't know a straightforward way, especially since from the interpreter's POV, there is not that much of a difference between a method of a class and any other variable (methods have descriptors, but that's it...).</p> <p>So when you only want non-callable class members, you have to fiddle around a little:</p> <pre><code>&gt;&gt;&gt; class cols: ... name = "name" ... @classmethod ... def foo(cls): pass &gt;&gt;&gt; import inspect &gt;&gt;&gt; def get_vars(cls): ... return [name for name, obj in cls.__dict__.iteritems() if not name.startswith("__") and not inspect.isroutine(obj)] &gt;&gt;&gt; get_vars(cols) ['name'] </code></pre>
Theories of software engineering <p>In my career I've come across two broad types of theory: physical theories and educational/management theories:</p> <p>Physical theories are either correct (under appropriate conditions) or incorrect, as judged by the physical world.</p> <p>Educational/management theories have the appearance of being like physical theories, but they lack rigorous testing. At best they give new ways of thinking about problems. Multiple theories are useful because one of them may speak to you in the right way.</p> <p>As an hobbyist student of software engineering there appear to be a lot of theories of software engineering (such agile programming, test driven design, patterns, extreme programming). Should I consider these theories to be physical-like or educational/management-like?</p> <p>Or have I mis-understood software engineering and find myself being in the position of "not even wrong"?</p>
<p>Software engineering is ultimately about psychology, how humans manage complexity. So software engineering principles are far more like education and management theories than physical principles.</p> <p>Some software engineering has solid math behind it: O(n log n) sorts are faster than O(n^2) sorts, etc. But mostly software engineering is about how humans think about software. How to organize things so that maintainers don't go crazy, anticipating what is likely to change and what is not, preventing and detecting human errors, etc. It's a branch of psychology or sociology.</p>
How do I build a OneTwoThree linked list with a minimum number of assignment operators? <p>I came across this problem while preparing for an interview and curious to know the diffrent ways it can be written. I found this at <a href="http://cslibrary.stanford.edu/103/" rel="nofollow">http://cslibrary.stanford.edu/103/</a> and have given the problem as it is.</p> <p>here is a code to build the list {1,2,3}</p> <pre><code>struct node* BuildOneTwoThree() { struct node* head = NULL; struct node* second = NULL; struct node* third = NULL; head = malloc(sizeof(struct node)); // allocate 3 nodes in the heap second = malloc(sizeof(struct node)); third = malloc(sizeof(struct node)); head-&gt;data = 1; // setup first node head-&gt;next = second; // note: pointer assignment rule second-&gt;data = 2; // setup second node second-&gt;next = third; third-&gt;data = 3; // setup third link third-&gt;next = NULL; // At this point, the linked list referenced by "head" // matches the list in the drawing. return head; } </code></pre> <p>Q: Write the code with the smallest number of assignments (=) which will build the above memory structure. A: It requires 3 calls to malloc(). 3 int assignments (=) to setup the ints. 4 pointer assignments to setup head and the 3 next fields. With a little cleverness and knowledge of the C language, this can all be done with 7 assignment operations (=).</p>
<p>I did it with six assignments. What do I get?</p> <pre><code>struct node { int data; struct node * next; }; struct node * build_123() { struct node * first = malloc(sizeof(*first)); struct node * second = malloc(sizeof(*second)); struct node * third = malloc(sizeof(*third)); assert(first &amp;&amp; second &amp;&amp; third); *first = (struct node){ 1, second }; *second = (struct node){ 2, third }; *third = (struct node){ 3, NULL }; return first; } </code></pre> <p><hr /></p> <p>Also, the exercise isn't very useful. If I wanted to build a linked list from a known set of integers, I'd do something like this:</p> <pre><code>struct node { int data; struct node * next; }; #define build_list(...) \ _build_list((sizeof((int []){ __VA_ARGS__ }))/(sizeof(int)), \ (int []){ __VA_ARGS__ }) struct node * _build_list(size_t count, int values[count]) { struct node * next = NULL; for(size_t i = count; i--; ) { struct node * current = malloc(sizeof *current); assert(current); *current = (struct node){ values[i], next }; next = current; } return next; } </code></pre> <p>Then, you can build an arbitrary list with</p> <pre><code>struct node * list = build_list(1, 2, 3); </code></pre> <p><hr /></p> <p>Here's another version using a single assignment, inspired by <a href="http://stackoverflow.com/questions/522010/build-onetwothree-linked-list-with-minimum-assignment-operators/522193#522193">codelogic's answer</a>:</p> <pre><code>struct node * build_123(void) { struct node * list = malloc(sizeof(struct node [3])); return memcpy( list, (struct node []){ { 1, list + 1 }, { 2, list + 2 }, { 3, NULL } }, sizeof(struct node [3]) ); } </code></pre> <p><hr /></p> <p>Finally, I slightly modified <a href="http://stackoverflow.com/questions/522010/build-onetwothree-linked-list-with-minimum-assignment-operators/522055#522055">MSN's solution</a> - now, there's no assignment at all:</p> <pre><code>struct node { int data; struct node * next; }; struct node * make_node(struct node * new_node, int data, struct node * next) { return memcpy(new_node, &amp;(struct node){ data, next }, sizeof(*new_node)); } struct node * create_node(int data, struct node * next) { return make_node(malloc(sizeof(struct node)), data, next); } struct node * build_123(void) { return create_node(1, create_node(2, create_node(3, NULL))); } </code></pre>
Good free offline PL/SQL formatter <p>Does anyone knows a good formatter for PL/SQL free and offline?</p> <p>Thank you very much.</p>
<p>Not really sure what you mean by "offline", however Oracle has a tool called SQL Developer that is free and can download from their website. It has some formatting options you can apply to your code.</p>
DataGridView Autogeneratecolumns as TextBox instead of label <p>How can I have a datagridview that will autogenerate a textbox instead of a label?</p>
<p>In short, you can't. You could inherit from a gridview and implement it yourself. It could look something like this:</p> <pre><code>Public Class MyGrid Inherits GridView Private Sub MyGrid_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles Me.RowDataBound If Me.AutoGenerateColumns = True Then If e.Row.RowType = DataControlRowType.DataRow Then For Each c As TableCell In e.Row.Cells Dim tb As New TextBox() tb.Text = c.Text c.Controls.Clear() c.Controls.Add(tb) Next End If End If End Sub </code></pre>
Differences among the methods of loading an extension in PHP <pre><code>extension="ext.so" zend_extension="/usr/lib/php4/ext.so" zend_extension_ts="/usr/lib/php4/ext.so" </code></pre> <p>What are the differences?</p>
<p>extension is used to load a user module that adds functionality into the language, such as database access, image manipulation. zend&#95;extension and zend&#95;extension&#95;ts are used to load a module that extends the underlying PHP engine. One such example would be <a href="http://xdebug.org" rel="nofollow">xdebug</a>, an extension that allows you to debug your PHP applications. zend&#95;extension&#95;ts is for ZTS enabled PHP installations. To see if you have a ZTS build get the output from:</p> <pre><code>&lt;?php phpinfo(); ?&gt; </code></pre>
How to quantify the quality of a pseudorandom number generator? <p>This is based on <a href="http://stackoverflow.com/questions/137783/">this question</a>. A number of answers were proposed that generate non-uniform distributions and I started wondering how to quantify the non uniformity of the output. I'm not looking for patterning issues, just single value aspects.</p> <p>What are the accepted procedures?</p> <p><hr /></p> <p>My current thinking is to computer the average <a href="http://en.wikipedia.org/wiki/Information_entropy" rel="nofollow">Shannon entropy</a> per call by computing the entropy of each value and taking a weighted average. This can then be compered to the expected value.</p> <p>My concerns are</p> <ol> <li>Is this correct?</li> <li>How to compute these value without loosing precision?</li> </ol> <p>For #1 I'm wondering if I've got it correct.</p> <p>For #2 the concern is that I would be processing numbers with magnitudes like 1/7 +/- 1e-18 and I'm worried that the floating point errors will kill me for any but the smallest problems. The exact form of the computation could result in some major differences here and I seem to recall that there are some ASM options for some special log cases but I can't seem to find the docs about this.</p> <p><hr /></p> <p>In this case the use is take a "good" PRNG for the range <code>[1,n]</code> and generate a SRNG for the range <code>[1,m]</code>. The question is how much worse is the results than the input?</p> <p>What I have is expected occurrence rates for each output value.</p>
<p>NIST has a set of documents and tools for statistically analyzing random number generators cross a variety of metrics.</p> <p><a href="http://csrc.nist.gov/groups/ST/toolkit/rng/index.html" rel="nofollow">http://csrc.nist.gov/groups/ST/toolkit/rng/index.html</a></p> <p>Many of these tests are also incorporated into the Dieharder PRNG test suite.</p> <p><a href="http://www.phy.duke.edu/~rgb/General/rand_rate.php" rel="nofollow">http://www.phy.duke.edu/~rgb/General/rand_rate.php</a></p> <p>There are a ton of different metrics, because there are many, many different ways to use PRNGs. You can't analyze a PRNG in a vacuum - you have to understand the use case. These tools and documents provide a lot of information to help you in this, but at the end of the day you'll still have to understand what you actually need before you can determine of the algorithm is suitable. The NIST documentation is thorough, if somewhat dense.</p>
Checking whether all enum values are mapped? <p>Is there a convenience method available in the java standard libraries to check whether all possible keys in an EnumMap are mapped to a value?</p> <p>I can write my own method like:</p> <pre><code>public static &lt;T extends Enum&lt;T&gt;&gt; boolean areAllValuesMapped(EnumMap&lt;T, ?&gt; map, Class&lt;T&gt; enumClass) { return map.keySet().equals(EnumSet.allOf(enumClass)); } </code></pre> <p>But then I'm repeating the Class parameter (already given in the EnumMap constructor) as well as creating throwaway KeySet and EnumSet objects. EnumMap should have enough information to do this efficiently as an internal operation.</p>
<p>There is no built-in way to do this that I can find in <code>EnumMap</code> (and I checked the source code to be sure). However, here is a slightly quicker method:</p> <pre><code>public static &lt;T extends Enum&lt;T&gt;&gt; boolean areAllValuesMapped(EnumMap&lt;T,?&gt; map, Class&lt;T&gt; enumClass) { return map.size() == enumClass.getEnumConstants().length; } </code></pre> <p>I should note that <code>EnumMap.keySet()</code> does not return an <code>EnumSet</code>; if it did, the <code>equals()</code> call that you use would be a simple matter of comparing <code>longs</code>. As it is, it has to use an iterator and check each enum constant sequentially.</p>
How can I set the value of auto property backing fields in a struct constructor? <p>Given a struct like this:</p> <pre><code>public struct SomeStruct { public SomeStruct(String stringProperty, Int32 intProperty) { this.StringProperty = stringProperty; this.IntProperty = intProperty; } public String StringProperty { get; set; } public Int32 IntProperty { get; set; } } </code></pre> <p>Of course, a compiler error is generated that reads <strong>The 'this' object cannot be used before all of its fields are assigned to</strong>.</p> <p>Is there a way to assign values to the backing fields or the properties themselves, or do I have to implement properties the old-fashioned way with my own explicit backing fields?</p>
<p>You need to use the "this" constructor:</p> <pre><code>public SomeStruct(String stringProperty, Int32 intProperty) : this() { this.StringProperty = stringProperty; this.IntProperty = intProperty; } </code></pre> <p>Doing this calls the default constructor and by doing so, it initializes all the fields, thus allowing <code>this</code> to be referenced in the custom constructor.</p>
Read rss and show as html <p>I am using google reader for my RSS, i want to export all my shared or starred rss items to HTML to take this html and put on my website</p> <p>Do any one have an idea about? And one important thing as well, can i page through this html? i mean to export as pages not all in one html page to let the user on my site page through my starred feeds.</p> <p>Thanks,</p>
<p>With XSTL you can transform XML to any format you want, including HTML. You can do the transformation on the server, or with modern browsers like IE6+ and Firefox2+ you can do the transformation on the client side. XSTL isn't very pretty as a programming language, but the concept is pretty neat.</p> <p>I don't know if you can link directly to the RSS feed XML so that it's always up to date. I think Google requires that you authenticate and have permission to access the feed.</p>
dependency injection and logging interfaces <p>I was wondering what some of the best practices were around logging and logging frameworks and dependency injection. Specifically, if I am designing a class that needs a way to log, how should I go about getting an interface to log to keeping dependency injection in mind?</p> <p>Dependency injection seems to state that external dependencies should be injected from the outside (constructor or property setters), so should I take an ILog instance in the constructor and use in the class? Should I consider logging an optional dependency and get it in a setter? Am I pushing for too much flexibility by allowing for the logging interface to change and should I just take a hard dependency on a specific logging interface (by e.g. create a static ILog variable via a call to a factory method)? Could this factory method call into the container to get the ILog implementation or will this create initialization conflicts between static variables being initialization and the IoC container being initialized?</p> <p>Should I be doing this:</p> <pre><code>public class MyService : ISomeService { private static readonly ILogger s_log = LoggingFactory.GetLogger(typeof(MyService)) ... } </code></pre> <p>or perhaps this:</p> <pre><code>public class MyService : ISomeService { protected virtual ILogger Logger {get; private set;} public MyService(ILogger logger, [other dependencies]) { Logger = logger; } } </code></pre> <p>or even this:</p> <pre><code>public class MyService : ISomeService { public virtual ILogger Logger {get; set;} public MyService() { } } </code></pre> <p>Other patterns or ways to do this? What are people out there doing? What's working and when?</p>
<p>It's great that you're looking into inversion-of-control and dependency-injection.</p> <p>But for your question, there's another concept you might want to look into: aspect-oriented programming.</p> <p>In .NET, there are some good frameworks available for doing aspect-oriented programming, including Castle, LinFu, and Microsoft's Policy-Injection Application Block. In fact, some inversion-of-control containers have some aspect-oriented features in them as well.</p> <p>These concepts and tools help make concerns such as logging take a background seat in terms of code noise, and make be handled automagically.</p>
Is there a way to loop through a sub section of a list in Python <p>So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it?</p> <p>I don't see a way by using the for each and for range techniques.</p>
<pre><code>for x in thousand[400:500]: pass </code></pre> <p>If you are working with an iterable instead of a list, you should use <a href="http://docs.python.org/library/itertools">itertools</a>:</p> <pre><code>import itertools for x in itertools.islice(thousand, 400, 500): pass </code></pre> <p>If you need to loop over <code>thousand[500]</code>, then use 501 as the latter index. This will work even if <code>thousand[501]</code> is not a valid index.</p>