input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
How do I iterate through a string in Python? <p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
|
<p>The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string).</p>
<p>You can use string.lowercase, as other posters have suggested:</p>
<pre><code>import string
allTheLetters = string.lowercase
</code></pre>
<p>To do things the way you're "used to", treating letters as numbers, you can use the "ord" and "chr" functions. There's absolutely no reason to ever do exactly this, but maybe it comes closer to what you're actually trying to figure out:</p>
<pre><code>def getAllTheLetters(begin='a', end='z'):
beginNum = ord(begin)
endNum = ord(end)
for number in xrange(beginNum, endNum+1):
yield chr(number)
</code></pre>
<p>You can tell it does the right thing because this code prints <code>True</code>:</p>
<pre><code>import string
print ''.join(getAllTheLetters()) == string.lowercase
</code></pre>
<p>But, to solve the problem you're actually trying to solve, you want to use a dictionary and collect the letters as you go:</p>
<pre><code>from collections import defaultdict
def letterOccurrances(string):
frequencies = defaultdict(lambda: 0)
for character in string:
frequencies[character.lower()] += 1
return frequencies
</code></pre>
<p>Use like so:</p>
<pre><code>occs = letterOccurrances("Hello, world!")
print occs['l']
print occs['h']
</code></pre>
<p>This will print '3' and '1' respectively.</p>
<p>Note that this works for unicode as well:</p>
<pre><code># -*- coding: utf-8 -*-
occs = letterOccurrances(u"héĺĺó, áºÃ³Åĺd!")
print occs[u'l']
print occs[u'ĺ']
</code></pre>
<p>If you were to try the other approach on unicode (incrementing through every character) you'd be waiting a long time; there are millions of unicode characters.</p>
<p>To implement your original function (print the counts of each letter in alphabetical order) in terms of this:</p>
<pre><code>def alphCount(text):
for character, count in sorted(letterOccurrances(text).iteritems()):
print "%s: %s" % (character, count)
alphCount("hello, world!")
</code></pre>
|
Application_Start works fine on workstation, is not called when deployed <p>I have an application that works great on my development workstation but fails when the application is deployed to the live environment. It seems that Application_Start is not being called in the live environment.</p>
|
<p>I was able to fix it by removing the PrecompiledApp.config file that was in the root directory of the web site on our test server. I'm guessing that file was a holdover from when the project was a Web Site project. I recently converted it over to a Web App project. So if you are building a Web App project, make sure you DON'T have a PrecompiledApp.config file on your target server.</p>
|
jQuery resize not working at FireFox, Chrome and Safari <pre><code>$("#dvMyDIV").bind("resize", function(){
alert("Resized");
});
</code></pre>
<p>or</p>
<pre><code>$("#dvMyDIV").resize(function(){
alert("Resized");
});
</code></pre>
<p>The questions</p>
<ol>
<li>Why is this not working at FireFox, Chrome and Safari?</li>
<li>Can this be considered a jQuery bug since the resize is not handled for other browsers?</li>
<li>Could the only workaround be calling a SetTimeout function checking the clientHeight and clientWidth?</li>
<li>Any workarounds using jQuery?</li>
</ol>
|
<p>I believe the JavaScript resize event only applies to frames or windows, not to DIVs.</p>
<p>e.g. see <a href="http://devguru.com/technologies/javascript/10929.asp">this page</a>:</p>
<blockquote>
<p>The onResize even handler is use to execute specified code whenever a user or script resizes a window or frame. This allows you to query the size and position of window elements, dynamically reset SRC properties etc. </p>
</blockquote>
<p>So if you want to detect when the window is resized, in jQuery you should probably use <code>$(window).resize(function() { });</code></p>
<p><b>Edit:</b> if you want to watch the size of a DIV, it depends on what your intention is. If you're resizing with JavaScript then you could implement a method to perform the resize and have that handle calling any other resize code.</p>
<p>Otherwise, if you're just watching for the DIV to resize when someone resizes the window, wouldn't it just work to attach the resize listener to the window and then check if the DIV had been resized (i.e. store the old values of width / height and check them on resize)?</p>
<p>Finally, you could consider using <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/watch">watch</a> on the width / height properties, although I don't know whether this is fully browser-compatible (think this might be Mozilla-only). I did find <a href="http://www.west-wind.com/Weblog/posts/453942.aspx">this jQuery plugin</a> which looks like it might do the same thing though (with some slight modification).</p>
|
Class methods as event handlers in JavaScript? <p>Is there a best-practice or common way in JavaScript to have class members as event handlers?</p>
<p>Consider the following simple example:</p>
<pre><code><head>
<script language="javascript" type="text/javascript">
ClickCounter = function(buttonId) {
this._clickCount = 0;
document.getElementById(buttonId).onclick = this.buttonClicked;
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
</script>
</head>
<body>
<input type="button" id="btn1" value="Click me" />
<script language="javascript" type="text/javascript">
var btn1counter = new ClickCounter('btn1');
</script>
</body>
</code></pre>
<p>The event handler buttonClicked gets called, but the _clickCount member is inaccessible, or <em>this</em> points to some other object.</p>
<p>Any good tips/articles/resources about this kind of problems?</p>
|
<pre><code>ClickCounter = function(buttonId) {
this._clickCount = 0;
var that = this;
document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
</code></pre>
|
Apache MOD_REWRITE Domain Level Cookie <p>I need to deal with Affiliate Tracking on our website.</p>
<p>In our .htaccess we have:</p>
<pre><code>RewriteCond %{QUERY_STRING} affiliate=(.*)
RewriteRule ^(.*)$ $1? [NC,R,L,co=AFFID:%1:%{HTTP:Host}:7200:/]
</code></pre>
<p>Which creates a COOKIE called AFFID with the value of the URL Parameter affiliate.</p>
<p>But the Cookie is not for the whole domain, i.e. Going to <a href="http://www.domain.com/?affiliate=bmk" rel="nofollow">http://www.domain.com/?affiliate=bmk</a> sets the AFFID cookie with the value bmk for .www.domain.com but I would like ti to be for .domain.com so that it can be used across our secure domain which will be secure.domain.com </p>
<p>Any help would be appreciated </p>
<p>Cheers</p>
|
<p>Why don't you just hardcode it?</p>
<pre><code>RewriteRule ^(.*)$ $1? [NC,R,L,co=AFFID:%1:.domain.com:7200:/]
</code></pre>
<p>If you can't do that, the you'd have to match the domain, like this (untested):</p>
<pre><code>RewriteCond %{QUERY_STRING} affiliate=(.*)
#This would work only for xxx.dom.com or dom.com forms, not for x.y.dom.com
RewriteCond %{HTTP_HOST} [^.]*?\.?([^.]+\.[^.]+)
RewriteRule ^(.*)$ $1? [NC,R,L,co=AFFID:%1:.%2:7200:/]
</code></pre>
|
How to ignore whitespace while reading a file to produce an XML DOM <p>I'm trying to read a file to produce a DOM Document, but the file has whitespace and newlines and I'm trying to ignore them, but I couldn't:</p>
<pre><code>DocumentBuilderFactory docfactory=DocumentBuilderFactory.newInstance();
docfactory.setIgnoringElementContentWhitespace(true);
</code></pre>
<p>I see in Javadoc that setIgnoringElementContentWhitespace method operates only when the validating flag is enabled, but I haven't the DTD or XML Schema for the document.</p>
<p>What can I do?</p>
<p>Update</p>
<p>I don't like the idea of introduce mySelf < !ELEMENT... declarations and i have tried the
solution proposed in the <a href="http://forums.sun.com/thread.jspa?messageID=2054303#2699961" rel="nofollow">forum</a> pointed by Tomalak, but it doesn't work, i have used java 1.6 in an linux environment. I think if no more is proposed i will make a few methods to ignore whitespace text nodes</p>
|
<p>âIgnoringElementContentWhitespaceâ is not about removing <em>all</em> pure-whitespace text nodes, only whitespace nodes whose parents are described in the schema as having ELEMENT contentâââthat is to say, they only contain other elements and never text.</p>
<p>If you don't have a schema (DTD or XSD) in use, element content defaults to MIXED, so this parameter will never have any effect. (Unless the parser provides a non-standard DOM extension to treat all unknown elements as containing ELEMENT content, which as far as I know the ones available for Java do not.)</p>
<p>You could hack the document on the way into the parser to include the schema information, for example by adding an internal subset to the < !DOCTYPE ... [...] > declaration containing < !ELEMENT ... > declarations, then use the IgnoringElementContentWhitespace parameter.</p>
<p>Or, possibly easier, you could just strip out the whitespace nodes, either in a post-process, or as they come in using an LSParserFilter.</p>
|
How to refresh Internet Explorer using SendMessage? <p>does anybody know how to refresh the Internet Explorer (like by pressingthe F5 key) but using some "backdoor" like PostMessage or SendMessage? The internet Explorer Window is not active so I can't use the keyboard.</p>
<p>Thanks</p>
<p>(Language doesnt matter)</p>
|
<p>I think I understand your need a little better now.</p>
<p>Create a new webpage on your machine with the following:</p>
<pre><code><html>
<head>
<meta http-equiv="refresh" content="5"/>
</head>
<body>
<iframe src="http://google.com" height="100%" width="100%" frameborder="0">
If you see this - Get a new browser.
</iframe>
</body>
<html>
</code></pre>
<p>Then double click to open that in your browser window.</p>
<p>If you are the developer of the webpage, simply add the meta-tag you see in the HEAD section to auto refresh the page.</p>
|
Delphi Multi-Threading Message Loop <p>My application has several threads:
1) Main Thread
2) 2 Sub-Main Threads (each with Message Loop, as shown below), used by TFQM
3) n Worker Threads (simple loop, containing Sleep())</p>
<p>My problem is, when I close my application, the Worker Threads manage to exit properly, but 1 of the 2 Sub-Main Threads hangs (never exits) when I issue WM_QUIT to close them.</p>
<p><hr /></p>
<pre><code>procedure ThreadProcFQM(P: Integer); stdcall;
var
Msg: TMsg;
_FQM: TFQM;
begin
_FQM := Ptr(P);
try
_FQM.fHandle := AllocateHwnd(_FQM.WndProc);
while GetMessage(Msg, 0, 0, 0) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
finally
DeallocateHWnd(_FQM.fHandle);
SetEvent(_FQM.hTerminated);
end;
end;
</code></pre>
<p><hr /></p>
<pre><code>procedure TFQM.Stop;
begin
PostMessage(fHandle, WM_QUIT, 0, 0);
WaitForSingleObject(hTerminated, INFINITE);
if hThread <> INVALID_HANDLE_VALUE then
begin
CloseHandle(hThread);
hThread := INVALID_HANDLE_VALUE;
end;
end;
</code></pre>
|
<p>If I may point to few problems in your code ...</p>
<p>1) You're not checking output of AllocateHwnd. Yes, most probably it will never fail, but still ...</p>
<p>2) AllocateHwnd belogs OUT of try..finally! If it fails, DeallocateHwnd should not be called.</p>
<p>3) AllocateHwnd is not threadsafe. If you call it from multiple threads at the same time, you can run into poblems. <a href="http://17slon.com/blogs/gabr/2007/06/allocatehwnd-is-not-thread-safe.html">Read more.</a></p>
<p>As Davy said, use MsgWaitForMultipleObjects instead of creating hidden message window. Then use PostThreadMessage to send messages to thread.</p>
<p>If I may put a plug for a totally free product here - use my <a href="http://otl.17slon.com/">OmniThreadLibrary</a> instead. Much simpler than messing directly with Windows messaging.</p>
|
need PropertyGrid with drill-down, similar to QuickWatch <p>I am trying to display object data members in a generic way. I started by using PropertyGrid, which satisfies my needs as far as simple properties are concerned. However, it doesn't let the user drill-down into data members. It allows browsing into collections, but the interface is a bit awkward.</p>
<p>I'm basically looking for something with the features of QuickWatch. Does anybody know of any libraries that can do drill-down?</p>
|
<p>You can drill down into properties in the PropertyGrid of course. This is a vast subject, but maybe your properties simply need to have the ExpandableObjectConverter attached to them? Or if you are going more into details, the attached TypeConverter needs to override the GetPropertiesSupported and GetProperties methods.</p>
<p>There is another way to tell the grid what properties to show underneath a property. You can implement ICustomTypeDescriptor and return your own PropertyDescriptors. But usually this is for more complex scenarios.</p>
<p>Let me know if you need any specific detail on this.</p>
<p><strong>Update:</strong> in the comments, you asked about displaying a Dictionary. If you want to see each entry of your dict as a subproperty, then this is the complex scenario mentioned above. Your TypeConverter or custom TypeDescriptor will have to generate a PropertyDescriptor for each entry. Its name will be the key and its value will be ... well ... the property value.
If you are new to the PropertyGrid, I encourage you to read a lot about it because it can be quite complex and you will find a good list of resources to start here: <a href="http://www.propertygridresourcelist.com" rel="nofollow">www.propertygridresourcelist.com</a></p>
|
Timeouts WCF Services <p>How do the timeouts work in WCF? I know for example that you can configure <em>sendTimeout</em> and <em>receiveTimeout</em> for a clients binding. But how do they work?</p>
<p>MSDN describes <em>sendTimeout</em> as:</p>
<blockquote>
<p>A TimeSpan value that specifies the interval of time provided for a
send operation to complete. This value should be greater than or equal
to Zero. The default is 00:01:00.</p>
</blockquote>
<p>What are send operations/receive operations?</p>
|
<p>Client side:</p>
<ul>
<li>SendTimeout is used to initialize the OperationTimeout, which governs the whole interaction for sending a message (including receiving a reply message in a request-reply case). This timeout also applies when sending reply messages from a CallbackContract method.</li>
<li>OpenTimeout and CloseTimeout are used when opening and closing channels (when no explicit timeout value is passed).</li>
<li>ReceiveTimeout is not used.</li>
</ul>
<p>Server side:</p>
<ul>
<li>Send, Open, and Close Timeout same as on client (for Callbacks).</li>
<li>ReceiveTimeout is used by ServiceFramework layer to initialize the session-idle timeout.</li>
</ul>
<p>The source is <a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/84551e45-19a2-4d0d-bcc0-516a4041943d/">Brian McNamara on MSDN forums</a>.</p>
|
gridview dynamic image change in imagebutton <p>I have a gridview containing some data from db, and after a check I want to see a small cross/tick image in each row, due to the result of the check.How can I change the image url dynamically? </p>
|
<p>You could either use inline statement like <br/>
<code><%#Eval("check").ToString() == "1" ? "images/checked.gif" : "images/unchceked.gif")%></code></p>
<p>or use a function to get the result as follows:</p>
<pre><code><%# getImageUrl(Eval("value")) %>
Public Function getImageUrl(ByVal value As Integer) As String
If value = 0 Then
Return "images/unchceked.gif"
Else
Return "mages/checked.gif"
End If
End Function
</code></pre>
|
Class design for serialization - ideas or patterns? <p>Let me begin with an illustrative example (assume the implementation is in a statically typed language such as Java or C#).</p>
<p>Assume that you are building a content management system (CMS) or something similar. The data is hierarchically organised into <code>Folder</code>s. Each folder has a collection of children; a child may be a <code>Page</code> or a <code>Folder</code>. All items are stored within a root folder. No cycles are allowed. We have an acyclic graph.</p>
<p>The system will have a remote API and instances of <code>Folder</code> and <code>Page</code> must be serialized / de-serialized across the network. With a typical implementation of folder, in which a folder's children are a <code>List</code>, serialization of the root node would send the entire graph. This is unacceptable for obvious reasons.</p>
<p>I am interested to hear people have solved this problem in the past.</p>
<p>I have two potential suggestions:</p>
<ol>
<li><strong>Navigation by query</strong>: Change the domain model so that the folder class contains only a list of IDs for each child. To access a child we must query for it. Serialisation is now trivial since the graph ends at a well defined point. The major downside is that we lose type safety - the ID could be for something other than a folder/child.</li>
<li><strong>Stop and re-attach</strong>: During serialization stop whenever we detect a reference to a folder or page, send the ID instead. When de-serializing we must then look up the corresponding object for each ID and re-attach it at the relevant position in the nascent object.</li>
</ol>
|
<p>I don't know what kind of API you are trying to build, but your suggestion #1 sounds like it is close to what is recommended for REST style services and APIs. Basically, a <code>Folder</code> object would contain a list of URLs to its children.</p>
|
New web app project does not recognize the <asp: tag space <p>Visual Studio 2008 w/Sp1</p>
<p>To reproduce my problem I simply create a new .Net 2.0 web application and add a page with the following markup:</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication5._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:button id="button1" runat="server" />
</div>
</form>
</body>
</html>
</code></pre>
<p>what happens is that a line is drawn under :button with the statement "Validation (): Element 'button' is not supported."</p>
<p>I've tried repairing the .net framework; however, that had no impact. This started happening on two different machines, one is vista the other is XP within the past week.</p>
<p><strong>UPDATE:</strong> I closed this question because after spending 2 days trying to fix it I gave up and performed a complete reinstall of Visual Studio 2008. This resolved whatever was jacked up and now the machines in question work properly. I upvoted each of you for the help.</p>
|
<p>Try "<strong>B</strong>utton" (capital B):</p>
<pre><code><body>
<form id="form1" runat="server">
<div>
<asp:Button id="button1" runat="server" />
</div>
</form>
</body>
</code></pre>
|
Mysterious assets used in swf, not found anywhere in fla? <p>near the top of the code i see things like, </p>
<p>btn_dropdown._visible = false;
mcMenuBkg._visible = false;</p>
<p>but I can't find these assets anywhere in the library or in any code, how does this make any sense?</p>
<p>The movie clips in the library that look the same have different names and I can delete them entirely and they still show up when I compile and run, or I can add trace statements into their code and they never get called.</p>
<p>where on earth are these assets defined?</p>
|
<p>In theory, any clip you see at runtime could be dynamically created, by making an empty MC and drawing in whatever contents you like with the drawing API. However, if you see clips in the library that are similar to what's showing up at runtime, then it's very unlikely that that's happening.</p>
<p>Your first step should probably be another look through the library. Remember that instance names don't have to be the same as MC names; even if something is called "Menu Holder" in the library there might be an instance of it somewhere called "mcMenuBkg" or whatever. But the fact that you can delete stuff without changing the output is mysterious.</p>
<p>So, other possibilities: contents are being loaded externally, or imported via runtime sharing. If feasible, try moving your SWF to a temp directory and running it from there; that should break all loads (unless contents are loaded from a remote URL).</p>
<p>Or, you're looking at the wrong clips in the library. If it's a crufty project there may be unused stuff in there. Try expanding the library wide enough to see the "Use count" column, and select "update use counts" from the library menu. Anything with a count of 1 or higher is part of your FLA's stage content - either it's sitting on the main stage or it's a child of something that is. Clips with a use count of 0 may still be used if they have a linkage ID; they could be created at runtime with <code>attachMovie()</code>. However, for any clip with a use count of 0 and no linkage id, it's safe to assume that it's unused, and irrelevant to what happens at runtime.</p>
<p>If none of that helps, the only things that come to mind are sanity checks... open up everything on the stage and every clip with a linkage id, and check for empty/invisible MCs. Check the Movie's export settings to make absolutely sure the SWF you're checking is the same one being published. And just for grins, open up the "Scenes" panel and make sure that some diabolical fiend hasn't put important content on a separate scene where no sane man would look for it.</p>
<p>Vague answer for a vague question. :D Hope it helps...</p>
|
SelectedValue is invalid - doesn't exist in list - C#/ASP.NET <p>Exception is:
'Country' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value</p>
<pre><code>UserService.DsUserAttributes dsCountry = us_service.GetUserAttributeDropDown(systemId, "Country");
Country.DataSource = dsCountry.tblDropDownValues;
Country.DataTextField = "AttrValue";
Country.DataValueField = "Id";
Country.DataBind();
</code></pre>
<p>The values held within dsCountry.tblDropDownValues are:</p>
<pre><code>Id AttrValue AttrName
aefa28e0-a118-11dd-ad8b-080c210c9a66 PLEASE SELECT Country
213a743e-ea0b-419c-bd44-03b1c35241b3 USA Country
eefa1387-8dc0-11d8-975f-13da67a41a5d CANADA Country
</code></pre>
|
<p>Try binding the data on postback. It sounds like when the event handler is accessing the DropDownList, it hasn't been repopulated with the values you are initially binding to the DropDownList.</p>
<p>Also, remember to bind early enough so that it is bound before the event handler starts its processing. OnInit or OnLoad should be good enough.</p>
<p>Otherwise, might need some more details:</p>
<ol>
<li>When is the exception occurring? During the rendering, or on the postback in the event handler?</li>
<li>Do you have a stack trace on the error that might point to the point in the code where the selected value is accessed?</li>
<li>When are you binding the data?</li>
</ol>
|
PHP syntax highlighting <p>I'm searching for a <strong>PHP syntax highlighting engine</strong> that can be customized (i.e. I can provide my <strong>own tokenizers</strong> for new languages) and that can handle several languages <em>simultaneously</em> (i.e. on the same output page). This engine has to work well together with <strong>CSS classes</strong>, i.e. it should format the output by inserting <code><span></code> elements that are adorned with <code>class</code> attributes. Bonus points for an extensible schema.</p>
<p>I do <em>not</em> search for a client-side syntax highlighting script (JavaScript).</p>
<p>So far, I'm stuck with <a href="http://qbnz.com/highlighter/">GeSHi</a>. Unfortunately, GeSHi fails abysmally for several reasons. The main reason is that the different language files define completely different, inconsistent styles. I've worked hours trying to refactor the different language definitions down to a common denominator but since most definition files are in themselves quite bad, I'd finally like to switch.</p>
<p>Ideally, I'd like to have an API similar to <a href="http://coderay.rubychan.de/">CodeRay</a>, <a href="http://pygments.org/">Pygments</a> or the JavaScript <a href="http://code.google.com/p/syntaxhighlighter/">dp.SyntaxHighlighter</a>.</p>
<h2>Clarification:</h2>
<p>I'm looking for a code highlighting software written <em>in</em> PHP, not <em>for</em> PHP (since I need to use it from inside PHP).</p>
|
<p>Since no existing tool satisfied my needs, I wrote my own. Lo and behold:</p>
<h2><a href="https://github.com/klmr/hyperlight">Hyperlight</a></h2>
<p>Usage is extremely easy: just use</p>
<pre><code> <?php hyperlight($code, 'php'); ?>
</code></pre>
<p>to highlight code. Writing new language definitions is relatively easy, too â using regular expressions and a powerful but simple state machine. By the way, I still <em>need</em> a lot of definitions so feel free to contribute.</p>
|
Any good "contact us" recipes for Cherrypy? <p>I'm looking to implement a "Contact Us" form with Cherrypy and was wondering: Is there a good recipe (or a BSD licensed set of code) that I could use instead of reinventing the wheel?</p>
<p>Ideally, this would be Cherrpy 3.1 compatible.</p>
|
<p>Well, I had to look into a solution. This works (ugly, and w/o Javascript validation) -- using the smtplib lib. Also, note that I stole Jeff's captcha for this example. Anyone using this will need to change it. </p>
<p><strong>EDIT:</strong> I added validation.</p>
<pre><code>#!/usr/local/bin/python2.4
import smtplib
import cherrypy
class InputExample:
@cherrypy.expose
def index(self):
return "<html><head></head><body><a href="contactus">Contact Us</a></body></html>"
@cherrypy.expose
def contactus(self,message=''):
return """
<html>
<head><title>Contact Us</title>
<script type="text/javascript">
function isNotEmpty(elem)
{
var str = elem.value;
var re = /.+/;
if (!str.match(re))
{
elem.focus();
return false;
}
else
{
return true;
}
}
function isEMailAddr(elem)
{
var str = elem.value;
var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!str.match(re))
{
return false;
}
else
{
return true;
}
}
function validateForm(form)
{
if (isNotEmpty(form.firstName) && isNotEmpty(form.lastName))
{
if (isNotEmpty(form.email))
{
if (isEMailAddr(form.email))
{
if (isNotEmpty(form.captcha))
{
if ( form.captcha.value=='egnaro'.split("").reverse().join(""))
{
if (isNotEmpty(form.subject))
{
alert("All required fields are found. We will respond shortly.");
return true;
}
}
else
{
alert("Please enter the word as displayed in the image.");
return false;
}
}//captcha empty
}
else
{
alert("Please enter a valid email address.");
return false;
} //email
} //email
} //first and last name
alert("Please fill in all required fields.");
return false;
}
</script>
</head>
<body>
<p>%(message)s</p>
<form method='POST' action='contactUsSubmitted' onsubmit='return validateForm(this)'>
<label for="firstName">First Name: </label>
<input type="text" id="firstName" name="firstName" /> (required)<br/>
<label for="lastName">Last Name: </label>
<input type="text" id="lastName" name="lastName" /> (required)<br/>
<label for="email">E-mail address: </label>
<input type="text" id="email" name="email" /> (required)<br/>
<label for="phone">Phone number: </label>
<input type="text" id="phone" name="phone" /> <br/><br/>
<!--THIS NEEDS TO BE CHANGED TO MATCH YOUR OWN CAPTCHA SCHEME!! -->
<label for="captcha">Enter the word<br /><img alt="rhymes with.." src="http://www.codinghorror.com/blog/images/word.png" width="99" height="26" border="0" /></label><br />
(<a href="http://www.codinghorror.com/blog/sounds/captcha-word-spoken.mp3">hear it spoken</a>)<br />
<input tabindex="3" id="captcha" name="captcha" /><br /><br />
<label for="subject">Subject: </label>
<input type="text" id="subject" name="subject" /> (required)<br/>
<label for="body">Details: </label>
<textarea id="body" name="body"></textarea><br/>
<input type='submit' value='Contact Us' />
</form>
</body>
</html>
"""%{'message':message}
@cherrypy.expose
def contactUsSubmitted(self, firstName, lastName, email, phone, captcha, subject, body ):
if captcha[::-1] != 'egnaro':
return self.contactus("Please reenter the word you see in the image." )
self.sendEmail('mail2.example.com','mailbox_account','mailbox_pwd','me@example.com',email,
'Website Contact: '+subject, 'Sender Email: ' + email + '\r\n'
'Name: ' + firstName + ' ' + lastName + '\r\n' + 'Phone: ' + phone + '\r\n' + body)
return self.index()
def sendEmail(self,smtpServer, mailboxName, mailboxPassword, contactEmail,senderEmail,subject,body):
server = smtplib.SMTP(smtpServer) #'smtp1.example.com')
server.login(mailboxName, mailboxPassword)
msg = "To: %(contactEmail)s\r\nFrom: %(senderEmail)s\r\nSubject: %(subject)s\r\nContent-type: text/plain\r\n\r\n%(body)s"
msg = msg%{'contactEmail':contactEmail,'senderEmail':mailboxName + '@example.com','subject':subject,'body':body}
server.sendmail(contactEmail, contactEmail, msg) #This is to send it from an internal account to another internal account.
server.quit()
cherrypy.root = InputExample()
cherrypy.config.update ( file = 'development.conf' )
cherrypy.server.start()
</code></pre>
|
How to add a dynamic weather ticker to the webpage <p>All Weather Tickers I found are static and if the user wants to select a zip code it links you to a different page.</p>
<p>Do you know any weather ticker that just gets the new info in the same page?</p>
|
<p><a href="http://demos.openrico.org/weather_demo" rel="nofollow">RICO</a> has an AJAX weather widget that seems to be along the lines of what you want.</p>
|
Can initialization list in constructors be used in template classes? <p>I find that most books concerning C++ templates don't tell anything about whether it's possible or not to use initialization list in constructor of a template class.</p>
<p>For example, I have code like this:</p>
<pre><code>template <class T>
class Stack {
T* data;
std::size_t count;
std::size_t capacity;
enum {INIT = 5};
public:
Stack() {
count = 0;
capacity = INIT;
data = new T [INIT];
}
</code></pre>
<p>Can I replace the constructor with</p>
<pre><code>Stack(): count(0), capacity(INIT), data(new T [INIT])
</code></pre>
|
<p>Yes. Did the compiler tell you otherwise?</p>
|
Does foreach always create a copy on a none reference in PHP? <p>I'm wondering if PHP has this optimization built in. Normally when you call foreach without using a reference it copies the passed array and operates on it. What happens if the reference count to that array is only 1?</p>
<p>Say for example if getData returns some array of data.</p>
<pre><code>foreach(getData() as $data)
echo $data;
</code></pre>
<p>Since the array returned by getData() only has one reference shouldn't it just be used by reference and not copied first or does php not have this optimization?</p>
<p>This seems like a simple optimization that could help a lot of badly written code.</p>
|
<p>I can't say for certain, but PHP normally uses "copy on write", so everything is a reference until you try to write to it, at which time a copy is made and you write to the copy.</p>
|
Window Handle and window dimension <p>The MFC application that i created is dialog based. Just one dialog thats all. How do I get the window handle to this window, while the application is performing the InitDialog. I need to find out its dimension as well. GetForegroundWindow not necessarily gives you the handle to this window that is loading up </p>
|
<p>Check the m_hWnd member of your dialog object. GetClientRect() should work to give you the size of client (interior) of the dialog. GetWindowRect() will give you the total size including window borders, but the position will be off.</p>
|
How would you write a non-recursive algorithm to calculate factorials? <p>How would you write a non-recursive algorithm to compute <code>n!</code>?</p>
|
<p>Since an Int32 is going to overflow on anything bigger than 12! anyway, just do:</p>
<pre><code>public int factorial(int n) {
int[] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320,
362880, 3628800, 39916800, 479001600};
return fact[n];
}
</code></pre>
|
Can I have url_for use a prefix option in Ruby on Rails? <p>In a project I am working on, Apache is set up to only forward requests that come in as /prefix/* to mongrel. How can I tell ruby on rails to generate all URLs with that prefix? </p>
<p>I have the routes set up for forward to the correct controller action by doing this:</p>
<pre><code>map.connect 'sfc/:controller/:action'
</code></pre>
<p>but that doesn't seem to affect the way that the url writer generates the URLs.</p>
<p>Any ideas?</p>
|
<p>The <code>RAILS_RELATIVE_URL_ROOT</code> environment variable should do the trick, though I haven't tried it myself.</p>
|
Installing a rails plugin from a Git repository <p>I've been trying to install <a href="http://thoughtbot.com/projects/shoulda" rel="nofollow">Shoulda</a></p>
<pre><code>script/plugin install git://github.com/thoughtbot/shoulda.git
</code></pre>
<p>but all I get is:</p>
<pre><code>removing: C:/Documents and Settings/Danny/My Documents/Projects/Ruby On Rails/_ProjectName_/vendor/plugins/shoulda/.git
>
</code></pre>
<p>And the <code>vender/plugins</code> directory is empty. I have Rails 2.1.1 installed as a gem and have verified that 2.1.1 is loaded (using a puts inserted into config/boot.rb). Any ideas about what's going on?</p>
<p>(this is on a windows box)</p>
|
<p>Do you have git installed? If you don't, it will just not work. Rails assumes git is installed and can be found in your PATH.</p>
<p>You can get Git for Windows <a href="http://code.google.com/p/msysgit/downloads/list" rel="nofollow">here</a>.</p>
|
How do I find where my .Net app is leaking Windows handles? <p>I've got a WinForms .Net app that runs over a lot of XPS documents (thousands) and during this run the number of handles (according sysinternals process monitor and task manager) increases by between 3-10 for each document. I heavily suspect that these are handles that are opened and not closed by the MS .Net XPS framework libraries but I can't track it down.</p>
<p>Despite stepping through the code the handle count increases at different points during the same run. For example, one pass through the loop and the handle count will jump by 1 on one line and next time it might not, or it might jump by 2. So I suspect the XPS com components have a handle leak.</p>
<p>Memory use is fine though, but if I keep exhausting handles like this then I'll crash the app and maybe the desktop.</p>
<p>So far I have tried sysinternals process explorer to look at the handles but they are all marked as with no more detail. Also used handle.exe from sysinternals and this does not show any significant different between a before, during and after snapshot.</p>
<p>Any clues on how to track down where the handles are going? I think I'm going to have to simplify to a single threaded console app to test.</p>
<p>Regards</p>
<p>Ryan</p>
|
<p>Possibly stupid, but have you checked that you're disposing everything that's disposable?</p>
|
Has anyone used or written an Ant task to compile (Rhino) JavaScript to Java bytecode? <p>I'd like to use the <a href="https://developer.mozilla.org/en/Rhino_JavaScript_Compiler" rel="nofollow">Rhino JavaScript</a> compiler to compile some JavaScript to .class bytecode files for use in a project. It seems like this should already exist, since there are groovyc, netrexxc, and jythonc tasks for Groovy, NetREXX(!) and Jython, respectively. Has anyone used or written such an Ant task, or can anyone provide some tips on how to write one?</p>
<p>Ideally it would have some way to resolve dependencies among JavaScript or Java classes.</p>
|
<p>I'm using <a href="http://requirejs.org/">RequireJS</a> in my project, which includes a script that traces out dependencies between modules, and combines them into a single JavaScript file. Optionally, it can also minify the combined js file with the Google Closure compiler. Once it's in this form, where all dependencies are included in a single js file, the file can be easily compiled using jsc. </p>
<p>Here's a segment of my ant script which I use to create the single combined js file, compile it to a class file, and then create an executable JAR:</p>
<pre><code><target name="compile-single-js">
<mkdir dir="${build-js}"/>
<java classname="org.mozilla.javascript.tools.shell.Main">
<classpath>
<path refid="rhino-classpath"/>
<path refid="closure-classpath"/>
</classpath>
<arg value="${js-build-script}"/>
<arg value="${js-build-dir}"/>
<arg value="name=${build-js-main-rhino-frontend-module}"/>
<arg value="out=${build-js-main}"/>
<arg value="baseUrl=."/>
<arg value="includeRequire=true"/>
<arg value="inlineText=true"/>
<arg value="optimize=none"/>
</java>
</target>
<target name="compile-single-class" depends="compile-single-js">
<mkdir dir="${build-class}"/>
<!-- TODO: set -opt -->
<java classname="org.mozilla.javascript.tools.jsc.Main">
<classpath>
<path refid="rhino-classpath"/>
</classpath>
<arg value="-o"/>
<arg value="${build-class-main-name}.class"/>
<arg value="${build-js-main}"/>
</java>
<move file="${build-js}/${build-class-main-name}.class" todir="${build-class}"/>
</target>
<target name="jar-single-class" depends="compile-single-class">
<mkdir dir="${build-jar}"/>
<jar destfile="${build-jar-main}"
basedir="${build-class}"
includes="${build-class-main-name}.class">
<manifest>
<attribute name="Main-Class" value="${build-class-main-name}" />
</manifest>
</jar>
</target>
</code></pre>
<p>The complete build script can be found <a href="https://svn.apache.org/repos/asf/commons/sandbox/gsoc/2010/scxml-js/trunk/build.xml">here</a>.</p>
|
Overriding CreateObject Function in VBScript <p>Need help to figure out how to overide the default CreateObject() function in VBScript with my own.</p>
<p>Basically the same exact thing as this example in VB6:</p>
<p><a href="http://www.darinhiggins.com/2007/08/22/TheVB6CreateObjectFunction.aspx" rel="nofollow">http://www.darinhiggins.com/2007/08/22/TheVB6CreateObjectFunction.aspx</a></p>
<p>I just need to adapt this to work in VBScript. The only thing I cannot figure out is this line:</p>
<p>VBA.CreateObject(Class$, ServerName$)</p>
<p>How do I refer to "VBA" in VBSript?</p>
<p>any help would be appreciated</p>
|
<p>This quick test seems to work...</p>
<pre><code>Function CreateObject(className, serverName)
'---- override the CreateObject
' function in order to register what
' object is being created in any error message
' that's generated
Dim source, descr, errNum
WScript.echo "In custom CreateObject"
If Len(serverName) > 0 Then
Set CreateObject = WScript.CreateObject(className, serverName)
Else
Set CreateObject = WScript.CreateObject(className)
End If
End Function
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject", "")
path = fso.GetAbsolutePathName(".")
WScript.echo path
</code></pre>
<p>No guarantees! ;-)</p>
|
Sharepoint: Web Part vs. ASP.NET User Control <p>When creating web parts for Sharepoint, is it better to create an actual web part, or is using and ASP.NET User Control (.ascx) just as good?</p>
<p>I already know how to create the user controls that I need, so it seems like the extra effort of creating a web part is just unnecessary leg work.</p>
<p>What are the advantages of using a web part over just creating and ASP.NET user control?</p>
|
<p>I am a big fan of user controls except for the simplest web parts. I create a webpart that instantiates and loads the user control. There are other tools out there that you can use to expose your user control, like smartpart, but I would suggest you wrap it up yourself, as it is a good learning experience. Once you have done it once, you basically have a template for any other webpart you want to create.</p>
<p>Good Luck!</p>
|
How to join another MySQL table when using Master/Detail Sample Form in Netbeans? <p>I am trying to implement an application by using MySQL/JAVA and I found this tool in netbeans to easily create a new form for an existing table. (edit, insert, delete etc.)
Is there an easy way to modify the code to join another table to display fields from that table.</p>
<p>Example:
I have an employee table that has a foreign key TitleID and another table called Title that has TitleID and TitleName.
I want to display TitleName instead of TitleID in the master table employee.</p>
|
<p>I do not think you will find something like that in NetBeans. However, if your DB design is simple enough (i.e. title example is real), you can try to use updatable view (<a href="http://dev.mysql.com/doc/refman/5.0/en/create-view.html" rel="nofollow">more info</a>) and use it as a table. </p>
<p>In complicated cases you will have to rewrite (extend?) whatever class you are using for DB access. But it is still should be possible to use whatever UI component you have been using.</p>
|
How do you compress objects stored in session / cache? <p>Scott Hanselman recently posted a <a href="http://www.hanselman.com/blog/TheWeeklySourceCode35ZipCompressingASPNETSessionAndCacheState.aspx" rel="nofollow">blog article</a> describing how to compress strings stored in the session / cache. This looks fairly promising, but the majority of data that I am storing in the session / cache are not strings but custom classes. How would you go about compressing these?</p>
<p>My initial thought would be to utilize the BinaryFormatter to serialize the object first (just like the ASP.NET framework would do normally when storing custom class objects into the session / cache), then compress the resulting byte array. However, this has the adverse side effect that the retrieved data from the session / cache would be readonly (since decompressing and deserializing would create a new in-memory object).</p>
<p>In other words, if my code currently looks like the following, is there a way to compress its storage into the session?</p>
<pre><code>MyClass foo = new MyClass();
Session["foo"] = foo;
MyClass retrievedFoo1 = (MyClass) Session["foo"];
retrievedFoo1.Property1 = "property 1";
// retrievedFoo2.Property1 should equal "property 1"!
MyClass retrievedFoo2 = (MyClass) Session["foo"];
</code></pre>
|
<p>Firstly I'd look at why you need to compress the data in your session / cache. Compression should be an act of last resort, better programming should be the first. </p>
<p>Are you running out of memory, and if so, which objects are consuming the most? This should point you in the direction for code improvement to reduce the amount of memory used.</p>
<p>If your app is optimised the best it can with the objects it needs, you may want to look at out of memory storage such as a database or file system to cache larger objects (which is where serialisation comes in handy).</p>
<p>You could also place InProc sessions on a different server to the webserver to improve scalability and distribute the site over a web farm.</p>
|
What does a type followed by _t (underscore-t) represent? <p>This seems like a simple question, but I can't find it with the Stack Overflow search or Google. What does a type followed by a <code>_t</code> mean? Such as</p>
<pre><code>int_t anInt;
</code></pre>
<p>I see it a lot in C code meant to deal closely with hardwareâI can't help but think that they're related.</p>
|
<p>As Douglas Mayle noted, it basically denotes a type name. Consequently, you would be ill-advised to end variable or function names with '<code>_t</code>' since it could cause some confusion. As well as <code>size_t</code>, the C89 standard defines <code>wchar_t</code>, <code>off_t</code>, <code>ptrdiff_t</code>, and probably some others I've forgotten. The C99 standard defines a lot of extra types, such as <code>uintptr_t</code>, <code>intmax_t</code>, <code>int8_t</code>, <code>uint_least16_t</code>, <code>uint_fast32_t</code>, and so on. These new types are formally defined in <code><stdint.h></code> but most often you will use <code><inttypes.h></code> which (unusually for standard C headers) includes <code><stdint.h></code>. It (<code><inttypes.h></code>) also defines macros for use with the <code>printf()</code> and <code>scanf()</code>.</p>
<p>As Matt Curtis noted, there is no significance to the compiler in the suffix; it is a human-oriented convention.</p>
<p>However, you should also note that POSIX defines a lot of extra type names ending in '<code>_t</code>', and reserves the suffix for the implementation. That means that if you are working on POSIX-related systems, defining your own type names with the convention is ill-advised. The system I work on has done it (for more than 20 years); we regularly get tripped up by systems defining types with the same name as we define.</p>
|
.NET compact framework and ActiveSync <p>Is there a way that my .NET CF app running on a Windows CE device can know when the device is docked/synced with the PC?</p>
|
<p>I believe this will help <a href="http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.status.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.status.aspx</a></p>
|
Force windows to refresh a disk FAT <p>I have a separate partition on my disk formatted with FAT32. When I hibernate windows, I want to be able to load another OS, create/modify files that are on that partition, then bring Windows out of hibernation and be able to see the changes that I've made.</p>
<p>I know what you're going to type, "Well, you're not supposed to do that!" and then link me to some specs about how what I'm trying to do is wrong/impossible/going to break EVERYTHING. However, I'm sure there's some way I can get around that. :)</p>
<p>I don't need the FAT32 partition in Windows, except to read the files that were written there, then I'm done - so whatever the solution is, it's acceptable for the disk to be completely inaccessible for a period of time. Unfortunately, I can't take the entire physical disk offline because it is just a partition of the same physical device that windows is installed on -- just the partition.</p>
<p>These are the things I've tried so far...</p>
<ol>
<li>Google it. I got at least one "this is NEVER going to happen" answer. Unacceptable! :)</li>
<li>Unmount the disk before hibernating. Mount after coming out of hibernation. This seems to have no effect. Windows still thinks the FAT is the same as it was before, so whatever data I wrote to disk is lost, and any files I resized are corrupted. If any of the file was cached, it's even worse.</li>
<li>Use DeviceIoControl to call IOCTL_DISK_UPDATE_PROPERTIES to try and refresh the disk (but the partition table hasn't changed, so this doesn't really do anything).</li>
</ol>
<p>Is there any way to invalidate the disk/volume read cache to force windows to go back to the disk? </p>
<p>I thought about opening the partition and reading/writing directly by using libfat and bypassing the cache or something is overkill.</p>
|
<p>So I finally got a solution to my problem. In my mind, I associated Mount Point with Mount. These are NOT the same thing. Removing all of the volume mount points does not make the volume unmounted. It's still mounted but not in the sense that you have a path you can access in explorer.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd143253.aspx" rel="nofollow">This is the article</a> that started it all.
It also goes to show that searching for your EXACT problem, as opposed to the perceived problem can help a lot!</p>
<p>So there were a couple of solutions, one was to constantly call NtSetSystemInformation() in a tight loop to set the "SYSTEMCACHEINFORMATION" property to essentially empty/clear the cache whenever the system is going to hibernation. Then stop the loop when you come out. This, to me, seemed like it could affect system performance. So I discarded it.</p>
<p>Even better though, is the recommended solution to a slightly different problem presented in this MSDN article, which provides direction to an even better solution to the problem: <a href="http://msdn.microsoft.com/en-us/library/dd143253.aspx" rel="nofollow">Dismounting Volumes in a Hibernate Once/Resume Many Configuration</a></p>
<p>Now I have a service which will flush the write caches, then lock and dismount the volume whenever the system goes into hibernation/sleep and release the lock on the volume as soon as it comes out. </p>
<p>Here's a little bit of code.
OnHibernate></p>
<pre><code>volumeHandle = CreateFile(volumePath,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0 );
FlushFileBuffers( volumeHandle );
DeviceIoControl( volumeHandle, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL ) ;
DeviceIoControl( volumeHandle, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL );
//Keep the handle open here.
//System hibernates.
</code></pre>
<p>OnResume></p>
<pre><code>DeviceIoControl( volumeHandle, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL )
CloseHandle(volumeHandle)
</code></pre>
<p>Hopefully this helps someone else out in the future :)</p>
|
SharePoint - ASP.Net Controls Integration <p>I have basically two separate sites, a SharePoint collaboration site, and an ASP.Net application site. The only linkage between the two are the hyperlinks going back and forth, and the user validation on the behalf of the SharePoint site. The user will enter and be authenticated through the SharePoint site and then may browse to the ASP.Net application.</p>
<p>What is the best way to integrate the two sites together? Is there an easy way to give the users a seamless experience while maintaining two sites?</p>
<p>UPDATE: I followed all of your advice and settled on going with Chris' answer.</p>
<p>Andrew Connel actually deploys the .aspx code behind pages as a SharePoint feature.</p>
<p>He sets out how to do this on his site <a href="http://www.andrewconnell.com/blog/articles/UsingCodeBehindFilesInSharePointSites.aspx" rel="nofollow">here.</a></p>
|
<p>You can use the ASP.NET Membership Provider on a SharePoint site. That is probably you're best option if you're not able to go with Windows Authentication.</p>
<p>There's a good article by Andrew Connell on how to set up the Membership Provider for SharePoint. It is MOSS-described but the practices can be ported to WSS.</p>
<p><a href="http://www.andrewconnell.com/blog/articles/HowToConfigPublishingSiteWithDualAuthProvidersAndAnonAccess.aspx" rel="nofollow">http://www.andrewconnell.com/blog/articles/HowToConfigPublishingSiteWithDualAuthProvidersAndAnonAccess.aspx</a></p>
|
How do you Manage Infragistics WebGrid Data from JavaScript/Ajax code? <p>I am working on a project that I need to use the Infragistics WebGrid control for some lists of data. I am loading the data on the client-side using JavaScript for display on a Map, and then I need to display that same data within multiple WebGrids. All the data available will be displayed in the WebGrids, but only a subset of the data (only that which is currently within view) will be plotted on the Map at any given time. Since I am loading the data using JavaScript/Ajax, I would like to only load it once, and use the same mechanism to populate the WebGrid control with data too.</p>
<p>Does anyone have any tips/pointers on working with the WebGrid completely from within client-side JavaScript/Ajax code?</p>
|
<p>The Infragistics webgrids expose a very complex client side object model that you will be able to use to populate your data client side.</p>
<p>The first thing you will want to do is get a look at the full CSOM for the webgrid control, you can find the current doc version at: http://help.infragistics.com/NetAdvantage/NET/2008.3/CLR2.0/</p>
<p>To make a short example, you will need to grab a refence to your grid(s) and then add some rows and data. It would probably be easier to setup the column definitions for your grids at design time, rather than try to do it all in the javascript.</p>
<p>First: get a refrence to your grid:</p>
<pre><code>var grid = igtbl_getGridById('dataGridControlID');
</code></pre>
<p>Then add a new row:</p>
<pre><code>var newRow = grid.Rows.addNew()
</code></pre>
<p>After thats done you can loop the columns of your row to fill the data:</p>
<pre><code>var oCols = newRow.Band.Columns;
for(var i=0; i < oCols.length; i++) {
newRow.getCell[i].setValue(yourValue)
}
</code></pre>
<p>or address each one by key to populate its data:</p>
<pre><code>newRow.getCellFromKey(colKey).setValue(yourValue,fireEvents);
</code></pre>
|
C++ Parent class calling a child virtual function <p>I want a pure virtual parent class to call a child implementation of a function like so:</p>
<pre><code>class parent
{
public:
void Read() { //read stuff }
virtual void Process() = 0;
parent()
{
Read();
Process();
}
}
class child : public parent
{
public:
virtual void Process() { //process stuff }
child() : parent() { }
}
int main()
{
child c;
}
</code></pre>
<p>This should work, but I get an unlinked error :/ This is using VC++ 2k3</p>
<p>Or shouldn't it work, am I wrong?</p>
|
<p>Title of the following article says it all: <a href="http://www.artima.com/cppsource/nevercall.html">Never Call Virtual Functions during Construction or Destruction</a>.</p>
|
Image Slider with Silverlight <p>I have a requirement of creating an Image slider using Silverlight. I need to display 5 images at first. There will be two buttons previous and next. When I'll click the next button another new 5 images will be shown in place of previously diplayed images. Would it be possible for anyone to tell me the solution for this? </p>
<p>Someone please help me. </p>
|
<p>Check this out.
<a href="http://www.silverlightshow.net/items/Image-slider-control-in-Silverlight-1.1.aspx" rel="nofollow">Image slider control in Silverlight 2</a></p>
<p>Slide.Show 2 - Another cool sample from <a href="http://www.vertigo.com/slideshow.aspx" rel="nofollow">Vertigo</a>. Source available at <a href="http://www.codeplex.com/SlideShow2" rel="nofollow">codeplex</a>.</p>
|
Extra backslashes being added in PHP <p>My <sub>crappy</sub> web host did some upgrades the other day and some settings have gone awry, because looking at our company's wiki (MediaWiki), every quote is being escaped with a backslashes. It's not even just data which is being posted (ie: the articles) which are affected, but also the standard MediaWiki text. eg:</p>
<blockquote>
<p>You\'ve followed a link to a page that doesn\'t exist yet. To create the page, start typing in the box below (see the help page for more info). If you are here by mistake, just click your browser\'s \'\'\'back\'\'\' button. </p>
</blockquote>
<p>The first thing I did was disable <code>magic_quotes_gpc</code> AND <code>magic_quotes_runtime</code> using a <code>.htaccess</code> file, but this is still occurring. My <code>php_info()</code> reports this:</p>
<pre><code>Setting Local Value Master Value
magic_quotes_gpc Off On
magic_quotes_runtime Off On
magic_quotes_sybase Off Off
</code></pre>
<p>Any ideas?</p>
|
<p>You may want to confirm that the data in your DB hasn't been corrupted. If you were addslash()ing your data when, unbeknownst to you, magic_quotes had been turned on, then you'd be double-slashifying data going into your DB.</p>
|
looking at client controls on the server <p>I'm just starting out with the whole ajax thing and I need some help. I have a form where the users will have the ability to add multiple e-mail addresses to a record. When the user clicks add a new e-mail address, I am going to perform an ajax call that will insert the email address and then get the current e-mails to be displayed for editing. Sounds fine, but the only problem I have is when the form submits I want to be able to access those values server side, as well as store the sequence numbers from the db so the emails can be updated on the final submit. In a repeater, I'd store the sequence number in a hidden field and then loop through the items, but I can't do that when I'm not using a repeater. I'd like to avoid using the update panel because of the large network traffic. I suppose I could use request.forms collection, but how would I store the sequence numbers in such a way that the users couldn't see them? Am I totally off base?</p>
|
<p>Why couldn't you use hidden fields anyway? As long as they are inside the <code>form</code> element it does not matter where they are, does it?</p>
<p>Say, for example, that your emails fields have <code>name</code> attribute set like "email_1", "email_2", etc. You could set <code>name</code> for your hidden fields like "seq_email_1", "seq_email_2"...</p>
<p>And then you can iterate through Request.Form and read emails and sequence numbers:</p>
<pre><code>foreach (string key in Request.Form.AllKeys) {
if (key.StartsWith("email_")) {
string email = Request.Form[key];
int seq = int.Parse(Request.Form["seq_" + key]);
// process email with seq number
}
}
</code></pre>
|
x86 question about bit comparisons <p>Im having a problem with a final part of my assignment. We get in a stream of bits, etc etc, in the stream is an integer with the number of 1's in the text portion. I get that integer and its 24 which is correct, now i loop through the text data i get and i try to count all the 1's in there. But my proc is always returning zero.</p>
<p>I was able to make sure it was looping properly and it is.</p>
<p>The text = Hello
which is 16 1's, here is my proc for looping through that text to count the number of ones in it.</p>
<pre><code>sub AX,AX
sub SI,SI
mov bx,[bp+6] ;get message offset
@@mainLoop:
mov cx,8
mov dh,80h
cmp byte ptr [bx + si],0
je @@endChecker
@@innerLoop:
test byte ptr [bx + si],dh
jz @@zeroFound
inc AX
@@zeroFound:
shr bh,1
loop @@innerLoop
@@continue:
inc si
jmp @@mainLoop
</code></pre>
<p>the rest of the proc is just push/pops. What im wanting this to actually do is use TEST to compare 100000000 to a byte, if its a 1 inc AX else shift right the mask by 1 and loop a whole byte, than inc to next byte and do again.</p>
|
<p>'shr bh,1' should probably be 'shr dh,1', no?</p>
|
Applications using Decimal versus double . . <p>I wanted to see if folks were using decimal for financial applications instead of double. I have seen lots of folks using double all over the place with unintended consequences . .</p>
<p>Do you see others making this mistake . . .</p>
|
<p>We did unfortunately and we regret it. We had to change all doubles to decimals. Decimals are good for financial applications. You can look at this article
<a href="http://www.codeproject.com/KB/recipes/MoneyTypeForCLR.aspx" rel="nofollow">A Money type for the CLR</a>:</p>
<blockquote>
<p>A convenient, high-performance money
structure for the CLR which handles
arithmetic operations, currency types,
formatting, and careful distribution
and rounding without loss.</p>
</blockquote>
|
How to configure security when calling WCF Service from .Net 2.0 Client <p>I have a WCF service up and running and am able to communicate between the service and a .Net 2.0 Client using basicHttpBinding. </p>
<p>I now need to lock down the WCF service so that it can only be called by authenticated clients.</p>
<p>I have control over the clients that will be calling my service. The clients are part of a product that will be installed in the wild and "phoning home" to push and pull data. The client app is written for .Net 2.0 framework and cannot be upgraded to 3.0 or 3.5 at this time. I cannot add windows user accounts to the client machines.</p>
<p>What are my options for securing the WCF Service and being able to authenticate from my .Net 2.0 clients? Also, data needs to be passed over https.</p>
<p>I've been searching the web, and feel like I'm on a wild goose chase.</p>
|
<p>You can configure a WCF endpoint to use <strong>2-way SSL authentication</strong>. That means that you can require clients to present an X.509 certificate that confirms their identity whenever they make a request to the service.<br /><br/>
On the server side of things, you can use one of the built-in validation schemes in WCF or provide your own validation logic to check the X.509 certificate.<br/>
If you were hosting your service in IIS, it would be trivial to configure SSL to require client certificates at the <strong>transport-level</strong>. However, you can find a good guide on how to implement this behaviour in a self-hosted WCF service here:</p>
<p><a href="http://leastprivilege.com/2007/08/25/certificate-based-authentication-and-wcf-message-security/" rel="nofollow">http://leastprivilege.com/2007/08/25/certificate-based-authentication-and-wcf-message-security/</a></p>
<p>I haven't tried this myself but, since this creates a security requirement at the <strong>message-level</strong>, I think you will have to use <strong>wsHttpBinding</strong> to enforce it in your WSDL contract, since imposing security requirements to access a web service is part of the WS-* standards.</p>
<p>If you have to use <strong>basicHttpBinding</strong>, you can try this solution instead that moves things up at the transport-level:</p>
<p><a href="http://leastprivilege.com/2007/08/26/certificate-based-authentication-and-wcf-mode-independent/" rel="nofollow">http://leastprivilege.com/2007/08/26/certificate-based-authentication-and-wcf-mode-independent/</a></p>
<p>Hope this helps</p>
|
How to backup project folders to local desktop if path more than 255 characters? <p>For e.g. if i am storing some files on a network server which is under many hierarchical folders.</p>
<p>Then i want to do backup. But i always encounter issue because the file path is more than 255?</p>
<p>How can i resolve this issue or work around it?</p>
|
<p>Preface: I'm assuming the OS of the machine you want to copy the files to is some flavor of Windows.</p>
<p>The first part of Mark Bessey's is somewhat correct, however even on modern versions of windows with modern filesystems (NTFS for example) you can still run into problems.</p>
<p>I suspect the limitation you're running into is due to MAX_PATH, which is a predefined limit on the length of a path that many APIs on Windows will accept.</p>
<p>You may try using <a href="http://en.wikipedia.org/wiki/Robocopy" rel="nofollow" title="Robocopy">Robocopy</a> to do the backup as it is able to create paths longer than the MAX_PATH limitation. However, most applications will not be able to access these files.</p>
<p>Taring or Zipping the files may be a good plan but it seems unlikely that you'd be able to unzip or untar them to a Windows machine.</p>
|
removing password for multiple PDF files <p>so I have a huge collection of PDF files that I need to extract text from.
The files are encrypted, but I know the password for them. I'm looking for a way to automate the process of extracting the text.<br><br>
I can manually open the file in Acrobat professional, remove security by typing in the password, and then save as .txt file. But there's no way to automate that with batch processing for the 600 files.<br><br>
I'm looking for a some tool to help with this. I'm good with Perl, so I tried the various PDF handling modules from CPAN, but they're failing to read the encrypted documents. Anyone has any solution for this?</p>
|
<p>Take a look at pdftk. It's console-based and handles password-secured PDF files.</p>
|
Eclipse: Hide paths in the "Open resource" dialog <p>Is there any way to define what the "Open Resource" dialog in Eclipse should show?</p>
<p>If you work with svn you don't want the *.svn files to show up. (I know there is a fix out for this one but does there exist a more general one?)</p>
|
<p>At the top-right corner of the "Open Resource" there is a small blue arrow.
Click it and "Select Working Set".
Create a new working set as required to include what you need</p>
|
What is the impact of virtualisation on cryptographically strong random number generators? <p>/dev/random and /dev/urandom use environmental noise to generate randomness. </p>
<p>With a virtualised server there can be multiple instances of an Operating System on one hardware configuration. These operating systems will all be sourcing their randomness from the same environmental noise.</p>
<p>Does this mean as a group the random number generators strength is reduced as all OS instances are basing their calculations of the same input? Or, is the environmental noise partitioned out so that sharing doesn't occur?</p>
<p>If the latter is true, I can see this reducing the effectiveness of /dev/urandom because it reuses its internal pool and with less environmental input, reduces entropy.</p>
<p>/dev/random should be ok because it blocks until enough noise is acquired... unless of course the OS instances are all sharing the input.</p>
<p>So, the question: What is the impact of virtualisation on cryptographically strong random number generators, specifically those that use environmental noise?</p>
|
<p>I couldn't find any references quickly, but it would seem to me that the entropy is derived from the kernel data structures for the devices, not the actual devices themselves. Since these would be independent regardless of virtualization, I suspect the answer is not much.</p>
<p>[EDIT] After peeking at the kernel source (actually patch history), it looks like Linux, at least, gathers entropy from keyboard presses, mouse activity, interrupt timing (but not all interrupts), and block device request finishing times. On a virtualized system, I suspect that mouse/keyboard events would be pretty low and thus not contribute to the entropy gathered. Presumably this would be offset by additional network I/O interrupt activity, but it's not clear. In this respect, I don't think it differs much from non-VM server.</p>
|
Cannot import SQLite with Python 2.6 <p>I'm running Python 2.6 on Unix and when I run the interactive prompt (<a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> is supposed to be preinstalled) I get:</p>
<pre><code>[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>
</code></pre>
<p>How do I resolve this?</p>
|
<p>The error: </p>
<pre><code>ImportError: No module named _sqlite3
</code></pre>
<p>means that <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> 3 does not find the associated shared library. On Mac OS X it's _sqlite3.so and it should be the same on other Unix systems. </p>
<p>To resolve the error you have to locate the _sqlite3.so library on your computer and then check your PYTHONPATH for this directory location. </p>
<p>To print the Python search path enter the following in the Python shell:</p>
<pre><code>import sys
print sys.path
</code></pre>
<p>If the directory containing your library is missing you can try adding it interactively with </p>
<pre><code>sys.path.append('/your/dir/here')
</code></pre>
<p>and try </p>
<pre><code>import sqlite3
</code></pre>
<p>again. If this works you have to add this directory permanently to your PYTHONPATH environment variable. </p>
<p>PS: If the library is missing you should (re-)install the module.</p>
|
How much a tester should know about internal details of code? <p>How useful, if at all, is for the testers on a product team to know about the internal code details of a product. This does not mean they need to know every line of code but a good idea of how the code is structured, what is the object model, how the various modules are inter-linked, what are the inter-dependencies between various features etc.? This can argubaly help them in finding related issues or defects once they hit one. On the other side, this can potentially 'bias' their "user-centric" approach towards evaluating and certifying the product and can effect the testing results in the end.</p>
<p>I have not heard of any specific model for such interaction. (Lets assume a product that users, potentially non-technical consume, and not a framework or API that the testers are testing - in the latter case the testers may need to understand the code to test that because the user is another programmer). </p>
|
<p>That entirely depends upon the type of testing being done.</p>
<p>For functional system testing, the testers can and probably should be oblivious to the details of the implementation -- if they know the details they may inadvertently account for that in their test strategy and not properly test the product.</p>
<p>For performance and scalability testing it's often helpful for the testers to have some high-level knowledge of the structure of the codebase, as it's beneficial in identifying potential performance hotspots, and therefore writing targetted test cases. The reason this is important is that generally performance testing is a broad open-ended process, so anything that can be done to focus the testing to get results is beneficial to everybody.</p>
|
Need to Impersonate user forAccessing Network resource, Asp.Net Account <p>I need to access a network resource on which only a given Domain Account has access.
I am using the LogonUser call, but get a "User does not have required priviliege" exception, as the web application is running with the asp.net account and it does not have adequate permissions to make this call.</p>
<p>Is there a way to get around it?
Changing the identity or permissions of the ASP.Net account is not an option as this is a production machine with many projects running.
Is there a better way to achieve this?</p>
<p>Using Asp.Net 2.0, Forms Authentication.</p>
<p>Kind Regards.</p>
|
<p>Just calling LogonUser is not enough. You need to impersonate that user. You can impersonate for just the access to the network resource.</p>
<p>Sample code can be found on <a href="http://msdn.microsoft.com/en-us/library/chf6fbt4.aspx">MSDN</a>.</p>
|
What technique would be the least effort to internationalise (at least multi-language) existing Delphi Applications? <p>I have developed about 300 Applications which I would like to provide with multi-language capabilities independent from the Operating System. I have written a just-in-time translator, but that is too slow in applications with many components. What would you suggest I do?</p>
|
<p>We are using <a href="http://www.sicomponents.com/tsilang1.html" rel="nofollow">TsiLang</a> and are very happy with it.</p>
<p>One of the best points is that you can pretranslate the project with a dictionary (which you filled from existing translations).</p>
|
Which Graphical Subsystem for Touchscreen Kiosk Development <p>I'm starting a hobby project in which I would like to have a graphical, touchscreen interface for interacting with a kiosk-like device running on top of Windows XP Embedded. For development of a rich UI experience, I was considering using WPF. However, a number of demonstration videos that I have come across have used Silverlight, while I haven't seen a single WPF demonstration.</p>
<p>It was my understanding that Silverlight was targeted towards website developers, while WPF was more targeted towards desktop development.</p>
<p>So this question has two parts. Firstly, what is the recommended graphical subsystem for development of a rich UI experience on a kiosk-like device hosted on the Windows XP embedded platform? Secondly, if it is Silverlight, which version is suggested (1.0 or 2.0) and why?</p>
|
<p>It seems that WPF works fine on embedded. See <a href="http://blogs.msdn.com/mikehall/archive/2006/07/10/661539.aspx" rel="nofollow">here</a> the second comment. </p>
<p>I think that your choice should be dependent on the type of kyosk you want to build. Some kyosks are just an open browser page. And then you have stuff like Microsoft Surface that can be used like an horizontal kyosk :-)</p>
|
Domain redirection to the same page and Google <p>We developed a website for a client and he has purchased the .com, .net, .info versions of the domain.</p>
<p>Is there any way to redirect all to the same page without being considered by Google as duplicated content and therefore penalized in the ranking position?</p>
|
<p>Just use the <a href="http://en.wikipedia.org/wiki/HTTP_301" rel="nofollow">permanent redirect</a>.</p>
|
Beta testing a new product <p>As a Micro ISV I am coming to the stage in the development of a new desktop software application where beta testing it with an external group of users would be great.</p>
<p><em>I would prefer private invite only beta testing as opposed to public free for all beta testing.</em></p>
<p><strong>Are there websites/organisations, both free or paid, where I can 'reach out' to people (with some degree of selectivity) who want to test software and provide feedback/bug reports and so on?</strong></p>
<p><strong>What have other people done when beta testing their products?</strong></p>
<p>UPDATE: I came across <a href="http://www.trybeta.com/login/index.php" rel="nofollow">TryBeta</a> which looks interesting (Although activity on the website seems to have ended around 2007).</p>
<p>With regard to turning testers into customers, I am not too concerned with doing this at the moment. Advertising towards the target audience to build up a customer base will be put in place at a later stage. Right now just testers, ideally managed by a third party website/organisation, would be ideal.</p>
<p>Many thanks in advance.</p>
|
<p>Usually, invite-only beta testing pretty much restricts you to existing or potential customers. If you have customers of this product (you don't because you say it's "new") or of other products from your company, invite them to test your product. They won't all say yes.</p>
<p>If you don't have customers, or you don't get enough beta testers, it's time for your sales critters (which sounds like it may be you) to get into action in creating some customers. Offering a beta, at no cost and no obligation, can often be an enticement to people that will actually encourage them to buy, especially if their bug reports are taken seriously. So this morphs your question into "how do I find potential customers for my app?" And that will depend on what your app is.</p>
|
Colorize logs in eclipse console <p>Is there a way to colorize parts of logs in the eclipse console. I know I could send to error and standard streams and color them differently but I'm more looking someting in the lines of ANSI escape codes (or anyother, HTML ?) where I could embed the colors in the string to have it colored in the logs.</p>
<p>It sure would help making the important bits stand out without resorting to weird layout, rather keep the layout to the log4j setups </p>
<p>here is an example of what I am looking for :</p>
<p>[INFO ] The grid is complete ....... <strong>false</strong></p>
<p>where the bold parts would be in blue, this coloring can be controlled by the application to an extent. like so (tags are conceptual and arbitrary, but you get the idea):</p>
<p>log.info(String.format("The grid is complete ....... <code><blue></code>%s<code></blue></code>", isComplete ));</p>
<p><hr /></p>
<p>On a more general note it is the ability to embed meta information in the logs to help the presentation of these logs. Much like we tag web pages content to help the presentation of the information by CSS.</p>
|
<p>have a try with this Eclipse Plugin:
<a href="http://marketplace.eclipse.org/content/grep-console">Grep Console</a></p>
<p><strong>[UPDATE]</strong>:
As pointed out by commenters:
When installing Grep Console in the currently last version of Eclipse, you need to uncheck 'Group items by category' in the Install dialog to see the available items.</p>
<p><strong>[UPDATE 2]</strong>:
As pointed out by azdev, to get proper highlighting </p>
<blockquote>
<p>entering just literal strings doesn't work. To get a line to be colored, you have to enclose the string in
<code>.*</code>
on either side, like so:
<code>.*ERROR.*</code></p>
</blockquote>
|
Tetris Piece Rotation Algorithm <p>What are the best algorithms (and explanations) for representing and rotating the pieces of a tetris game? I always find the piece rotation and representation schemes confusing.</p>
<p>Most tetris games seem to use a naive "remake the array of blocks" at each rotation:</p>
<p><a href="http://www.codeplex.com/Project/ProjectDirectory.aspx?ProjectSearchText=tetris">http://www.codeplex.com/Project/ProjectDirectory.aspx?ProjectSearchText=tetris</a></p>
<p>However, some use pre-built encoded numbers and bit shifting to represent each piece:</p>
<p><a href="http://www.codeplex.com/wintris">http://www.codeplex.com/wintris</a></p>
<p>Is there a method to do this using mathematics (not sure that would work on a cell based board)?</p>
|
<p>There is a limited amount of shapes, so I would use a fixed table and no calculation. That saves time.</p>
<p>But there are rotation algorithms. </p>
<p>Chose a centerpoint and rotate pi/2. </p>
<p>If a block of a piece starts at (1,2) it moves clockwise to (2,-1) and (-1,-2) and (-1, 2).
Apply this for each block and the piece is rotated.</p>
<p>Each x is the previous y and each y - the previous x. Which gives the following matrix:</p>
<pre><code>[ 0 1 ]
[ -1 0 ]
</code></pre>
<p>For counterclockwise rotation, use:</p>
<pre><code>[ 0 -1 ]
[ 1 0 ]
</code></pre>
|
How can I create a copy of an Oracle table without copying the data? <p>I know the statement:</p>
<pre><code>create table xyz_new as select * from xyz;
</code></pre>
<p>Which copies the structure and the data, but what if I just want the structure?</p>
|
<p>Just use a where clause that won't select any rows:</p>
<pre><code>create table xyz_new as select * from xyz where 1=0;
</code></pre>
|
Visual Studio solution that just points to a folder and shows all sub-folders and files in the solution explorer? <p>Is there a way to create a blank solution, or some type of file-based project solution within Visual Studio so that I can point to a root folder, and have all of the sub-folders and files in that root, show up in my solution explorer? I realize I can create a blank solution and then add the individual items manually by add > existing item, however, this does not keep the folder structure intact, and, well, it would take forever if I have a lot of folders/files. </p>
|
<p>You can also create the blank solution and then click the second-from-the-right icon at the top of the solution explorer (it looks like three files with one "cut out"). Once you click that button to show the files in the solution directory that are not in a project, you can select all the files (with shift-click) and then right-click on your selection and select "Include In Project."</p>
<p>Also note you can select multiple files in the "Add Existing..." file window with shift- or control-click.</p>
|
How to pass parameter to servlet <p>How do I pass a parameter from a page's useBean in JSP to a servlet in Java? I have some data in a form that gets passed no problem with a submit button, but no way to send anything else. Please help? Here is my code:</p>
<pre><code><input name = "deleteGameButton" type = "submit" value = "Delete"
onclick = "submitToServlet('DeleteGameServlet');">
</code></pre>
<p>Here is the corresponding javascript:</p>
<pre><code> function submitToServlet(newAction)
{
document.userGameForm.action = newAction;
}
</code></pre>
<p>I'd like the servlet to have access to userBean</p>
<pre><code> <jsp:useBean id = "userBean" scope = "session" class = "org.project.User" />
</code></pre>
|
<p>You kind of mess things here.</p>
<p>onclick() is Javascript and executed on client side. It has no (direct) way to update session-scoped bean. That bean is left on server-side, and was used when the HTML page was <strong>generated</strong>. To pass parameters back to servlet you need to use good old form fields, and submit the form. </p>
<p>Add more fields to the form, set their values before submit, then submit.</p>
<p>In Servlet call request.getParameter("name");</p>
<p>P.S. To automate this kind of things <strong>USE STRUTS</strong>. :-) Struts does exactly what you want: before passing the parameters to action, it populates the bean with those parameters. Transparently.</p>
|
Getting a sqlexception on successful insert, VB.NET <p>I'm trying to do a very simple INSERT using VB.NET. For some reason I'm getting a SqlException on every insert though. The data is inserted, but still get the following: </p>
<p>Violation of PRIMARY KEY constraint 'PK_User'. Cannot insert duplicate key in object 'dbo.Employee'. The statement has been terminated</p>
<p>When I check in SQL Management Studio, the data is succesfully inserted.</p>
<p>Here is the code where the problem is happening</p>
<pre><code>Try
conn.Open()
Dim insertSQL As String = "insert into Employee(uName, firstName, lastName,
On_Switch, On_Phone) " + "values('" & uName & "', '" & firstName & "', '" _
& lastName & "', '" & onSwitch & "', '" & onPhone & "')"
Dim AddCom As SqlCommand = New SqlCommand(insertSQL, conn)
If (AddCom.ExecuteNonQuery() = 1) Then
lblError.Text = "User Added."
' string urlBack = "../ViewAsset.aspx?DeptID=" + DeptID;
' Response.Redirect(urlBack);
End If
conn.Close()
Catch ex As SqlException
Dim ExMsg As String = ex.Message.ToString()
lblError.Text = ExMsg
</code></pre>
<p>I went back and tested the same code in C# and there is no Exception thrown. It seems to be something small I'm doing in VB, but I'm lost as to what it is.</p>
|
<p>As a side note, I STRONGLY recommend changing to parameterized queries to prevent the risk of SQL injection that your current code is not protected from.</p>
<p>For the error issue, I would check to see that your code isn't being called twice in the VB version.</p>
|
Flash Logging API <p>Can anyone recommend a good (AS3) logging API for Flash/AIR/Flex? I need something to capture and record mouse and keyboard events in addition to coded events. Preferably something well documented/supported. Thanks in advance.</p>
|
<p>I've been using <a href="http://code.google.com/p/flash-thunderbolt/" rel="nofollow">Thunderbolt</a>. It allows you to see your log results in Firebug.</p>
|
Can anyone explain servlet mapping?
<p>I'm trying to write a web application using SpringMVC. Normally I'd just map some made-up file extension to Spring's front controller and live happily, but this time I'm going for REST-like URLs, with no file-name extensions.</p>
<p>Mapping everything under my context path to the front controller (let's call it "<strong>app</strong>") means I should take care of static files also, something I'd rather not do (why reinvent yet another weel?), so some combination with tomcat's default servlet (let's call it "<strong>tomcat</strong>") appears to be the way to go.</p>
<p>I got the thing to work doing something like </p>
<pre class="lang-xml prettyprint-override"><code><servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>tomcat</servlet-name>
<url-pattern>*.ext</url-pattern>
</servlet-mapping>
</code></pre>
<p>and repeating the latter for each one of the file extensions of my static content. I'm just wondering why the following setups, which to me are equivalent to the one above, don't work.</p>
<pre class="lang-xml prettyprint-override"><code><!-- failed attempt #1 -->
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>tomcat</servlet-name>
<url-pattern>*.ext</url-pattern>
</servlet-mapping>
<!-- failed attempt #2 -->
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>tomcat</servlet-name>
<url-pattern>/some-static-content-folder/*</url-pattern>
</servlet-mapping>
</code></pre>
<p>Can anyone shed some light?</p>
|
<p>I think I may know what is going on.</p>
<p>In your working web.xml you have set your servlet to be the default servlet (/ by itself is the default servlet called if there are no other matches), it will answer any request that doesn't match another mapping.</p>
<p>In Failed 1 your /* mapping does appear to be a valid path mapping. With the /* mapping in web.xml it answers all requests except other path mappings. According to the specification extension mappings are implicit mappings that are overwritten by explicit mappings. That's why the extension mapping failed. Everything was explicitly mapped to app.</p>
<p>In Failed 2, App is responsible for everything, except content that matches the static content mapping. To show what is happening in the quick test I set up. Here is an example. <code>/some-static-content-folder/</code> contains <code>test.png</code></p>
<p>Trying to access test.png I tried:</p>
<pre><code>/some-static-content-folder/test.png
</code></pre>
<p>and the file was not found. However trying</p>
<pre><code>/some-static-content-folder/some-static-content-folder/test.png
</code></pre>
<p>it comes up. So it seems that the Tomcat default servlet (6.0.16 at least) drops the servlet mapping and will try to find the file by using the remaining path. According to this post <a href="http://stackoverflow.com/questions/132052">Servlet for serving static content</a> Jetty gives the behavior you and I were expecting.</p>
<p>Is there some reason you can't do something like map a root directory for your rest calls. Something like app mapped to /rest_root/* than you are responsible for anything that goes on in the rest_root folder, but anywhere else should be handled by Tomcat, unless you make another explicit mapping. I suggest setting your rest servlet to a path mapping, because it declares the intent better. Using / or /* don't seem appropriate, since you have to map out the exceptions. Using SO as an example, my rest mappings would be something like</p>
<blockquote>
<p>/users/* for the user servlet</p>
<p>/posts/* for the posts servlet</p>
</blockquote>
<p>Mapping order</p>
<ol>
<li>Explicit (Path mappings)</li>
<li>Implicit (Extension mappings)</li>
<li>Default (/)</li>
</ol>
<p>Please correct anything that I got wrong.</p>
|
How does Telnet server communicate to the client? <p>I want to write a C# application where it connects to a telnet server and communicates to the server. I was wondering how a telnet server sends information to the client. I have looked (skimmed) over the <a href="http://www.faqs.org/rfcs/rfc854.html" rel="nofollow">Telnet RFC</a> and looked at the incoming packets coming in from the server and still a bit confused. Can somebody give me an example how the server moves the cursor around in the telnet client and how it can change colors of characters? (An example would be most appreciated)</p>
<p><strong>Update I</strong></p>
<p>Here's some additional VT100 resources:</p>
<ol>
<li><a href="http://graphcomp.com/info/specs/ansi%5Fcol.html" rel="nofollow">ANSI/VT100 Terminal Control</a></li>
<li><a href="http://www.cs.utk.edu/~shuford/terminal/vt100%5Fcodes%5Fnews.txt" rel="nofollow">vt100_codes_news.txt</a></li>
</ol>
<p><strong>Update II</strong></p>
<p>With much research and time, here what I found out: <a href="http://srand2.blogspot.com/2009/02/telnet-programming-with-c.html" rel="nofollow">Telnet Programming with C#</a></p>
|
<p>Moving the cursor and changing the color isn't done by the telnet protocol.</p>
<p>Your telnet client is emulating a <a href="http://en.wikipedia.org/wiki/Computer_terminal" rel="nofollow">terminal</a>, most probably a VT-100 variant. To move the cursor and change the color, the server sends escape sequences especific to the type of terminal being emulated (which one is sent in the telnet protocol negotiation).</p>
<p>If you don't want these escape sequences, telling the server on the telnet protocol negotiation you are a "dumb" terminal should be enough. If you want them (or if the server assumes everyone has a VT-100 and always sends them) you will have to implement a VT-100 terminal emulator (or at least enough of it to discard what you don't want).</p>
|
BindingFlags for Type.GetMethods excluding property accesors <p>Suppose I've got the following program:</p>
<pre><code>namespace ReflectionTest
{
public class Example
{
private string field;
public void MethodOne() { }
public void MethodTwo() { }
public string Property
{
get { return field; }
set { this.field = value; }
}
}
class Program
{
static void Main(string[] args)
{
iterate(typeof(Example));
Console.ReadLine();
}
public static void iterate(Type type)
{
MethodInfo[] methods = type.GetMethods(
BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public);
foreach (MethodInfo mi in methods)
{
Console.WriteLine(mi.Name);
}
}
}
}
</code></pre>
<p>When I run the program I'm getting the following output:</p>
<pre>MethodOne
MethodTwo
get_Property
set_Property</pre>
<p>I want to skip the property accesor methods. I've tried with different <a href="http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx"><code>BindingFlags</code></a>, for instance, <code>~BindingFlags.SetProperty</code>, but with no luck. At the moment the only way I've found to skip those methods is rewriting the iterate function to:</p>
<pre><code>public static void iterate(Type type)
{
MethodInfo[] methods = type.GetMethods(
BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public);
foreach (MethodInfo mi in methods)
{
if (mi.IsSpecialName) continue;
Console.WriteLine(mi.Name);
}
}
</code></pre>
<p>Do you know what <code>BindingFlags</code> should I use?</p>
<p>Thank you very much.</p>
<h3>Update:</h3>
<p>Well, I should have explained that the project is actually for building automatically templates for unit testing, so I can skip all the special methods. Thanks for the additional information on IsSpecialName :)</p>
<p>LINQ? Really? Wow. Anyway, this project is .NET 2.0 so LINQ is (sadly) not an option.</p>
|
<p>From the top of my head:</p>
<pre><code>mi.IsSpecialName &&( mi.Name.StartsWith("set_") || mi.Name.StartsWith("get_"))
</code></pre>
<p>should get you all set.
SpecialName is more than property accessors (event add/remove methods count here as well), that's why you have to check the names as well.</p>
<p>You can use LINQ for that as well :)</p>
|
Skip Lists -- ever used them? <p>I'm wondering whether anyone here has ever used a <a href="http://en.wikipedia.org/wiki/Skip_list">skip list</a>. It looks to have roughly the same advantages as a balanced binary tree, but is simpler to implement. If you have, did you write your own, or use a pre-written library (and if so, what was its name)?</p>
|
<p>My understanding is that they're not so much a useful alternative to <em>binary trees</em> (e.g. red-black trees) as they are to <em>B-trees</em> for database use, so that you can keep the # of levels down to a feasible minimum and deal w/ base-K logs rather than base-2 logs for performance characteristics. The algorithms for probabilistic skip-lists are (IMHO) easier to get right than the corresponding B-tree algorithms. Plus there's some literature on lock-free skip lists. I looked at using them a few months ago but then abandoned the effort on discovering the <a href="http://en.wikipedia.org/wiki/Hierarchical_Data_Format">HDF5</a> library. </p>
<p>literature on the subject:</p>
<p>Papers by Bill Pugh:</p>
<ul>
<li><a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.524">A skip list cookbook</a></li>
<li><a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.9380">Skip lists: A probabilistic alternative to balanced trees</a></li>
<li><a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.8201"> Concurrent Maintenance of Skip Lists </a></li>
</ul>
<p>non-academic papers/tutorials:</p>
<ul>
<li><a href="http://www.eternallyconfuzzled.com/tuts/datastructures/jsw_tut_skip.aspx">Eternally Confuzzled</a> (has some discussion on several data structures)</li>
<li><a href="http://www.csee.umbc.edu/courses/undergraduate/341/fall01/Lectures/SkipLists/skip_lists/skip_lists.html">"Skip Lists"</a> by Thomas A. Anastasio</li>
</ul>
|
One DB per developer or not? <p>In a corporate development environment writing mostly administrative software, should every developer use their own database instance, or should they use a central database instance during development? What are the advantages and disadvantages of each approach? What about other environments and other products?</p>
|
<p>If you all share the same database, you might have some issues if someone make a structure change to the database and that the code is not "Synchronized" with it.</p>
<p>I highly recommend one DB per developer for the only reason that you don't want to do "write" test to see someone else override you right after. A simple exemple? You try to display product for a website. Everything works until all the products disappear. Problem? Another developer decided to play with the "Active" flag of the product to test something else. In cases like that, a transaction might not even work. End of the story, you spend time debugging for someone else action.</p>
<p>I highly recommend replicating the staging database to the developer database once in a while to synchronize the structure (or better, have a tool to rebuild a database from scratch). </p>
<p>Of course, we require scripts for changes to the database and EVERYTHING is in a Source Control.</p>
|
Solving the shared-server security problem for Python <p>So my group is trying to set up a shared-server environment for various and sundry web services. I think we've settled on setting <code>disable_functions</code> and <code>disable_classes</code> site wide in <code>php.ini</code> and <code>php_admin_value</code> to force <code>open_basedir</code> in each app's <code>httpd.conf</code>
for php scripts, and passenger's <a href="http://www.modrails.com/documentation/Users%20guide.html#user_switching" rel="nofollow">user switching</a> for ruby scripts. </p>
<p>We still need to find something for python though. Passenger does support python, but not for per-application security for specific sub-directories (it's all or nothing at the domain level). </p>
<p>Any suggestions?</p>
<p>(And if any of the previous doesn't make sense - well, I'm the guy who's supposed to set up the python support, not the guy who set up the php or ruby support, so there's still some "and then some magic happens" steps in there from my perspective).</p>
|
<p>Well, there is a system called <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> which allows you to run Python in a sort of safe environment, and configure/load/shutdown these environments on the fly. I don't know much about it, but you should take a serious look into it; here is the description from its web page (just Google it and you'll find it):</p>
<blockquote>
<p>The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.4/site-packages (or whatever your platform's standard location is), it's easy to end up in a situation where you unintentionally upgrade an application that shouldn't be upgraded.</p>
<p>Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.</p>
<p>Also, what if you can't install packages into the global site-packages directory? For instance, on a shared host.</p>
<p>In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn't share libraries with other virtualenv environments (and optionally doesn't use the globally installed libraries either).</p>
</blockquote>
|
Can I use Class.newInstance() with constructor arguments? <p>I would like to use <code>Class.newInstance()</code> but the class I am instantiating does not have a nullary constructor. Therefore I need to be able to pass in constructor arguments. Is there a way to do this?</p>
|
<pre><code>Class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");
</code></pre>
|
Which method name fits in best with Objective-C/Cocoa conventions? <p>Here's a quicky question. Which method name makes the most sense for an Objective-C Cocoa application?</p>
<pre><code>-(void) doSomethingWithAnimation:(BOOL)animated
</code></pre>
<p>or:</p>
<pre><code>-(void) doSomething:(BOOL)animated
</code></pre>
<p>or even:</p>
<pre><code>-(void) doSomethingAnimated:(BOOL)animated
</code></pre>
|
<p>I think the Cocoa convention would give your examples the following semmantics (ignoring the BOOL type for the argument, obviously):</p>
<pre><code>-(void) doSomethingWithAnimation:(BOOL)animated
</code></pre>
<p>would actually expect an Animation as the parameter (i.e. something that represents the animation.</p>
<pre><code>-(void) doSomething:(BOOL)animated
</code></pre>
<p>would expect the Something to do.</p>
<pre><code>-(void) doSomethingAnimated:(BOOL)animated
</code></pre>
<p>would, as Noah answered, do something with optional animation.</p>
|
Weird case sensitivity bug in Class.getResource? <p>I was loading an image resource with the following code and it works fine from my dev environment (netbeans) but threw an exception as soon as it ran from the desktop.</p>
<pre><code>new ImageIcon(Images.class.getResource("images/highlighter24.gif"));
</code></pre>
<p>I traced it down to my file having different case than in the code.</p>
<p>Fine, my bad, but why the inconsistent behavior?</p>
<p>Gremlins?</p>
<p>Note: I'm running on windows before you ask.</p>
|
<p>Let me guess: in NetBeans it was loading it from the file system (which is case-insensitive) whereas when running it from the desktop it was in a jar file (which is case-sensitive).</p>
<p>I've seen this kind of thing before, where a web app worked fine on Windows but failed on Unix because we'd got the case wrong in the URL.</p>
<p>If you think of jar files as "just another file system" then it makes sense, even if it's slightly annoying to have the inconsistency.</p>
|
Sending emails with the error log through CruiseControl <p>How do you configure cruiseControl to send out emails that contains the error log whenever a build fails? I've gotten it to send out emails to users when the build fails, but it does not include the actual error that caused the build to fail. I know that if I only configure it to send out emails to the users that have made modifications, the error log is included in those emails. This is a sample of what I have:</p>
<p>< publishers><br/>
< rss/><br/>
< xmllogger/> <br/>
< email from="abc@abc.com" mailhost="abc.abc.com" includeDetails="TRUE"><br/>
< users><br/>
< user name="Joe" group="devs" address="joe@abc.com"/><br/>
< user name="Jim" group="devs" address="jim@abc.com"/><br/>
< /users><br/>
< groups><br/>
< group name="devs" notification="Failed"/><br/>
< /groups><br/>
< /email><br/>
< /publishers></p>
|
<p>You can check if \cruisecontrol.net\server\xsl\compile.xsl is the same as \cruisecontrol.net\webdashboard\xsl\compile.xsl.</p>
<p>Compile.xsl is the default file used to print the error messages from your error log. The one in \webdashboard\ is used for the web dashboard (as the name implies) and the one under \server\ is used for emails.</p>
<p>You can also check ccnet.exe.config whether or not \cruisecontrol.net\server\xsl\compile.xsl is used for emails.</p>
<p>Mine's for example points to compile.xsl on \server\:</p>
<pre><code><!-- Specifies the stylesheets that are used to transform the build results when using the EmailPublisher -->
<xslFiles>
<file name="xsl\header.xsl" />
<file name="xsl\compile.xsl" />
<file name="xsl\unittests.xsl" />
<file name="xsl\fit.xsl" />
<file name="xsl\modifications.xsl" />
<file name="xsl\fxcop-summary.xsl" />
</xslFiles>
</code></pre>
|
What's the UITableView index magnifying glass character? <p>In Apple's iPhone apps (like Contacts), they have a nice magnifying glass icon at the top of the table view index. Since the table view index API is character-based, I assume that this magnifying glass is a Unicode character. So far I've resorted to placing a question mark character there, but that looks lame.</p>
<p>Can anyone tell me what character the magnifying glass is?</p>
|
<p>Returning <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006943-CH3-SW49"><code>UITableViewIndexSearch</code></a> as section index title (same as @"{search}") also works.</p>
|
General Business Object Practices (and exception errors - redux) <p>Recently, <a href="http://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception">I made a post about the developers I'm working with not using try catch blocks properly</a>, and unfortuantely using try... catch blocks in critical situations and ignoring the exception error all together. causing me major heart ache. Here is an example of one of the several thousand sections of code that they did this (some code left out that doesn't particuarly matter:</p>
<pre><code>public void AddLocations(BOLocation objBllLocations)
{
try
{
dbManager.Open();
if (objBllLocations.StateID != 0)
{
// about 20 Paramters added to dbManager here
}
else
{
// about 19 Paramters added here
}
dbManager.ExecuteNonQuery(CommandType.StoredProcedure, "ULOCATIONS.AddLocations");
}
catch (Exception ex)
{
}
finally
{
dbManager.Dispose();
}
}
</code></pre>
<p>This is absolutely discusting, in my eyes, and does not notify the user in case some potential problem occurred. I know many people say that OOP is evil, and that adding multiple layers adds to the number of lines of code and to the complexity of the program, leading to possible issues with code maintainence. Much of my programming background, I personally, have taken almost the same approach in this area. Below I have listed out a basic structure of the way I normally code in such a situation, and I've been doing this accross many languages in my career, but this particular code is in C#. But the code below is a good basic idea of how I use the Objects, it seems to work for me, but since this is a good source of some fairly inteligent programming mines, I'd like to know If I should re-evaluate this technique that I've used for so many years. Mainly, because, in the next few weeks, i'm going to be plunging into the not so good code from the outsourced developers and modifying huge sections of code. i'd like to do it as well as possible. sorry for the long code reference. </p>
<pre><code>// *******************************************************************************************
/// <summary>
/// Summary description for BaseBusinessObject
/// </summary>
/// <remarks>
/// Base Class allowing me to do basic function on a Busines Object
/// </remarks>
public class BaseBusinessObject : Object, System.Runtime.Serialization.ISerializable
{
public enum DBCode
{ DBUnknownError,
DBNotSaved,
DBOK
}
// private fields, public properties
public int m_id = -1;
public int ID { get { return m_id; } set { m_id = value; } }
private int m_errorCode = 0;
public int ErrorCode { get { return m_errorCode; } set { m_errorCode = value; } }
private string m_errorMsg = "";
public string ErrorMessage { get { return m_errorMsg; } set { m_errorMsg = value; } }
private Exception m_LastException = null;
public Exception LastException { get { return m_LastException; } set { m_LastException = value;} }
//Constructors
public BaseBusinessObject()
{
Initialize();
}
public BaseBusinessObject(int iID)
{
Initialize();
FillByID(iID);
}
// methods
protected void Initialize()
{
Clear();
Object_OnInit();
// Other Initializable code here
}
public void ClearErrors()
{
m_errorCode = 0; m_errorMsg = ""; m_LastException = null;
}
void System.Runtime.Serialization.ISerializable.GetObjectData(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
{
//Serialization code for Object must be implemented here
}
// overrideable methods
protected virtual void Object_OnInit()
{
// User can override to add additional initialization stuff.
}
public virtual BaseBusinessObject FillByID(int iID)
{
throw new NotImplementedException("method FillByID Must be implemented");
}
public virtual void Clear()
{
throw new NotImplementedException("method Clear Must be implemented");
}
public virtual DBCode Save()
{
throw new NotImplementedException("method Save Must be implemented");
}
}
// *******************************************************************************************
/// <summary>
/// Example Class that might be based off of a Base Business Object
/// </summary>
/// <remarks>
/// Class for holding all the information about a Customer
/// </remarks>
public class BLLCustomer : BaseBusinessObject
{
// ***************************************
// put field members here other than the ID
private string m_name = "";
public string Name { get { return m_name; } set { m_name = value; } }
public override void Clear()
{
m_id = -1;
m_name = "";
}
public override BaseBusinessObject FillByID(int iID)
{
Clear();
try
{
// usually accessing a DataLayerObject,
//to select a database record
}
catch (Exception Ex)
{
Clear();
LastException = Ex;
// I can have many different exception, this is usually an enum
ErrorCode = 3;
ErrorMessage = "Customer couldn't be loaded";
}
return this;
}
public override DBCode Save()
{
DBCode ret = DBCode.DBUnknownError;
try
{
// usually accessing a DataLayerObject,
//to save a database record
ret = DBCode.DBOK;
}
catch (Exception Ex)
{
LastException = Ex;
// I can have many different exception, this is usually an enum
// i do not usually use just a General Exeption
ErrorCode = 3;
ErrorMessage = "some really weird error happened, customer not saved";
ret = DBCode.DBNotSaved;
}
return ret;
}
}
// *******************************************************************************************
// Example of how it's used on an asp page..
protected void Page_Load(object sender, EventArgs e)
{
// Simplifying this a bit, normally, I'd use something like,
// using some sort of static "factory" method
// BaseObject.NewBusinessObject(typeof(BLLCustomer)).FillByID(34);
BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34);
if (cust.ErrorCode != 0)
{
// There was an error.. Error message is in
//cust.ErrorMessage
// some sort of internal error code is in
//cust.ErrorCode
// Give the users some sort of message through and asp:Label..
// probably based off of cust.ErrorMessage
//log can be handled in the data, business layer... or whatever
lab.ErrorText = cust.ErrorMessage;
}
else
{
// continue using the object, to fill in text boxes,
// literals or whatever.
this.labID = cust.ID.toString();
this.labCompName = cust.Name;
}
}
</code></pre>
<p>Bottom line, my question is, Am I over complicating things with the muliple layers, and the inherited classes or is my old concept illustrated still working good and stable? Is there a better way now a days to accomplish these things? Should I go to just making straight SQL calls from the asp.net page code behind pages as fellow work associate developer suggested (though that last solution makes me feel icky), instead of going through a business object, and data layer (data layer not shown, but basically holds all the stored proc calls). Yeah, another developer did ask me why i go through the effort of layering things, when you can just type what you need straight in a *.aspx.cs code behind page, and then I can have the joys of over 1k lines of code behind. What is some advice here?</p>
|
<p>Have you considered using an ORM like NHibernate? There's no point in re-inventing the wheel.</p>
<p>To me this is a code smell:</p>
<pre><code>BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34);
</code></pre>
<p>Too many brackets!</p>
<p>I've found that using the active record pattern in a language like C# always ends in tears because it's hard(er) to unit test.</p>
|
What are the benefits of maintaining a "clean" list of using directives in C#? <p>I know VS2008 has the remove and sort function for cleaning up using directives, as does Resharper. Apart from your code being "clean" and removing the problem of referencing namespaces which might not exist in the future, what are the benefits of maintaining a "clean" list of using directives?</p>
<p>Less code?
Faster compilation times?</p>
|
<p>If you always only have the using directives that you need, and always have them appropriately sorted, then when you come to diff two versions of the code, you'll never see irrelevant changes.</p>
<p>Furthermore, if you have a neat set of using directives then anyone looking at the code to start with can get a <em>rough</em> idea of what's going to be used just by look at the using directives.</p>
|
Are there better clients for viewing System Monitor logs? <p>Does anyone know of a better GUI client for displaying Windows <a href="http://support.microsoft.com/kb/248345" rel="nofollow">System Monitor</a> log files? (System Monitor is sometimes called <a href="http://support.microsoft.com/?kbid=330138" rel="nofollow">Performance Monitor</a>.) I'm trying to track a long-term memory leak in a C# application running on Windows XP or 2K3 by comparing memory usages to run logs.</p>
<p>Specifically I want a client that will allow me to see the following (because System Monitor is unable or difficult):</p>
<ul>
<li>Specify exact date time ranges for viewing data (or at least finer granularity than hours)</li>
<li>Show time intervals along the horizontal axis</li>
<li>Show max, min, average for the time range</li>
<li>Somewhere show the interval on which source data was captured (1 sec, 5 min, etc.)</li>
</ul>
<p>(If no such thing exists I'm willing to hear recommendations for better long term performance/memory capturing tools.)</p>
<p><strong>Edit:</strong> I've done Google searches and haven't found anything except tutorials on how to create System Monitor logs.</p>
|
<p>See <a href="http://stackoverflow.com/questions/37425/what-is-the-best-way-to-interpret-perfmon-analysis-into-application-specific-ob#158314">this</a> question.</p>
<p>The PAL tool does a nice job of creating an HTML report with charts and graphs. By creating your own Threshold file you can control what goes into the report. </p>
|
What is the scope of a function in Javascript/ECMAScript? <p>Today I had a discussion with a colleague about nested functions in Javascript:</p>
<pre><code>function a() {
function b() {
alert('boo')
}
var c = 'Bound to local call object.'
d = 'Bound to global object.'
}
</code></pre>
<p>In this example, trials point out that b is not reachable outside the body of a, much like c is. However, d is - after executing a(). Looking for the exact definition of this behaviour in the <a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf">ECMAScript v.3 standard </a>, I didn't find the exact wording I was looking for; what Sec.13 p.71 does not say, is which object the function object created by the function declaration statement is to be bound to. Am I missing something?</p>
|
<p>This is static scoping. Statements within a function are scoped within that function. </p>
<p>Javascript has a quirky behavior, however, which is that without the <strong>var</strong> keyword, you've implied a <strong>global variable</strong>. That's what you're seeing in your test. Your "d" variable is available because it is an implied global, despite being written within the body of a function.</p>
<p>Also, to answer the second part of your question: A function exists in whatever scope it is declared, just like a variable.</p>
<p><strong>Sidenote:</strong>
You probably don't want global variables, especially not implied ones. It's recommended that you always use the var keyword, to prevent confusion and to keep everything clean.</p>
<p><strong>Sidenote:</strong>
The ECMA Standard isn't probably the most helpful place to find answers about Javascript, although it certainly isn't a bad resource. Remember that javascript in your browser is just an implementation of that standard, so the standards document will be giving you the rules that were (mostly) followed by the implementors when the javascript engine was being built. It can't offer specific information about the implementations you care about, namely the major browsers. There are a couple of books in particular which will give you very direct information about how the javascript implementations in the major browsers behave. To illustrate the difference, I'll include excerpts below from both the ECMAScript specification, and a book on Javascript. I think you'll agree that the book gives a more direct answer.</p>
<p>Here's from the <strong>ECMAScript Language Specification</strong>:</p>
<blockquote>
<p>10.2 <em>Entering An Execution Context</em></p>
<p>Every function and constructor call
enters a new execution context, even
if a function is calling itself
recursively. Every return exits an
execution context. A thrown exception,
if not caught, may also exit one or
more execution contexts. </p>
<p>When control
enters an execution context, the scope
chain is created and initialised,
variable instantiation is performed,
and the this value is determined. </p>
<p>The
initialisation of the scope chain,
variable instantiation, and the
determination of the this value depend
on the type of code being entered.</p>
</blockquote>
<p>Here's from <strong>O'Reilly's <a href="http://oreilly.com/catalog/9780596101992/index.html">Javascript: The Definitive Guide (5th Edition)</a></strong>:</p>
<blockquote>
<p>8.8.1 Lexical Scoping</p>
<p>Functions in JavaScript are lexically
rather than dynamically scoped. This
means that they run in the scope in
which they are defined, not the scope
from which they are executed. When a
function is defined, the current scope
chain is saved and becomes part of
the internal state of the function.
...</p>
</blockquote>
<p>Highly recommended for covering these kinds of questions is Douglas Crockford's book: </p>
<p><img src="http://oreilly.com/catalog/covers/9780596517748_cat.gif" alt="JavaScript, The Good Parts" /></p>
<p><a href="http://oreilly.com/catalog/9780596517748/index.html"><strong>Javascript, The Good Parts</strong></a>, also from O'Reilly.</p>
|
C# How do I sort the columns in a datagrid into alphabetical order? <p>How do I sort the columns in a winforms datagrid control into alphabetical order?</p>
<p>Thanks</p>
|
<p>Have you tried binding the DataGrid to a DataTable object (instead of a view) and turning setting the "AllowSorting" property to true on the DataGrid? I believe the grid will then automatically sort the table source for you.</p>
<p>If not, you can always catch the event when a column header is clicked and rebuild a DataView to bind to the DataGrid.</p>
|
How to effectively implement sessions in GAE? <p>I was wondering about implementing my own sessions (more for an exercise than anything else) for a GAE app I'm working ... at first I was thinking of using the datastore to store the session data. However, every time something needs to be added to the session 'bucket', it would require saving to the datastore. Obviously that's bad since we want to minimize our writes. Then I thought about using memcache ... seemed like a good idea but then we're faced with issues of possible session corruption due to memcache being "evicted through memory pressure" by Google. So does that mean we are left with only the following options:</p>
<ol>
<li>Storing all session data in cookies</li>
<li>Writing all session data to datastore and memcache, and then only reading from memcache</li>
</ol>
<p>Anyone have any other ideas?</p>
|
<p><strong>UPDATE - 21 Mar 2011</strong> </p>
<p>At the time of this answer <strong>app-engine-patch is discontinued</strong> and <strong>gaeutilities</strong> <a href="https://github.com/dound/gae-sessions/wiki/comparison-with-alternative-libraries">offer worst features</a> than <strong>gae-sessions</strong>.</p>
<ul>
<li>GitHub <a href="https://github.com/dound/gae-sessions">gae-sessions</a> </li>
<li>HowTo <a href="http://blog.stannard.net.au/2011/01/09/how-to-use-sessions-on-google-app-engine-with-python-and-gae-sessions/">10-steps tutorials</a></li>
</ul>
|
Good FAQ For Recompiling apps with GCC for AmigaOS? <p>There are a couple of open source apps I am trying to recompile to work under amigaOS. Can someone point me to a good step-by-step guide explaining what changes (from a rule-of-thumb standpoint) I need to make to the source before it'll compile?</p>
|
<p>Here's a good place to <a href="http://www.monkeyhouse.eclipse.co.uk/amiga/dev.htm" rel="nofollow">start</a>. <a href="http://amiga.sourceforge.net/amigadevhelp/" rel="nofollow">This</a> also looks like an excellent resource.</p>
<p>What kind of software are you looking to port, exactly?</p>
|
How do you detect low memory situations within the java virtual machine? <p>I've been getting some OutOfMemory errors lately in my application. Is it possible to detect ahead of time when the virtual machine is running low on memory? In other words to preemptively deal with OutOfMemory errors before they actually occur?</p>
|
<p>Java (as of Java 5) now has a standard JMX bean that can be used to receive low memory notification. See <code>java.lang.management.MemoryMXBean</code>.</p>
|
Can the overall implementation of a component be divided in two objects? <p>I've seen with Microsoft COM and XPCOM, at least from what I've read and gathered so far, that the implementations of interfaces in a component have to essentially be in the single class that derives all the virtual interfaces. Is this correct? What am I missing?</p>
<p>Is there a way to have multiple objects (possibly in separate DLL's) each provide their functionality and still be able to freely transition between them using QueryIterface?</p>
<p>What I'm looking for is to have a component with some functionality, but still allow external client code to create new extensions of the component with (possibly) new interfaces. Ideally this should happen without divulging the current source of the component and its implementation.</p>
|
<p>This should be possible, although probably not supported by the standard high-level wrappers. Most of the wrappers (ATL, MFC, etc.) only support mapping a COM object to a single class. However, QueryInterface is allowed to return a different pointer and calls COM object code, so the first COM object could load a different DLL, instantiate a different object, and return a pointer to it's interface (vtable).</p>
<p>It's all possible as far as I know, you'll just likely be writing a lot of the low-level glue code yourself.</p>
|
Is there a concise catalog of variable naming-conventions? <p>There are many different styles of variable names that I've come across over the years.</p>
<p>The current wikipedia entry on naming conventions is fairly light... </p>
<p>I'd love to see a concise catalog of variable naming-conventions, identifying it by a name/description, and some examples. </p>
<p>If a convention is particularly favored by a certain platform community, that would be worth noting, too.</p>
<p>I'm turning this into a community wiki, so please create an answer for each convention, and edit as needed.</p>
|
<p>The best naming convention set that I've seen is in the book "<a href="http://rads.stackoverflow.com/amzn/click/0735619670" rel="nofollow">Code Complete</a>" Steve McConnell has a great section in there about naming conventions and lots of examples. His examples run through a number of "best practices" for different languages, but ultimately leave it up to the developer, dev manager, or architect to decide the specific action.</p>
|
Is it possible to change SQL user-defined data type? <p>I have a bunch of tables using user-defined data type for PK column. Is it possible to change this type Using SQL Server 2005?</p>
|
<p>I would suggest that it is always possible to refactor poor or outmoded database designs, it simply depends on how much work you are willing to go to in order to do so.</p>
<p>If you are looking to replace the user-defined data with a surrogate key then you should be able to simply alter the existing table to contain a non-nullable identity column and this should cause all of the existing records to be assigned a new key automatically.</p>
<p>Once the new field is populated with unique id's, if you need to move out and replace foreign key references to this table, then I would simply alter those tables to contain the new field and use something like the following:</p>
<pre><code>UPDATE child_table
SET new_fk_val =
SELECT new_pk_val
FROM parent_table
WHERE parent_table.old_pk_val = child_table.old_fk_val
</code></pre>
<p>Once that step is complete, then you could drop the old foreign key constraint, drop the old foreign key column, drop the old primary key column, establish the new primary key constraint, and then establish the new foreign key constraint.</p>
<p>Of course, if the old version of the parent and child tables relationship was such that you have invalid records in the child table you may have to do something like the following:</p>
<pre><code>DELETE FROM child_table
WHERE old_fk_val NOT IN
( SELECT old_pk_val FROM parent_table)
</code></pre>
|
System.Windows.Forms.WebBrowser.Refresh showing previous page <p>My WinForms application has a tab with a <code>System.Windows.Forms.WebBrowser</code> control. There are several controls that set the WebBrowser's <code>.Url</code> property, and when the form repaints it calls the WebBrowser's <code>.Refresh(WebBrowserRefreshOption.Completely)</code> method.</p>
<p>Occasionally, however, the form gets repainted and the WebBrowser content doesn't change. I break on the <code>.Refresh( )</code>, and the <code>.Url</code> is the previous Url. What's going on?</p>
<p>According to <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.url.aspx" rel="nofollow">MSDN</a>:</p>
<blockquote>If you set the value of this property and then immediately retrieve it again, the value retrieved may be different than the value set if the WebBrowser control has not had time to load the new document.</blockquote>
<p>Well isn't that special? Why doesn't <code>.Refresh( )</code> wait until the control has "had time to load the new document" before it redraws? Is there any way to force this to happen?</p>
|
<p>Unless you're doing something very special, it doesn't make sense to force the WB to repaint itself. Since it is its own control and has its own Handle, it is quite capable of repainting itself whenever it deems necessary. Since you are forcing it to repaint at a moment that's completely out of sync with its ReadyState, getting an "old" url is to be expected.</p>
|
F# int64 to int <p>How can I convert an <code>Int64</code> to an <code>Int32</code> type in F# without using the <code>Microsoft.FSharp.Compatibility.Int32.of_int64</code>?</p>
<p>I'm doing this because interactive doesn't seem to work when I try:</p>
<pre><code>open Microsoft.FSharp.Compatibility
</code></pre>
<p>With <code>FSharp.PowerPack</code> added as a reference it says: </p>
<blockquote>
<p>error FS0039: The namespace 'Compatibility' is not defined.</p>
</blockquote>
<p><strong>Edit:</strong> Does anyone have an answer to the question? The suggestions about the int types are useful and informative, but I'm having the same issue opening the powerpack namespace in F# interactive.</p>
|
<p>F# 1.9.6 has a type conversion function so you can do this: </p>
<pre><code>let num = 1000
let num64 = int64(num)
</code></pre>
|
How do I make a function happen 50% of the time in vb6 <p>Making a small app, and I want a function to execute 50% of the time. So if I were to dbl click the exe half the time the function would execute, and the other half it wouldn't. I can't seem to find anyway to easily do this, the one solution I tried seemed to determine the chance on compile rather than on run. Thanks in advance!</p>
|
<p>Generate a random decimal number between 0 and 1. If it is greater than 0.5 run, if it is less than or equal to 0.5 do not run. </p>
|
How to lookup django session for a particular user? <p>I am writing an application where I will be accessing the database from django and from a stand alone application. Both need to do session verification and the session should be the same for both of them. Django has a built in authentication/session verification, which is what I am using, now I need to figure out how to reuse the same session for my stand alone application.</p>
<p>My question is how can I look up a session_key for a particular user?</p>
<p>From what it looks there is nothing that ties together auth_user and django_session</p>
|
<p>This answer is being posted five years after the original question, but this SO thread is one of the top Google results when searching for a solution to this problem (and it's still something that isn't supported out of the box with Django).</p>
<p>I've got an alternate solution for the use case where you're only concerned with logged in user sessions, which uses an additional <code>UserSession</code> model to map users to their sessions, something like this:</p>
<pre><code>from django.conf import settings
from django.db import models
from django.contrib.sessions.models import Session
class UserSession(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
session = models.ForeignKey(Session)
</code></pre>
<p>Then you can simply save a new <code>UserSession</code> instance any time a user logs in:</p>
<pre><code>from django.contrib.auth.signals import user_logged_in
def user_logged_in_handler(sender, request, user, **kwargs):
UserSession.objects.get_or_create(user = user, session_id = request.session.session_key)
user_logged_in.connect(user_logged_in_handler)
</code></pre>
<p>And finally when you'd like to list (and potentially clear) the sessions for a particular user:</p>
<pre><code>from .models import UserSession
def delete_user_sessions(user):
user_sessions = UserSession.objects.filter(user = user)
for user_session in user_session:
user_session.session.delete()
</code></pre>
<p>That's the nuts and bolts of it, if you'd like more detail I have a <a href="http://gavinballard.com/associating-django-users-sessions/">blog post</a> covering it.</p>
|
VistaDB Connection Issue Programmatically using SQLConnection and ConnectionString <p>I'm getting an error connecting to a VistaDB using a connection string in the web.config file.</p>
<p>It works fine using a SQLDataSource AFTER I specified the ProviderName. On another page I'm only connecting in code and </p>
<p><em>Here is the code for the connection string:</em></p>
<p>Public Function CreateConnection() As SqlConnection
_connectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
Return New SqlConnection(_connectionString)
End Function</p>
<p><em>Here is the error:</em></p>
<blockquote>
<p>A network-related or instance-specific
error occurred while establishing a
connection to SQL Server. The server
was not found or was not accessible.
Verify that the instance name is
correct and that SQL Server is
configured to allow remote
connections. (provider: SQL Network
Interfaces, error: 26 - Error Locating
Server/Instance Specified)</p>
</blockquote>
<p><strong>How can I resolve this error?</strong></p>
|
<p>You can't use a SqlConnection with a VistaDB connection string. That is the error you are getting from SQL Server - it can't find that server.</p>
<p>Use a VistaDBConnection instead.</p>
|
What's a Turing machine? <p>What is a Turing machine and why do people keep mentioning it? My IBM PC is all I need to do my computation! Why does anyone care about these machines?</p>
|
<p>The reason that Turing Machines are a big deal has to do with the study of classical Computing Science or Theory of Computation type stuff. It's basically about analyzing the general properties of a computer, such as what theoretical abilities and limitations a computer has, as well as what we mean when we talk about "computing" something.</p>
<p>One example of something that one might study using Turing Machines is <a href="http://en.wikipedia.org/wiki/Halting_problem">The Halting Problem</a>. While this problem is something of an academic exercise, it has easily tangible real-world implications. Why not write a debugger that will simply tell you whether or not your program contains any infinite loops? The Halting Problem establishes that solving this problem for the general case is impossible.</p>
<p>The study of Turing Machines also lends itself to studying language grammars and classes of thereof, which leads into programming language development. The term "regular expressions" comes about because they are a <a href="http://en.wikipedia.org/wiki/Regular_grammar">regular grammar</a>, and the study of these grammars (part of Theory of Computation) will tell you more about exactly what kinds of problems regular expressions can solve and what they can't. For example, a traditional regular expression syntax won't be able to solve the following problem: parse some number N of 'a' chars in input, and then parse the same number N of char 'b'.</p>
<p>If you're interested in a good text about this sort of thing, check out <a href="http://rads.stackoverflow.com/amzn/click/053494728X">Introduction to the Theory of Computation</a> by Michael Sipser. It's good.</p>
|
PHP Script Version Checking/Notification <p>How can I check the version of my script against an online file to see if it's the latest version?</p>
<p><em>For clarification, I'm talking about a script I wrote, not the version of PHP. I'd like to incorporate a way for the end user to tell when I've updated the script.</em></p>
|
<p>To specify the second (more simple) solution <a href="http://stackoverflow.com/questions/236070/php-version-checking#236098">phjr</a> proposed:</p>
<p>Have a file <code>version.txt</code> on your own public server and include the following function into your deployed project/script:</p>
<pre><code>define('REMOTE_VERSION', 'http://your.public.server/version.txt');
// this is the version of the deployed script
define('VERSION', '1.0.1');
function isUpToDate()
{
$remoteVersion=trim(file_get_contents(REMOTE_VERSION));
return version_compare(VERSION, $remoteVersion, 'ge');
}
</code></pre>
<p><code>version.txt</code> should just contain the most recent version number, e.g.:</p>
<pre><code>1.0.2
</code></pre>
|
Is there a Windows Forms native way to flash a form's title bar? <p>Is there a correct way in Windows Forms to flash a titlebar without having to drop to P/Invoking FlashWindow?</p>
<p>I'm using .NET 2.0 for compatibility and size reasons, so maybe I just missed the method because it's in newer versions of the .NET framework.</p>
|
<p>No, I dont think so. PInvoking the <code>FlashWindowEx</code> method is the only way I think. </p>
|
Can garbage collection coexist with explicit memory management? <p>For example, say one was to include a 'delete' keyword in C# 4. Would it be possible to guarantee that you'd never have wild pointers, but still be able to rely on the garbage collecter, due to the reference-based system?</p>
<p>The only way I could see it possibly happening is if instead of references to memory locations, a reference would be an index to a table of pointers to actual objects. However, I'm sure that there'd be some condition where that would break, and it'd be possible to break type safety/have dangling pointers.</p>
<p>EDIT: I'm not talking about just .net. I was just using C# as an example.</p>
|
<p>You can - kind of: make your object disposable, and then dispose it yourself.</p>
<p>A manual delete is unlikely to improve memory performance in a managed environment. It might help with unmanaged ressources, what dispose is all about. </p>
<p>I'd rather have implementing and consuming Disposable objects made easier. I have no consistent, complete idea how this should look like, but managing unmanaged ressources is a verbose pain under .NET.</p>
<p><hr /></p>
<p>An idea for implementing delete:
delete tags an object for manual deletion. At the next garbage collection cycle, the object is removed and all references to it are set to null.</p>
<p>It sounds cool at first (at least to me), but I doubt it would be useful.
This isn't particulary safe, either - e.g. another thread might be busy executing a member method of that object, such an methods needs to throw e.g. when accessing object data.</p>
|
Any Smalltalk on .NET? <p>Are there any usable implementations of Smalltalk for the .NET runtime?</p>
|
<p>There's a project to build Smalltalk on top of the DLR. Unsurprisingly, it's called <a href="http://www.codeplex.com/IronSmalltalk">IronSmaltalk</a>.</p>
|
Using the typical get set properties in C#... with parameters <p>I'd like to do the same in C#. Is there anyway of using properties in C# with parameters in the same way I've done with the parameter 'Key' in this VB.NET example?</p>
<blockquote>
<pre><code>Private Shared m_Dictionary As IDictionary(Of String, Object) = New Dictionary(Of String, Object)
</code></pre>
</blockquote>
<pre><code>Public Shared Property DictionaryElement(ByVal Key As String) As Object
Get
If m_Dictionary.ContainsKey(Key) Then
Return m_Dictionary(Key)
Else
Return [String].Empty
End If
End Get
Set(ByVal value As Object)
If m_Dictionary.ContainsKey(Key) Then
m_Dictionary(Key) = value
Else
m_Dictionary.Add(Key, value)
End If
End Set
End Property
</code></pre>
<p>Thanks</p>
|
<blockquote>
<p>Is there anyway of using properties in C# with parameters</p>
</blockquote>
<p>No. You only can provide the <em>default</em> property in C# with an argument, to model indexed access (as in a dictionary):</p>
<pre><code>public T this[string key] {
get { return m_Dictionary[key]; }
set { m_Dictionary[key] = value; }
}
</code></pre>
<p>Other properties can't have arguments. Use a function instead. By the way, it's recommented to do the same in VB so other .NET languages (C# â¦) can use your code.</p>
<p>By the way, your code is unnecessarily complicated. Four things:</p>
<ul>
<li>You don't need to escape the <code>String</code> identifier. Use the keyword directly.</li>
<li>Why not use <code>""</code>?</li>
<li>Use <code>TryGetValue</code>, it's faster. You query the dictionary twice.</li>
<li>Your setter doesn't have to test whether the value already exists.</li>
</ul>
<p><hr /></p>
<pre><code>Public Shared Property DictionaryElement(ByVal Key As String) As Object
Get
Dim ret As String
If m_Dictionary.TryGetValue(Key, ret) Then Return ret
Return "" ' Same as String.Empty! '
End Get
Set(ByVal value As Object)
m_Dictionary(Key) = value
End Set
End Property
</code></pre>
|
Printing Scrolled Divs <p>I have a web page that displays a long line graph inside a div with overflow-x: scroll.
This works well as a web page allowing the use to scroll back and forward through the graph.</p>
<p>However, when printing the page the scroll position is reset to zero.
Is there a way to overcome this?</p>
|
<p>I think you're going to have to specify an alternate CSS for printing where you somehow need to remove the overflow:</p>
<pre><code><link rel="stylesheet" type="text/cssâ href="sheet.css" media="print" />
</code></pre>
<p>However, maybe there is an approach with JavaScript or even Flash? If I understand correctly, you only want to have a part of the graph printed (the one "selected" by the user?) and not the full one? I'm pretty sure that's not possible with plain HTML/CSS, but I strongly believe that Flash or maybe JavaScript/AJAX (to only load a part of the image at a time) can solve it.</p>
|
How do I get a zipped file's content using the rubyzip library? <p>I'm trying to extract an uploaded zip file and store its contents in the database, one entry per file. The rubyzip library has nearly no useful documentation.</p>
<p>There is an assets table that has key :string (file name) and data :binary (file contents).</p>
<p>I'm using the rubyzip library, and have made it as far as this:</p>
<pre><code>Zip::ZipFile.open(@file_data.local_path) do |zipfile|
zipfile.each do |entry|
next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file?
asset = self.assets.build
asset.key = entry.name
asset.data = ?? # what goes here?
end
end
</code></pre>
<p>How can I set the data from a ZipEntry? Do I have to use a temp file?</p>
|
<p>Found an even more simple way: </p>
<pre><code>asset.data = entry.get_input_stream.read
</code></pre>
|
Embedding Opera in Cocoa <p>So, I'm writing a Cocoa application that needs to be able to display web content using Opera's rendering engine. This is for a feature, not because I'm an Opera fanboi (I'm not). All I've been able to find on the subject is this <a href="http://www.opera.com/pressreleases/en/2003/09/30/" rel="nofollow">press release about Adobe's use of the Opera engine</a>.</p>
<p>Has anyone done this? What's the API like? Are they going to want royalties, payments, an NDA, etc?</p>
<p>Edited to add: This is for a cross-engine web debugging tool. I'm going to be using this alongside WebKit.</p>
|
<p>Adobe has gone to Opera and licensed their software for some (exorbitant?) amount of money. What that probably means is Adobe has access to the library and SDK documentation so they can embed it in their applications. Opera doesn't give its engine away for free as in beer or freedom. It appears there are several B2B opportunities and I'm sure for the right amount of money you can get access to it. More information can be found out at <a href="http://www.opera.com/b2b/" rel="nofollow">http://www.opera.com/b2b/</a>.</p>
|
Is there hard evidence of the ROI of unit testing? <p>Unit testing sounds great to me, but I'm not sure I should spend any time really learning it unless I can convince others that is has significant value. I have to convince the other programmers and, more importantly, the bean-counters in management, that all the extra time spent learning the testing framework, writing tests, keeping them updated, etc.. will pay for itself, and then some.</p>
<p>What proof is there? Has anyone actually developed the same software with two separate teams, one using unit testing and the other not, and compared the results? I doubt it. Am I just supposed to justify it with, "Look it up on the Internet, everybody's talking about it, so it must be the right thing to do"?</p>
<p>Where is the hard evidence that will convince the laymen that unit testing is worth the effort?</p>
|
<p>Yes. This is a <a href="http://collaboration.csc.ncsu.edu/laurie/Papers/TDDpaperv8.pdf">link</a> to a study by Boby George and Laurie Williams at NCST and a <a href="http://research.microsoft.com/en-us/groups/ese/nagappan_tdd.pdf">another</a> by Nagappan et al. I'm sure there are more. Dr. Williams <a href="http://collaboration.csc.ncsu.edu/laurie/publications.html#Testing">publications</a> on testing may provide a good starting point for finding them.</p>
<p>[EDIT] The two papers above specifically reference TDD and show 15-35% increase in initial development time after adopting TDD, but a 40-90% decrease in pre-release defects. If you can't get at the full text versions, I suggest using <a href="http://scholar.google.com">Google Scholar</a> to see if you can find a publicly available version.</p>
|
What methods get called when you resize a JFrame? <p>I'm using a JFrame in which the CENTER portion of the BorderLayout is occupied by a JScrollPane that wraps around a JPanel. What I'm finding is that when I initiate the action that actually causes the JPanel to be displayed, the display doesn't change. But when I resize the JFrame, the new JScrollPane has now magically appeared.</p>
<p>So what methods are called when you resize a JFrame? If I know, then I can call it in the code and avoid having to resize the frame just to see the results of the operation.</p>
|
<p>Its been a little bit since I've done swing, but from memory, calling validate() on the panel should do the trick. This will cause it and its children to have their layout calculated which is when the scrollbars decision is made. If that doesn't work, try calling validate on the frame's content pane. This is a little more costly, but may be needed if other components are being considered.</p>
|
abstract methods in skeletal implementations of interfaces <p>I was re-reading Effective Java (2nd edition) item 18, <a href="http://my.safaribooksonline.com/9780137150021/ch04lev1sec6" rel="nofollow">prefer interfaces to abstract classes</a>. In that item Josh Bloch provides an example of a skeletal implementation of the <code>Map.Entry<K,V></code> interface:</p>
<pre><code>// Skeletal Implementation
public abstract class AbstractMapEntry<K,V>
implements Map.Entry<K,V> {
// Primitive operations
public abstract K getKey();
public abstract V getValue();
// ... remainder omitted
}
</code></pre>
<p>Two questions stem from this example:</p>
<ol>
<li>Why are getKey and getValue explicitly declared here as abstract methods? They are part of the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.Entry.html" rel="nofollow">Map.Entry</a> interface, so I don't see a reason for the redundant declaration in the abstract class.</li>
<li><p>Why use the idiom of leaving these primitives methods, as Mr. Bloch refers to them, as abstract? Why not just do this:</p>
<p>// Skeletal Implementation
public abstract class AbstractMapEntry
implements Map.Entry {
private K key;
private V value;</p>
<pre><code> // Primitive operations
public K getKey() {return key;}
public V getValue() {return value;}
// ... remainder omitted
</code></pre>
<p>}</p></li>
</ol>
<p>The benefits of this are that each subclass doesn't have to define its own set of fields, and can still access the key and value by their accessors. If a subclass truly needs to define its own behavior for the accessors, it can implement the Map.Entry interface directly. The other downside is that in the equals method provided by the skeletal implementation, the abstract accessors are called:</p>
<pre><code>// Implements the general contract of Map.Entry.equals
@Override public boolean equals(Object o) {
if (o == this)
return true;
if (! (o instanceof Map.Entry))
return false;
Map.Entry<?,?> arg = (Map.Entry) o;
return equals(getKey(), arg.getKey()) &&
equals(getValue(), arg.getValue());
}
</code></pre>
<p>Bloch warns against calling overridable methods (item 17) from classes designed for inheritance as it leaves the superclass vulnerable to changes made by subclasses.
Maybe this is a matter of opinion, but I was hoping to determine whether there's more to the story, as Bloch doesn't really elaborate on this in the book.</p>
|
<ol>
<li>I would say it helps emphasize what the concrete class is intended to deal with, instead of just leaving it up to the compiler to tell you (or you having to compare both to see what is missing). Kind of self-documenting code. But it certainly isn't necessary, it is more of a style thing, as far as I can see.</li>
<li>There is more significant logic in returning these values than simple getter and setting. Every class I spot checked in the standard JDK(1.5) did something non-simple on at least one of the methods, so I would guess that he views such an implementation as too naive and it would encourage subclasses to use it instead of thinking through the problem on their own.</li>
</ol>
<p>Regarding the issue with equals, nothing would change if the abstract class implemented them because the issue is overrid**able**. In this case I would say that the equals is attempting to be carefully implemented to anticipate implementations. Normally equals in general should not be implemented to return true between itself and its subclass (although there are plenty that do) due to covariance issues (the superclass will think it equals the subclass, but the subclass won't think it equals the superclass), so this type of implementation of equals is tricky no matter what you do.</p>
|
Tickmark algorithm for a graph axis <p>I'm looking for an algorithm that places tick marks on an axis, given a range to display, a width to display it in, and a function to measure a string width for a tick mark.</p>
<p>For example, given that I need to display between 1e-6 and 5e-6 and a width to display in pixels, the algorithm would determine that I should put tickmarks (for example) at 1e-6, 2e-6, 3e-6, 4e-6, and 5e-6. Given a smaller width, it might decide that the optimal placement is only at the even positions, i.e. 2e-6 and 4e-6 (since putting more tickmarks would cause them to overlap).</p>
<p>A smart algorithm would give preference to tickmarks at multiples of 10, 5, and 2. Also, a smart algorithm would be symmetric around zero.</p>
|
<p>Check Paul Heckbert's article "Nice Numbers for Graph Labels" on Graphics Gems.</p>
<p><a href="http://books.google.com/books?id=fvA7zLEFWZgC&pg=PA61&lpg=PA61#v=onepage&q&f=false">Google book preview</a></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.