input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
---|---|
Question about object-orientation <p>I had this questions since the time I learnt about object-oriented programming. Now, I have got a wonderful forum I thought of asking this.</p>
<p>Lets say we are implementing an employee management application using EJB.</p>
<p>Now, there are 2 ways of doing this.</p>
<ol>
<li><p>Normally, we create entities (POJOs) which represent an employee. Then we create an EJB interface 'EmployeeManager' with add, delete, update, retrieve, retrieveAll methods. This way I could use 'employee' entity as a data transfer object.</p></li>
<li><p>We call the EJB interface itself 'Employee'. Implementation could be called 'EmployeeImpl' which has <em>fields</em> as well as method implementation (add, delete, update, retrieve, retrieveAll). If I am using a layered approach where my business logic needs access to employee details, I need to pass 'EmployeeImpl' (because it contains values).</p></li>
</ol>
<p>Which one do you think is the better way?</p>
<p>I prefer the first one, because it 'looks' fine and does not feel awkward. like</p>
<pre><code>EmployeeMgr empMgr = // JNDI lookup;
Employee emp = new Employee();
empMgr.add(emp);
Employee employees[] = empMgr.retrieveAll();
</code></pre>
<p>Where as the second one would look like (though I am not sure),</p>
<pre><code>Employee emp = // JNDI lookup;
emp.setName(); //set the properties
emp.add();
Employee employees[] = emp.retrieveAll();
</code></pre>
<p>As you can see, the second one looks awkward.</p>
<p>I request you guys to advise me on this.</p>
<p>Thanks
manju</p>
|
<p>Of your examples, I would not recommend #2, because it gives the Employee class too many responsibilities.</p>
<p>Although not giving a straight answer, I can cordially recommend Martin Fowler's book <a href="http://www.martinfowler.com/books.html#eaa" rel="nofollow">Patterns of Enterprise Application Architecture</a>. It has been a great eye-opener for me personally, and describes several different approaches to this.</p>
<p>I also think the open-source <a href="http://www.hibernate.org/" rel="nofollow">Hibernate</a> is a great tool for persisting entities. I'm sure you will find lots of good input there.</p>
|
Whats the best book/site/tutorial for learning object oriented php? <p>Im pretty familiar with procedural side of php, but I would like to learn the OO side of things. Can you guys suggest some (short) reads that would get me on my way?</p>
<p>Would prefer online articles, to paper. </p>
|
<p>I'd personally reccomend <a href="http://rads.stackoverflow.com/amzn/click/1590599098" rel="nofollow">PHP Objects, Patterns and Practice</a></p>
|
What tool do you use to do burndown charts? <p>do you use a tool? or just manually make them?</p>
|
<p><a href="http://code.google.com/apis/chart/basics.html">Google charts api/server</a> can make one fairly easily</p>
<p><img src="http://chart.apis.google.com/chart?chs=600x250&cht=lxy&chtt=Burndown&chxt=x,y&chxl=days&chdl=Estimated|Actual&chco=FF0000,00FF00&chd=t:-1|40,36,32,28,24,20,16,12,8,4,0|-1|40,38,36,35,20,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1&chxr=0,0,30,2|1,0,40,2&chds=0,40&chm=s,FF0000,0,-1,5|s,0000ff,1,-1,5|s,00aa00,2,-1,5" alt="Burndown 2" />
<img src="http://chart.apis.google.com/chart?chs=600x250&chtt=Burndown&cht=lc&chxt=x,y&chxl=days&chdl=Estimated|Actual&chco=FF0000,00FF00&chd=t:40,36,32,28,24,20,16,12,8,4,0|40,39,38,37,36,35,30,25,23,21,18,14,4,0,0&chxr=0,0,30,2|1,0,40,2&chds=0,40" alt="Burn down" /></p>
<p>You specify everything in the URL so it's easy to update:</p>
<pre><code>http://chart.apis.google.com/chart?
chs=600x250& // the size of the chart
chtt=Burndown& // Title
cht=lc& // The chart type - "lc" means a line chart that only needs Y values
chdl=estimated|actual& // The two legends
chco=FF0000,00FF00& // The colours in hex of the two lines
chxr=0,0,30,2|1,0,40,2& // The data range for the x,y (index,min,max,interval)
chds=0,40 // The min and max values for the data. i.e. amount of features
chd=t:40,36,32,28,24,20,16,12,8,4,0|40,39,38,37,36,35,30,25,23,21,18,14,12,9,1 // Data
</code></pre>
<p>The URL above plots in intervals of 2 - so work every 2 days. You'll need a bigger size chart for every day. To do this make the data have 30 values for estimated and actual, and change the "chxr" so the interval is 1, not two.</p>
<p>You can plot only the days done more clearly with the "lxy" chart type (the first image). This needs you to enter the X data values too (so a vector). Use -1 for unknown.</p>
|
C# - Why won't a fullscreen winform app ALWAYS cover the taskbar? <p>I'm using Windows Vista and C#.net 3.5, but I had my friend run the program on XP and has the same problem.</p>
<p>So I have a C# program that I have running in the background with an icon in the SystemTray. I have a low level keyboard hook so when I press two keys (Ctr+windows in this case) it'll pull of the application's main form. The form is set to be full screen in the combo key press even handler:</p>
<pre><code>this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
</code></pre>
<p>So it basically works. When I hit CTR+Windows it brings up the form, no matter what program I have given focus to. But sometimes, the taskbar will still show up over the form, which I don't want. I want it to always be full screen when I hit that key combo.</p>
<p>I figure it has something to do with what application has focus originally. But even when I click on my main form, the taskbar sometimes stays there. So I wonder if focus really is the problem. It just seems like sometimes the taskbar is being stubborn and doesn't want to sit behind my program.</p>
<p>Anyone have any ideas how I can fix this?</p>
<p>EDIT: More details-
I'm trying to achieve the same effect that a web browser has when you put it into fullscreen mode, or when you put powerpoint into presentation mode.</p>
<p>In a windows form you do that by putting the border style to none and maximizing the window. But sometimes the window won't cover the taskbar for some reason. Half the time it will.</p>
<p>If I have the main window topmost, the others will fall behind it when I click on it, which I don't want if the taskbar is hidden.</p>
|
<p>Try this (where <code>this</code> is your form):</p>
<pre><code>this.Bounds = Screen.PrimaryScreen.Bounds;
this.TopMost = true;
</code></pre>
<p>That'll set the form to fullscreen, and it'll cover the taskbar.</p>
|
How do I ignore ampersands in a SQL script running from SQL Plus? <p>I have a SQL script that creates a package with a comment containing an ampersand (&). When I run the script from SQL Plus, I am prompted to enter a substitute value for the string starting with &. How do I disable this feature so that SQL Plus ignores the ampersand?</p>
|
<p>This may work for you:</p>
<pre><code>set define off
</code></pre>
<p>Otherwise the ampersand needs to be at the end of a string, </p>
<pre><code>'StackOverflow &' || ' you'
</code></pre>
<p>EDIT: I was click-happy when saving... This was referenced from a <a href="http://blog.andrewbeacock.com/2008/09/using-ampersands-without-variable_15.html">blog</a>.</p>
|
How to start IDLE (Python editor) without using the shortcut on Windows Vista? <p>I'm trying to teach Komodo to fire up <a href="http://en.wikipedia.org/wiki/IDLE%5F%28Python%29">IDLE</a> when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.</p>
<p>I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.</p>
<p>How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.</p>
|
<p>There's a file called idle.py in your Python installation directory in Lib\idlelib\idle.py</p>
<p>If you run that file with Python, then IDLE should start.</p>
<blockquote>
<p>c:\Python25\pythonw.exe c:\Python25\Lib\idlelib\idle.py</p>
</blockquote>
|
Best way to manipulate pages while embedding Webkit? <p>I'm using Webkit-sharp to embed Webkit into an application and I need to hook certain links to perform actions in my app rather than their normal action.</p>
<p>I've considered using Javascript to iterate over the anchor tags and replace the ones that match with the proper link, but I'm wondering if this is the best way. Is there a preferred way of doing this?</p>
|
<p>jQuery has a lot of useful iteration features that may be able to use for that. :-) I haven't used jQuery, but <a href="http://docs.jquery.com/Traversing/find" rel="nofollow"><code>find</code></a> and <a href="http://docs.jquery.com/Attributes/attr" rel="nofollow"><code>attr</code></a> look promising for your purposes.</p>
|
Trying to resize a jQuery dialog in IE6? <p>I thought I had seen a bug report about this on the jQuery site, but now I cannot find it. I'm trying to resize a dialog in IE6. But when the element is resized, the content and title bar don't resize down. They will resize up if the dialog is made larger, however. The result is that the close button ends up being cut off and the content is clipped if the user resize the dialog to be smaller. </p>
<p>I've tried handling the resizeStop event and manually resizing the content and titlebar, but this can gave me weird results. The sizes and positions of elements in the content area were still off. Also, even though I resize the title bar, the close button still doesn't move back into view. Any ideas? If this is a bug in jQuery-ui, does anyone know a good workaround?</p>
<pre><code><html>
<head>
<title>Example of IE6 resize issue</title>
<link rel="stylesheet" type="text/css" href="http://ui.jquery.com/repository/latest/themes/flora/flora.all.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
google.setOnLoadCallback(
function() {
$(document).ready(function()
{
$("#main-dialog").dialog();
});
});
</script>
</head>
<body>
<div id="main-dialog">
This is just some simple content that will fill the dialog. This example is
sufficient to reproduce the problem in IE6. It does not seem to occur in IE7
or FF. I haven't tried with Opera or Safari.
</div>
</body>
</html>
</code></pre>
|
<p>I was able to come up with a solution. If you add the style <strong>overflow: hidden</strong> to the dialog container div element (which has the css class .ui-dialog-container applied to it), then everything resizes correctly. All I did was add a css rule as follows to the flora theme:</p>
<pre><code>.ui-dialog .ui-dialog-container {
overflow: hidden;
}
</code></pre>
<p>It could also be corrected by executing the following:</p>
<pre><code>if ($.browser.msie && $.browser.version == 6)
{
$(".ui-dialog-container").css({ overflow: 'hidden' });
}
</code></pre>
<p>This corrected the issue I was seeing under IE6 and has not introduced any problems in FireFox.</p>
|
ASP.NET TextBox control with label text in the background <p>I'm creating a login page. I want to create ASP.NET TextBox controls that have "Username" and "Password" as their Text, but as soon as they receive focus, these words should disappear and whatever the user types should appear, just like normal textbox. If the user leaves it blank and tabs to the next textbox, then these words appear again. This will eliminate the need for having separate labels in front of the text boxes. I would appreciate if someone can share their expertise for doing this.</p>
|
<p>Use the <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/TextBoxWatermark/TextBoxWatermark.aspx">TextBox Watermark Extender</a> that's in Microsoft's AJAX Toolkit.</p>
|
How do you use the ellipsis slicing syntax in Python? <p>This came up in <a href="http://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a>, but I can't see good documentation or examples that explain how the feature works.</p>
|
<p>The ellipsis is used to slice higher-dimensional data structures. </p>
<p>It's designed to mean <em>at this point, insert as many full slices (<code>:</code>) to extend the multi-dimensional slice to all dimensions</em>.</p>
<p><strong>Example</strong>:</p>
<pre><code>>>> from numpy import arange
>>> a = arange(16).reshape(2,2,2,2)
</code></pre>
<p>Now, you have a 4-dimensional matrix of order 2x2x2x2. To select all first elements in the 4th dimension, you can use the ellipsis notation</p>
<pre><code>>>> a[..., 0].flatten()
array([ 0, 2, 4, 6, 8, 10, 12, 14])
</code></pre>
<p>which is equivalent to</p>
<pre><code>>>> a[:,:,:,0].flatten()
array([ 0, 2, 4, 6, 8, 10, 12, 14])
</code></pre>
<p>In your own implementations, you're free to ignore the contract mentioned above and use it for whatever you see fit.</p>
|
RTF control for .Net 1.1 Windows <p>Can anyone recommend a cheap and good RTF control for .Net 1.1 Windows development. It needs to be able to do print/preview and some basic text formatting, fonts etc but nothing too advanced.</p>
<p>Cheers</p>
<p>Andreas</p>
|
<p>If you're interested in rolling out your own, the framework provides a RTF control by default. It's arcane, but one can learn enough RTF to create simple formatting, and printing/print previewing can both be implemented using native classes as well.</p>
|
How would you implement a badge system like StackOverflow's? <p>Just wondering how you would do this. Would you have some sort of process that scanned through all the actions that took place over the past X minutes? Would you trigger a badge update check every time any action took place (up vote, down vote, tag, etc.)? It seems like this would be a relatively expensive process one way or another.</p>
|
<p>Perhaps a bit of both. I would probably queue up a check every time an action occurred and have a process that goes down the queue and determines if a badge has been earned for each check. This way it's semi-real time without causing pages to take more time to load. In fact, here on StackOverflow I've noticed a delay between when the badge is earned and when the system realizes it, so this site probably uses the same approach.</p>
|
What is wrong with my snap to grid code? <p>First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong.</p>
<p>Here's the situation</p>
<p>I have an abstract concept of a grid, with Y steps exactly Y_STEP apart (the x steps are working fine so ignore them for now)</p>
<p>The grid is in an abstract coordinate space, and to get things to line up I've got a magic offset in there, let's call it Y_OFFSET</p>
<p>to snap to the grid I've got the following code (python)</p>
<pre><code>def snapToGrid(originalPos, offset, step):
index = int((originalPos - offset) / step) #truncates the remainder away
return index * gap + offset
</code></pre>
<p>so I pass the cursor position, Y_OFFSET and Y_STEP into that function and it returns me the nearest floored y position on the grid</p>
<p>That appears to work fine in the original scenario, however when I take into account the fact that the view is scrollable things get a little weird.</p>
<p>Scrolling is made as basic as I can get it, I've got a viewPort that keeps count of the distance scrolled along the Y Axis and just offsets everything that goes through it.</p>
<p>Here's a snippet of the cursor's mouseMotion code:</p>
<pre><code>def mouseMotion(self, event):
pixelPos = event.pos[Y]
odePos = Scroll.pixelPosToOdePos(pixelPos)
self.tool.positionChanged(odePos)
</code></pre>
<p>So there's two things to look at there, first the Scroll module's translation from pixel position to the abstract coordinate space, then the tool's positionChanged function which takes the abstract coordinate space value and snaps to the nearest Y step.</p>
<p>Here's the relevant Scroll code</p>
<pre><code>def pixelPosToOdePos(pixelPos):
offsetPixelPos = pixelPos - self.viewPortOffset
return pixelsToOde(offsetPixelPos)
def pixelsToOde(pixels):
return float(pixels) / float(pixels_in_an_ode_unit)
</code></pre>
<p>And the tools update code</p>
<pre><code>def positionChanged(self, newPos):
self.snappedPos = snapToGrid(originalPos, Y_OFFSET, Y_STEP)
</code></pre>
<p>The last relevant chunk is when the tool goes to render itself. It goes through the Scroll object, which transforms the tool's snapped coordinate space position into an onscreen pixel position, here's the code:</p>
<pre><code>#in Tool
def render(self, screen):
Scroll.render(screen, self.image, self.snappedPos)
#in Scroll
def render(self, screen, image, odePos):
pixelPos = self.odePosToPixelPos(odePos)
screen.blit(image, pixelPos) # screen is a surface from pygame for the curious
def odePosToPixelPos(self.odePos):
offsetPos = odePos + self.viewPortOffset
return odeToPixels(offsetPos)
def odeToPixels(odeUnits):
return int(odeUnits * pixels_in_an_ode_unit)
</code></pre>
<p>Whew, that was a long explanation. Hope you're still with me... </p>
<p>The problem I'm now getting is that when I scroll up the drawn image loses alignment with the cursor.<br />
It starts snapping to the Y step exactly 1 step below the cursor.
Additionally it appears to phase in and out of allignment.<br />
At some scrolls it is out by 1 and other scrolls it is spot on.<br />
It's never out by more than 1 and it's always snapping to a valid grid location.</p>
<p>Best guess I can come up with is that somewhere I'm truncating some data in the wrong spot, but no idea where or how it ends up with this behavior.</p>
<p>Anyone familiar with coordinate spaces, scrolling and snapping?</p>
|
<p>Ok, I'm answering my own question here, as alexk mentioned, using int to truncate was my mistake. </p>
<p>The behaviour I'm after is best modeled by math.floor().</p>
<p>Apologies, the original question does not contain enough information to really work out what the problem is. I didn't have the extra bit of information at that point.</p>
<p>With regards to the typo note, I think I may be using the context in a confusing manner... From the perspective of the positionChanged() function, the parameter is a new position coming in.<br />
From the perspective of the snapToGrid() function the parameter is an original position which is being changed to a snapped position.
The language is like that because part of it is in my event handling code and the other part is in my general services code. I should have changed it for the example</p>
|
Is there a way to use the same file for both a RTP and a kernel module in vxWorks? <p>We have a vxWorks application that we would like to deploy either as a kernel module, or as a Real-Time process.</p>
<p>Is there a way to do this from the same source file, or do we have to create one file for the kernel module and another for the RTP?</p>
|
<p>The easiest solution would be to have a single file that can be compiled either as a kernel module, or as a Real-Time Process.
It probably should look something like this:</p>
<pre><code>
void MyModule_Init()
{
// Initialize the module
...
}
...
#ifdef __RTP__
int main(...)
{
// RTP Main just invokes the Module's initialization
MyModule_Init();
}
#endif
</code></pre>
<p>The __RTP__ macro is defined if the build is for a RTP environment<br />
The _WRS_KERNEL macro is defined if the build is for a kernel environment.</p>
<p>With those two macros, you can have code compiling for both environment.</p>
|
What is the best signature for overloaded arithmetic operators in C++? <p>I had assumed that the canonical form for operator+, assuming the existence of an overloaded operator+= member function, was like this:</p>
<pre><code>const T operator+(const T& lhs, const T& rhs)
{
return T(lhs) +=rhs;
}
</code></pre>
<p>But it was pointed out to me that this would also work:</p>
<pre><code>const T operator+ (T lhs, const T& rhs)
{
return lhs+=rhs;
}
</code></pre>
<p>In essence, this form transfers creation of the temporary from the body of the implementation to the function call.</p>
<p>It seems a little awkward to have different types for the two parameters, but is there anything wrong with the second form? Is there a reason to prefer one over the other?</p>
|
<p>I'm not sure if there is much difference in the generated code for either.</p>
<p>Between these two, I would (personally) prefer the first form since it better conveys the intention. This is with respect to both your reuse of the += operator and the idiom of passing templatized types by const&.</p>
|
GCC inline assembler, mixing register sizes (x86) <p>Does anyone know how I can get rid of the following assembler warning?</p>
<p>Code is x86, 32 bit:</p>
<pre><code>int test (int x)
{
int y;
// do a bit-rotate by 8 on the lower word. leave upper word intact.
asm ("rorw $8, %0\n\t": "=q"(y) :"0"(x));
return y;
}
</code></pre>
<p>If I compile it I get the following (very valid) warning:</p>
<pre><code>Warning: using `%ax' instead of `%eax' due to `w' suffix
</code></pre>
<p>What I'm looking for is a way to tell the compiler/assembler that I want to access the lower 16 bit sub-register of %0. Accessing the byte sub-registers (in this case AL and AH) would be nice to know as well. </p>
<p>I've already chosen the "q" modifier, so the compiler is forced to use EAX, EBX, ECX or EDX. I've made sure the compiler has to pick a register that has sub-registers.</p>
<p>I know that I can force the asm-code to use a specific register (and its sub-registers), but I want to leave the register-allocation job up to the compiler.</p>
|
<p>You can use <code>%w0</code> if I remember right. I just tested it, too. :-)</p>
<pre><code>int
test(int x)
{
int y;
asm ("rorw $8, %w0" : "=q" (y) : "0" (x));
return y;
}
</code></pre>
<p>Edit: In response to the OP, yes, you can do the following too:</p>
<pre><code>int
test(int x)
{
int y;
asm ("xchg %b0, %h0" : "=Q" (y) : "0" (x));
return y;
}
</code></pre>
<p>At present, the only place (that I know of) it's documented in is <code>gcc/config/i386/i386.md</code>, not in any of the standard documentation.</p>
|
How to count rows in Lift (Scala's web framework) <p>I want to add a property to my User model that returns the number of rows in the Project table that have a user Id of the user.</p>
<p>So something like this...</p>
<pre><code>def numProjects = {
/* somehow get count from Project table
The straight sql would be:
SELECT COUNT(*) FROM projects WHERE userId = <the current user>
*/
}
</code></pre>
|
<p>According to the documentation <a href="http://scala-tools.org/mvnsites/liftweb/lift-webkit/scaladocs/net/liftweb/mapper/MetaMapper.html">here</a> (found <a href="http://scala-tools.org/mvnsites/liftweb/lift-webkit/scaladocs/">here</a>), assuming you're looking for the project count for a User of id 1234 and assuming that your Project model inherits the MetaMapper trait (probably through KeyedMetaMapper), it seems you can use the count method as such:</p>
<pre><code>Project.count(By(User.id, 1234))
</code></pre>
<p>or</p>
<pre><code>Project.count(BySql("userId = ?", 1234))
</code></pre>
<p>I can't test because I haven't used Lift yet, but it looks right... :) Let me know if it works!</p>
|
Best way to secure an AJAX app <p>I am currently working on the authentication of an AJAX based site, and was wondering if anybody had any reccomendations on best practices for this sort of thing.</p>
<p>My original approach was a cookie based system. Essentially I set a cookie with an auth code, and every data access changed the cookie. As well, whenever there was a failed authentication, all sessions by that user were de-authenticated, to keep hijackers out. To hijack a session, somebody would have to leave themselves logged in, and a hacker would need to have the very last cookie update sent to spoof a session.</p>
<p>Unfortunatley, due to the nature of AJAX, when making multiple requests quickly, they might come back out of order, setting the cookie wrong, and breaking the session, so I need to reimplement.</p>
<p>My ideas were: </p>
<ul>
<li>A decidedly less secure session based method</li>
<li>using SSL over the whole site (seems like overkill)</li>
<li>Using an iFrame which is ssl authenticated to do secure transactions (I just sorta assume this is possible, with a little bit of jquery hacking)</li>
</ul>
<p>The issue is not the data being transferred, the only concern is that somebody might get control over an account that is not theirs.</p>
<p>A decidedly less secure session based method</p>
|
<p>Personally, I have not found using SSL for the entire site (or most of it) to be overkill. Maybe a while ago when speeds and feeds were slower. Now I wouldn't hesitate to put any part of a site under SSL.
<p>
If you've decided that using SSL for the entire site is acceptable, you might consider just using the old "Basic Authentication" where the server returns the <em>401</em> response which causes the browser to prompt for username/password. If your application can live with this type of login, is works great for AJAX and all other accesses to your site because the browser handles re-submitting requests with appropriate credentials (and it is safe if you use SSL, but <b>only</b> if you use SSL -- don't use Basic auth with plain http!).</p>
|
What are the print functions in Adobe AIR? <p>I've been trying to figure out how to print in Adobe AIR. I know the standard javascript functions don't work. The AIRforJSDev guide says:
"The window.print() method is not supported within Adobe
AIR 1.0. There are other methods available via the exposed AIRAPIs that give you access to printing within the runtime"</p>
<p>But I can't find those functions. I've looked in the language reference but can't find them there anywhere. Where are they and what are they ? </p>
|
<p>What you need to do is access the AS3 <a href="http://livedocs.adobe.com/flex/201/langref/flash/printing/PrintJob.html" rel="nofollow">flash.printing.PrintJob</a> API. Here's a page on <a href="http://livedocs.adobe.com/air/1/devappshtml/help.html?content=ProgrammingHTMLAndJavaScript_05.html" rel="nofollow">accessing flash API from javascript</a> (basically you just do window.runtime.XYZ where XYZ is the flash API). </p>
<p>You should look up tutorials on printing in flash, just need minor tweaks to do it from JS. Here's two random tutorials on printing in flash I found: <a href="http://blog.tikikitchen.com/2008/04/18/printing-in-flash-in-1000000000-simple-steps" rel="nofollow">one</a>, <a href="http://snipplr.com/view/4942/as3-flash-printing-basics/" rel="nofollow">two</a></p>
|
Connection to report server could not be made from BI VS 2005 but the report server is browseable <p>I have IIS6 configured such that browsing to <a href="http://localhost:8082/Reports" rel="nofollow">http://localhost:8082/Reports</a> gets me the reporting services default home page, which is all as expected. However, when I try to publish a report via Microsoft Business Intelligence Visual Studio 2005 I get the following error: A connection could not be made to the report server <a href="http://localhost:8082/Reports" rel="nofollow">http://localhost:8082/Reports</a> The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version. </p>
<p>I have windows authentication turned on for report server. Does that have anything to do with not being able to publish projects?</p>
|
<p>Have you tried to publish you report to:</p>
<p><a href="http://localhost:8082/ReportsServer" rel="nofollow">http://localhost:8082/ReportsServer</a></p>
<p>"/ReportsServer" is the webservice for Reporting Services. "/Reports" is the front end.</p>
|
Can I make a SharePoint Image Web Part clickable to link to another page <p>The Image Web Part doesn't seem to have an href attribute that I can set. Is there something I am missing?</p>
|
<p>Does it have to be an Image Web Part? If not I would simply use a <a href="http://office.microsoft.com/en-us/sharepointserver/HA100240461033.aspx">Content Editor Web Part</a> and paste the required HTML there.</p>
<pre><code><a href="http://www.google.com"><img src="urlToImage" /></a>
</code></pre>
|
What is the difference between Events with Delegate Handlers and those without? <p>What is the difference between this:</p>
<pre><code>this.btnOk.Click += new System.EventHandler(this.btnOK_Click);
</code></pre>
<p>and this?</p>
<pre><code>this.btnOk.Click += this.btnOK_Click;
</code></pre>
<p>They both work. The former is what Visual Studio defaults to when you use the snippets. But it seems like it only ads extra verbiage, or am I missing something?</p>
|
<p>No difference. Omitting the delegate instantiation is just syntax candy; the C# compiler will generate the delegate instantiation for you under the hood.</p>
|
What tools allows me to keep track of html tags when doing web development? <p>What tools allows me keep track of tags when doing web development? For example, I would like to be able to quickly find whether I missed closing a div tag.</p>
<p>At the moment I am using notepad++ to write html. It highlights starting and ending tags, but it can take me time to review almost all tags to find where I went wrong.</p>
|
<p><a href="http://tidy.sourceforge.net/" rel="nofollow">HTMLTidy</a> is pretty much the de-facto standard for this kind of thing nowadays</p>
<p><a href="http://dev.int64.org/tidy.html" rel="nofollow">Tidy Windows Installer</a></p>
<p><a href="http://tidy.sourceforge.net/docs/faq.html" rel="nofollow">Tidy FAQ</a></p>
|
Specify the from user when sending email using the mail command <p>Does anyone know how to change the from user when sending email using the mail command? I have looked through the man page and can not see how to do this. </p>
<p>We are running Redhat Linux 5.</p>
|
<p>You can specify any extra header you may need with -a</p>
<pre><code>$mail -s "Some random subject" -a "From: [email protected]" [email protected]
</code></pre>
|
Business Logic: Database or Application Layer <p>The age old question. Where should you put your business logic, in the database as stored procedures ( or packages ), or in the application/middle tier? And more importantly, Why?</p>
<p>Assume database independence is not a goal.</p>
|
<p>Maintainability of your code is always a big concern when determining where business logic should go. </p>
<p>Integrated debugging tools and more powerful IDEs generally make maintaining middle tier code easier than the same code in a stored procedure. Unless there is a real reason otherwise, you should start with business logic in your middle tier/application and not in stored procedures.</p>
<p>However when you come to reporting and data mining/searching, stored procedures can often a better choice. This is thanks to the power of the databases aggregation/filtering capabilities and the fact you are keeping processing very close the the source of the data. But this may not be what most consider classic business logic anyway.</p>
|
I want to log the Poison message that my wcf service is dropping using MSMQ 3.0 and windows 2003 <p>I want to log the Poison message that my wcf service is dropping using MSMQ 3.0 and windows 2003</p>
|
<p>You can implement a custom <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx" rel="nofollow">IErrorHandler</a> and associate it with your service using a custom behavior. In your implementation, check if the exception raised is of type MsmqPoisonMessageException, and if so, go out and grab the message from the queue using System.Messaging,MessageQueue and log it.</p>
<p>There's a <a href="http://msdn.microsoft.com/en-us/library/ms751472.aspx" rel="nofollow">sample</a> that shows how most of this stuff is done: it moves the message to another queue, but should be trivial to modify it so that it just logs the message somewhere instead.</p>
|
How do I sort a VARCHAR column in SQL server that contains numbers? <p>I have a <code>VARCHAR</code> column in a <code>SQL Server 2000</code> database that can contain either letters or numbers. It depends on how the application is configured on the front-end for the customer. </p>
<p>When it does contain numbers, I want it to be sorted numerically, e.g. as "1", "2", "10" instead of "1", "10", "2". Fields containing just letters, or letters and numbers (such as 'A1') can be sorted alphabetically as normal. For example, this would be an acceptable sort order.</p>
<pre><code>1
2
10
A
B
B1
</code></pre>
<p>What is the best way to achieve this? </p>
|
<p>One possible solution is to pad the numeric values with a character in front so that all are of the same string length.</p>
<p>Here is an example using that approach:</p>
<pre class="lang-sql prettyprint-override"><code>select MyColumn
from MyTable
order by
case IsNumeric(MyColumn)
when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn
else MyColumn
end
</code></pre>
<p>The <code>100</code> should be replaced with the actual length of that column.</p>
|
Shortcut to switch between markup and code <p>Using Visual Studio 2008 Team Edition, is it possible to assign a shortcut key that switches between markup and code? If not, is it possible to assign a shortcut key that goes from code to markup?</p>
|
<p>The following is a macro taken from a comment by Lozza on <a href="http://www.codinghorror.com/blog/archives/000315.html" rel="nofollow">http://www.codinghorror.com/blog/archives/000315.html</a>. You just need to bind it to a shortcut of your choice:</p>
<pre><code>Sub SwitchToMarkup()
Dim FileName
If (DTE.ActiveWindow.Caption().EndsWith(".cs")) Then
' swith from .aspx.cs to .aspx
FileName = DTE.ActiveWindow.Document.FullName.Replace(".cs", "")
If System.IO.File.Exists(FileName) Then
DTE.ItemOperations.OpenFile(FileName)
End If
ElseIf (DTE.ActiveWindow.Caption().EndsWith(".aspx")) Then
' swith from .aspx to .aspx.cs
FileName = DTE.ActiveWindow.Document.FullName.Replace(".aspx", ".aspx.cs")
If System.IO.File.Exists(FileName) Then
DTE.ItemOperations.OpenFile(FileName)
End If
ElseIf (DTE.ActiveWindow.Caption().EndsWith(".ascx")) Then
FileName = DTE.ActiveWindow.Document.FullName.Replace(".ascx", ".ascx.cs")
If System.IO.File.Exists(FileName) Then
DTE.ItemOperations.OpenFile(FileName)
End If
End If
End Sub
</code></pre>
|
How to export fonts and colors from VS2008 to VS2005? <p>I have been forced to work in Visual Studio 2005 and would like to export my fonts and colors from Visual Studio 2008. However, VS2005 complains about wrong export document version. Is there any good way to do this besides manually changing each color and font?</p>
|
<p>I think there's a tag in the exported file called "applicationIdentity" that is set to a value of "9.0" by 2008, change it to "8.0" and the file should import. I don't recall it causing any problems from settings that are 2k8 specific, but take a backup of your settings first!</p>
<p>UPDATE: Just looked in an export file and there is indeed a '<ApplicationIdentity version="8.0"/>' in a 2k5 file so it should be "9.0" in the 2k8 file (I haven't VS2k8 on my PC here to verify this beyond a doubt).</p>
|
Detect via javascript whether Silverlight is installed <p>Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser?</p>
<p>I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load.</p>
<p><strong>Edit:</strong> From link provided in accepted answer:</p>
<p>Include Silverlight.js (from Silverlight SDK)</p>
<pre><code>Silverlight.isInstalled("2.0");
</code></pre>
|
<p>Include Silverlight.js (from Silverlight SDK)</p>
<p><code>Silverlight.isInstalled("4.0")</code></p>
<hr>
<p><strong>Resource:</strong></p>
<p><a href="http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx" rel="nofollow"><a href="http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx</a></a></p>
|
How can you get more information about processes when Linux runs out of memory? <p>I had recently a problem with oom-killer starting to kill processes after some time. I could see that the memory was consumed, but by the time I got to the server it wasn't clear anymore what consumed it. Is there a good non-obvious place to get more info about oom-killer? E.g. detailed info about processes at the time of activation, detailed info about killed processes and reasons for the choice?</p>
<p>I'm looking for a specific place to find this information, specific tool to gather it or some configuration to improve oom-killer reporting. I'm not looking for generic info about oom-killer. /var/messages by default will only contain a detailed report on the free/allocated memory, but not specific processes it was allocated to.</p>
|
<p>You can check the messages log file to see which process got killed and some related information. As for the reasons:</p>
<blockquote>
<p>... the ideal candidate for liquidation is a recently started, non privileged process which together with it's children uses lots of memory, has been nice'd, and does no raw I/O. Something like a nohup'd parallel kernel build (which is not a bad choice since all results are saved to disk and very little work is lost when a 'make' is terminated).</p>
</blockquote>
<p>From <a href="http://linux-mm.org/OOM_Killer" rel="nofollow">here</a>. </p>
<p>You can define some processes to be immune to the killer, adjust the swappiness parameter in case you have it too low (which makes the killer trigger happy) and check for things listed <a href="http://linux.derkeiler.com/Mailing-Lists/RedHat/2007-08/msg00061.html" rel="nofollow">here</a></p>
|
Save drop-down history in a Firefox Toolbar <p>I'm doing some testing on Firefox toolbars for the sake of learning and I can't find out any information on how to store the contents of a "search" drop-down inside the user's profile.</p>
<p>Is there any tutorial on how to sort this out?</p>
|
<p>Since it's taking quite a bit to get an answer I went and investigate it myself.
Here is what I've got now. Not all is clear to me but it works.</p>
<p>Let's assume you have a <textbox> like this, on your .xul:</p>
<pre><code><textbox id="search_with_history" />
</code></pre>
<p>You now have to add some other attributes to enable history.</p>
<pre><code><textbox id="search_with_history" type="autocomplete"
autocompletesearch="form-history"
autocompletesearchparam="Search-History-Name"
ontextentered="Search_Change(param);"
enablehistory="true"
/>
</code></pre>
<p>This gives you the minimum to enable a history on that textbox.<br/>
For some reason, and here is where my ignorance shows, the onTextEntered event function has to have the param to it called "param". I tried "event" and it didn't work.<br/>
But that alone will not do work by itself. One has to add some Javascript to help with the job.</p>
<pre><code>// This is the interface to store the history
const HistoryObject = Components.classes["@mozilla.org/satchel/form-history;1"]
.getService(
Components.interfaces.nsIFormHistory2 || Components.interfaces.nsIFormHistory
);
// The above line was broken into 4 for clearness.
// If you encounter problems please use only one line.
// This function is the one called upon the event of pressing <enter>
// on the text box
function Search_Change(event) {
var terms = document.getElementById('search_with_history').value;
HistoryObject.addEntry('Search-History-Name', terms);
}
</code></pre>
<p>This is the absolute minimum to get a history going on.</p>
|
How to do query auto-completion/suggestions in Lucene? <p>I'm looking for a way to do query auto-completion/suggestions in Lucene. I've Googled around a bit and played around a bit, but all of the examples I've seen seem to be setting up filters in Solr. We don't use Solr and aren't planning to move to using Solr in the near future, and Solr is obviously just wrapping around Lucene anyway, so I imagine there must be a way to do it!</p>
<p>I've looked into using EdgeNGramFilter, and I realise that I'd have to run the filter on the index fields and get the tokens out and then compare them against the inputted Query... I'm just struggling to make the connection between the two into a bit of code, so help is much appreciated!</p>
<p>To be clear on what I'm looking for (I realised I wasn't being overly clear, sorry) - I'm looking for a solution where when searching for a term, it'd return a list of suggested queries. When typing 'inter' into the search field, it'll come back with a list of suggested queries, such as 'internet', 'international', etc.</p>
|
<p>Based on @Alexandre Victoor's answer, I wrote a little class based on the Lucene Spellchecker in the contrib package (and using the LuceneDictionary included in it) that does exactly what I want.</p>
<p>This allows re-indexing from a single source index with a single field, and provides suggestions for terms. Results are sorted by the number of matching documents with that term in the original index, so more popular terms appear first. Seems to work pretty well :)</p>
<pre><code>import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.ISOLatin1AccentFilter;
import org.apache.lucene.analysis.LowerCaseFilter;
import org.apache.lucene.analysis.StopFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter;
import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter.Side;
import org.apache.lucene.analysis.standard.StandardFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.spell.LuceneDictionary;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/**
* Search term auto-completer, works for single terms (so use on the last term
* of the query).
* <p>
* Returns more popular terms first.
*
* @author Mat Mannion, [email protected]
*/
public final class Autocompleter {
private static final String GRAMMED_WORDS_FIELD = "words";
private static final String SOURCE_WORD_FIELD = "sourceWord";
private static final String COUNT_FIELD = "count";
private static final String[] ENGLISH_STOP_WORDS = {
"a", "an", "and", "are", "as", "at", "be", "but", "by",
"for", "i", "if", "in", "into", "is",
"no", "not", "of", "on", "or", "s", "such",
"t", "that", "the", "their", "then", "there", "these",
"they", "this", "to", "was", "will", "with"
};
private final Directory autoCompleteDirectory;
private IndexReader autoCompleteReader;
private IndexSearcher autoCompleteSearcher;
public Autocompleter(String autoCompleteDir) throws IOException {
this.autoCompleteDirectory = FSDirectory.getDirectory(autoCompleteDir,
null);
reOpenReader();
}
public List<String> suggestTermsFor(String term) throws IOException {
// get the top 5 terms for query
Query query = new TermQuery(new Term(GRAMMED_WORDS_FIELD, term));
Sort sort = new Sort(COUNT_FIELD, true);
TopDocs docs = autoCompleteSearcher.search(query, null, 5, sort);
List<String> suggestions = new ArrayList<String>();
for (ScoreDoc doc : docs.scoreDocs) {
suggestions.add(autoCompleteReader.document(doc.doc).get(
SOURCE_WORD_FIELD));
}
return suggestions;
}
@SuppressWarnings("unchecked")
public void reIndex(Directory sourceDirectory, String fieldToAutocomplete)
throws CorruptIndexException, IOException {
// build a dictionary (from the spell package)
IndexReader sourceReader = IndexReader.open(sourceDirectory);
LuceneDictionary dict = new LuceneDictionary(sourceReader,
fieldToAutocomplete);
// code from
// org.apache.lucene.search.spell.SpellChecker.indexDictionary(
// Dictionary)
IndexReader.unlock(autoCompleteDirectory);
// use a custom analyzer so we can do EdgeNGramFiltering
IndexWriter writer = new IndexWriter(autoCompleteDirectory,
new Analyzer() {
public TokenStream tokenStream(String fieldName,
Reader reader) {
TokenStream result = new StandardTokenizer(reader);
result = new StandardFilter(result);
result = new LowerCaseFilter(result);
result = new ISOLatin1AccentFilter(result);
result = new StopFilter(result,
ENGLISH_STOP_WORDS);
result = new EdgeNGramTokenFilter(
result, Side.FRONT,1, 20);
return result;
}
}, true);
writer.setMergeFactor(300);
writer.setMaxBufferedDocs(150);
// go through every word, storing the original word (incl. n-grams)
// and the number of times it occurs
Map<String, Integer> wordsMap = new HashMap<String, Integer>();
Iterator<String> iter = (Iterator<String>) dict.getWordsIterator();
while (iter.hasNext()) {
String word = iter.next();
int len = word.length();
if (len < 3) {
continue; // too short we bail but "too long" is fine...
}
if (wordsMap.containsKey(word)) {
throw new IllegalStateException(
"This should never happen in Lucene 2.3.2");
// wordsMap.put(word, wordsMap.get(word) + 1);
} else {
// use the number of documents this word appears in
wordsMap.put(word, sourceReader.docFreq(new Term(
fieldToAutocomplete, word)));
}
}
for (String word : wordsMap.keySet()) {
// ok index the word
Document doc = new Document();
doc.add(new Field(SOURCE_WORD_FIELD, word, Field.Store.YES,
Field.Index.UN_TOKENIZED)); // orig term
doc.add(new Field(GRAMMED_WORDS_FIELD, word, Field.Store.YES,
Field.Index.TOKENIZED)); // grammed
doc.add(new Field(COUNT_FIELD,
Integer.toString(wordsMap.get(word)), Field.Store.NO,
Field.Index.UN_TOKENIZED)); // count
writer.addDocument(doc);
}
sourceReader.close();
// close writer
writer.optimize();
writer.close();
// re-open our reader
reOpenReader();
}
private void reOpenReader() throws CorruptIndexException, IOException {
if (autoCompleteReader == null) {
autoCompleteReader = IndexReader.open(autoCompleteDirectory);
} else {
autoCompleteReader.reopen();
}
autoCompleteSearcher = new IndexSearcher(autoCompleteReader);
}
public static void main(String[] args) throws Exception {
Autocompleter autocomplete = new Autocompleter("/index/autocomplete");
// run this to re-index from the current index, shouldn't need to do
// this very often
// autocomplete.reIndex(FSDirectory.getDirectory("/index/live", null),
// "content");
String term = "steve";
System.out.println(autocomplete.suggestTermsFor(term));
// prints [steve, steven, stevens, stevenson, stevenage]
}
}
</code></pre>
|
Is there an alternative to the SQL Profiler for SQL Server 2000 <p>I am trying to optimize some stored procedures on a SQL Server 2000 database and when I try to use SQL Profiler I get an error message "In order to run a trace against SQL Server you have to be a member of sysadmin fixed server role.". It seems that only members of the sysadmin role can run traces on the server (something that was fixed in SQL Server 2005) and there is no way in hell that I will be granted that server role (company policies)</p>
<p>What I'm doing now is inserting the current time minus the time the procedure started at various stages of the code but I find this very tedious </p>
<p>I was also thinking of replicating the database to a local installation of SQL Server but the stored procedure is using data from many different databases that i will spend a lot of time copying data locally</p>
<p>So I was wondering if there is some other way of profiling SQL code? (Third party tools, different practices, something else )</p>
|
<p>In query analyser:</p>
<pre><code>SET STATISTICS TIME ON
SET STATISTICS IO ON
</code></pre>
<p>Run query and look in the messages tab.</p>
<p>It occurs to me this may require same privileges, but worth a try.</p>
|
Short Integers in Python <p>Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. </p>
<p>So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?</p>
|
<p>Nope. But you can use short integers in arrays:</p>
<pre><code>from array import array
a = array("h") # h = signed short, H = unsigned short
</code></pre>
<p>As long as the value stays in that array it will be a short integer.</p>
<ul>
<li>documentation for the <a href="http://docs.python.org/dev/library/array">array module</a></li>
</ul>
|
Irretrievably destroying data in Java <p>Is there anyway in Java to delete data (e.g., a variable value, object) and be sure it can't be recovered from memory? Does assigning <code>null</code> to a variable in Java delete the value from memory? Any ideas? Answers applicable to other languages are also acceptable.</p>
|
<p>Due to the wonders virtual memory, it is nearly impossible to delete something from memory in a completely irretrievable manner. Your best bet is to zero out the value fields; however: </p>
<ul>
<li>This does not mean that an old (unzeroed) copy of the object won't be left on an unused swap page, which could persist across reboots.</li>
<li>Neither does it stop someone from attaching a debugger to your application and poking around before the object gets zeroed or crashing the VM and poking around in the heap dump.</li>
</ul>
|
Image icon beside the site URL <p>I would like to have information about the icons which are displayed alongside the site URLs on a web browser. Is this some browser specific feature? Where do we specify the icon source, ie, is it in some tag on the web page itself ?</p>
|
<p>These icons are called <a href="http://en.wikipedia.org/wiki/Favicon">favicons</a></p>
<p>Most web browsers support <a href="http://mysite.com/favicon.ico">http://mysite.com/favicon.ico</a> but the proper way to do it is to include an icon meta tag in the head profile.</p>
<pre><code><head profile="http://www.w3.org/2005/10/profile">
<link rel="icon"
type="image/png"
href="/somewhere/myicon.png" />
[â¦]
</head>
</code></pre>
<p><a href="http://www.w3.org/2005/10/howto-favicon">Source from the W3C itself.</a></p>
<p>Your best bet is to probably do both with the same icon image.</p>
|
What is the most convincing way to require formalized unit testing? <p>This certainly presupposes that unit testing is a good thing. Our projects have some level of unit testing, but it's inconsistent at best.</p>
<p>What are the most convincing ways that you have used or have had used with you to convince everyone that formalized unit testing is a good thing and that making it required is really in the best interest of the 'largeish' projects we work on. I am not a developer, but I am in Quality Assurance and would like to improve the quality of the work delivered to ensure it is ready to test.</p>
<p>By formalized unit tests, I'm simply talking about </p>
<ul>
<li>Identifying the Unit Tests to be written</li>
<li>Identifying the test data (or describe it)</li>
<li>Writing these tests</li>
<li>Tracking these tests (and re-using as needed)</li>
<li>Making the results available</li>
</ul>
|
<p>A very convincing way is to do formalized unit test yourself, regardless of what your team/company does. This might take some extra effort on your side, especially if you're not experienced with this sort of practice.</p>
<p>When you can then show your code is better and you are being more productive than your fellow developers, they are going to want to know why. Then feed them your favorite unit testing methods. </p>
<p>Once you've convinced your fellow developers, convince management together. </p>
|
NHibernate nvarchar/ntext truncation problem <p>I'm using nhibernate to store some user settings for an app in a SQL Server Compact Edition table.</p>
<p>This is an excerpt the mapping file:</p>
<pre><code><property name="Name" type="string" />
<property name="Value" type="string" />
</code></pre>
<p>Name is a regular string/nvarchar(50), and Value is set as ntext in the DB</p>
<p>I'm trying to write a large amount of xml to the "Value" property. I get an exception every time:</p>
<pre><code>@p1 : String truncation: max=4000, len=35287, value='<lots of xml..../>'
</code></pre>
<p>I've googled it quite a bit, and tried a number of different mapping configurations:</p>
<pre><code><property name="Name" type="string" />
<property name="Value" type="string" >
<column name="Value" sql-type="StringClob" />
</property>
</code></pre>
<p>That's one example. Other configurations include "ntext" instead of "StringClob". Those configurations that don't throw mapping exceptions still throw the string truncation exception.</p>
<p>Is this a problem ("feature") with SQL CE? Is it possible to put more than 4000 characters into a SQL CE database with nhibernate? If so, can anyone tell me how?</p>
<p>Many thanks!</p>
|
<p>Okay, with many thanks to Artur in <a href="http://groups.google.com/group/nhusers/browse_thread/thread/4f865f0f516234ca" rel="nofollow">this thread</a>, here's the solution:
Inherit from the SqlServerCeDriver with a new one, and override the InitializeParamter method:</p>
<pre><code>using System.Data;
using System.Data.SqlServerCe;
using NHibernate.Driver;
using NHibernate.SqlTypes;
namespace MySqlServerCeDriverNamespace
{
/// <summary>
/// Overridden Nhibernate SQL CE Driver,
/// so that ntext fields are not truncated at 4000 characters
/// </summary>
public class MySqlServerCeDriver : SqlServerCeDriver
{
protected override void InitializeParameter(
IDbDataParameter dbParam,
string name,
SqlType sqlType)
{
base.InitializeParameter(dbParam, name, sqlType);
if (sqlType is StringClobSqlType)
{
var parameter = (SqlCeParameter)dbParam;
parameter.SqlDbType = SqlDbType.NText;
}
}
}
}
</code></pre>
<p>Then, use this driver instead of NHibernate's in your app.config</p>
<pre><code><nhibernateDriver>MySqlServerCeDriverNamespace.MySqlServerCeDriver , MySqlServerCeDriverNamespace</nhibernateDriver>
</code></pre>
<p>I saw a lot of other posts where people had this problem, and solved it by just changing the sql-type attribute to "StringClob" - as attempted in this thread.</p>
<p>I'm not sure why it wouldn't work for me, but I suspect it is the fact that I'm using SQL CE and not some other DB. But, there you have it!</p>
|
How to update components in different threads? .NET CF <p>I´m programming a .NET Compact Framework application which shows maps on a PDA.</p>
<p>I´ve created an ad hoc component that paints it´s own piece of the whole map, using several of this components the big picture is composed. I did it this way to avoid the latency of painting the whole map in a single step.</p>
<p>What I would like to do know is to paint this pieces in their own thread, so the map appears to grow as a single entity and (also, and more important) to avoid freezing the rest of the user interface.</p>
<p>Right know each piece of the map is painted in its onPaint method. My idea is to, somehow, tell the system "execute this code in a thread please".</p>
<p>Something like:</p>
<pre><code>protected override void OnPaint(PaintEventArgs e)
{
// <code to be executed in a thread>
e.Graphics.paintTHis();
e.Graphics.paintThat();
whateverItTakesToPaintThisPieceOfTheMap();
// </code to be executed in a thread>
}
</code></pre>
<p>Do you know how to do this? Or is my approach simply wrong?</p>
<p>Thanks for your time!</p>
|
<p>The approach is wrong. Code that updates the ui has to run on the ui thread. You'll get an exception if you update the ui from another thread.</p>
|
How to check if a trigger is invalid? <p>I'm working on databases that have moving tables auto-generated by some obscure tools. By the way, we have to track information changes in the table via some triggers. And, of course, it occurs that some changes in the table structure broke some triggers, by removing a column or changing its type, for example.</p>
<p>So, the question is: Is there a way to query the Oracle metadata to check is some triggers are broken, in order to send a report to the support team? </p>
<p>The user_triggers give all the triggers and tells if they are enable or not, but does not indicate if they are still valid.</p>
|
<pre><code>SELECT *
FROM ALL_OBJECTS
WHERE OBJECT_NAME = trigger_name
AND OBJECT_TYPE = 'TRIGGER'
AND STATUS <> 'VALID'
</code></pre>
|
Stuck creating a "security trimmed" html.ActionLink extension method <p>I'm trying to create an Extension Method for MVC's htmlHelper.
The purpose is to enable or disable an ActionLink based on the AuthorizeAttribute set on the controller/action.
Borrowing from the <a href="http://blog.maartenballiauw.be/post/2008/08/29/Building-an-ASPNET-MVC-sitemap-provider-with-security-trimming.aspx" rel="nofollow">MVCSitemap</a><br />
code that Maarten Balliauw created, I wanted to validate the user's permissions against the controller/action before deciding how to render the actionlink.
When I try to get the MvcHandler, I get a null value.
Is there a better way to the the attributes for the controller/action?</p>
<p>Here is the code for the extension method:</p>
<pre><code>public static class HtmlHelperExtensions
{
public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller)
{
//simplified for brevity
if (IsAccessibleToUser(action, controller))
{
return htmlHelper.ActionLink(linkText, action,controller);
}
else
{
return String.Format("<span>{0}</span>",linkText);
}
}
public static bool IsAccessibleToUser(string action, string controller)
{
HttpContext context = HttpContext.Current;
MvcHandler handler = context.Handler as MvcHandler;
IController verifyController =
ControllerBuilder
.Current
.GetControllerFactory()
.CreateController(handler.RequestContext, controller);
object[] controllerAttributes = verifyController.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true);
object[] actionAttributes = verifyController.GetType().GetMethod(action).GetCustomAttributes(typeof(AuthorizeAttribute), true);
if (controllerAttributes.Length == 0 && actionAttributes.Length == 0)
return true;
IPrincipal principal = handler.RequestContext.HttpContext.User;
string roles = "";
string users = "";
if (controllerAttributes.Length > 0)
{
AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (actionAttributes.Length > 0)
{
AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)
return true;
string[] roleArray = roles.Split(',');
string[] usersArray = users.Split(',');
foreach (string role in roleArray)
{
if (role != "*" && !principal.IsInRole(role)) return false;
}
foreach (string user in usersArray)
{
if (user != "*" && (principal.Identity.Name == "" || principal.Identity.Name != user)) return false;
}
return true;
}
}
</code></pre>
|
<p>Here is the working code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
using System.Web.Routing;
using System.Web.Mvc;
using System.Collections;
using System.Reflection;
namespace System.Web.Mvc.Html
{
public static class HtmlHelperExtensions
{
public static string SecurityTrimmedActionLink(
this HtmlHelper htmlHelper,
string linkText,
string action,
string controller)
{
return SecurityTrimmedActionLink(htmlHelper, linkText, action, controller, false);
}
public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, bool showDisabled)
{
if (IsAccessibleToUser(action, controller))
{
return htmlHelper.ActionLink(linkText, action, controller);
}
else
{
return showDisabled ? String.Format("<span>{0}</span>", linkText) : "";
}
}
public static bool IsAccessibleToUser(string actionAuthorize, string controllerAuthorize)
{
Assembly assembly = Assembly.GetExecutingAssembly();
GetControllerType(controllerAuthorize);
Type controllerType = GetControllerType(controllerAuthorize);
var controller = (IController)Activator.CreateInstance(controllerType);
ArrayList controllerAttributes = new ArrayList(controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true));
ArrayList actionAttributes = new ArrayList();
MethodInfo[] methods = controller.GetType().GetMethods();
foreach (MethodInfo method in methods)
{
object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true);
if ((attributes.Length == 0 && method.Name == actionAuthorize) || (attributes.Length > 0 && ((ActionNameAttribute)attributes[0]).Name == actionAuthorize))
{
actionAttributes.AddRange(method.GetCustomAttributes(typeof(AuthorizeAttribute), true));
}
}
if (controllerAttributes.Count == 0 && actionAttributes.Count == 0)
return true;
IPrincipal principal = HttpContext.Current.User;
string roles = "";
string users = "";
if (controllerAttributes.Count > 0)
{
AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (actionAttributes.Count > 0)
{
AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)
return true;
string[] roleArray = roles.Split(',');
string[] usersArray = users.Split(',');
foreach (string role in roleArray)
{
if (role == "*" || principal.IsInRole(role))
return true;
}
foreach (string user in usersArray)
{
if (user == "*" && (principal.Identity.Name == user))
return true;
}
return false;
}
public static Type GetControllerType(string controllerName)
{
Assembly assembly = Assembly.GetExecutingAssembly();
foreach (Type type in assembly.GetTypes())
{
if (type.BaseType.Name == "Controller" && (type.Name.ToUpper() == (controllerName.ToUpper() + "Controller".ToUpper())))
{
return type;
}
}
return null;
}
}
}
</code></pre>
<p>I don't like using reflection, but I can't get to the ControllerTypeCache. </p>
|
Good Resource Loading System <p>I'm currently looking for a resource management system for actionscript3. More specifically in this case, I'm looking for opinions on off-the-shelf resource loaders/managers from people who have used them, </p>
<ul>
<li>are they clean/simple to use? </li>
<li>are they designed to be extended?</li>
<li><p>I plan on using this with an MVC like system, Mate is next on the list, has anyone else used a resource loader in this manner?</p></li>
<li><p><a href="http://code.google.com/p/masapi/" rel="nofollow">masapi</a></p></li>
<li><p><a href="http://code.google.com/p/queueloader-as3/" rel="nofollow">queueloader</a></p></li>
<li><p><a href="http://code.google.com/p/bulk-loader/" rel="nofollow">bulk-loader</a></p></li>
</ul>
|
<p>I've been very happy with bulk-loader. We've integrated it with Parsley's MVC and IoC frameworks - <a href="http://spicefactory.org/parsley/" rel="nofollow">http://spicefactory.org/parsley/</a> - with great success.</p>
|
How to do saturating addition in C? <p>What is the best (cleanest, most efficient) way to write saturating addition in C?</p>
<p>The function or macro should add two unsigned inputs (need both 16- and 32-bit versions) and return all-bits-one (0xFFFF or 0xFFFFFFFF) if the sum overflows.</p>
<p>Target is x86 and ARM using gcc (4.1.2) and Visual Studio (for simulation only, so a fallback implementation is OK there).</p>
|
<p>In plain C:</p>
<pre><code>uint16_t sadd16(uint16_t a, uint16_t b)
{ return (a > 0xFFFF - b) ? 0xFFFF : a + b; }
uint32_t sadd32(uint32_t a, uint32_t b)
{ return (a > 0xFFFFFFFF - b) ? 0xFFFFFFFF : a + b;}
</code></pre>
<p>which is almost macro-ized and directly conveys the meaning.</p>
|
How do I detect what browser is used to access my site? <p>How do I detect what browser (IE, Firefox, Opera) the user is accessing my site with? Examples in Javascript, PHP, ASP, Python, JSP, and any others you can think of would be helpful. Is there a language agnostic way to get this information?</p>
|
<p>If it's for handling the request, look at the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43">User-Agent</a> header on the incoming request.</p>
<p>UPDATE: If it's for reporting, configure your web server to log the User-Agent in the access logs, then run a log analysis tool, e.g., <a href="http://awstats.sourceforge.net/">AWStats</a>.</p>
<p>UPDATE 2: FYI, it's <em>usually</em> (not always, usually) a bad idea to change the way you're handling a request based on the User-Agent.</p>
|
Point ADO.Net DataSet to different databases at runtime? <p>I have a large ADO.Net dataset and two database schemas (Oracle) with different constraints. The dataset will work with either schema, but I want to be able to tell the dataset which schema to use (via connection string) at runtime.</p>
<p>Is that even possible?</p>
|
<p>In the .Net 2.0 world, you can change your connection string on your table adapters at run-time. You just have to be sure the Connnection property is public, which can be set from the dataset designer.</p>
|
Is there a good way of securing an ASP.Net web service call made via Javascript on the click event handler of an HTML button? <p>The purpose of using a Javascript proxy for the Web Service using a service reference with Script Manager is to avoid a page load. If the information being retrieved is potentially sensitive, is there a way to secure this web service call other than using SSL? </p>
|
<p>I would use ssl it would also depend I suppose on how sensitive your information is.</p>
|
What's the difference between 'int?' and 'int' in C#? <p>I am 90% sure I saw this answer on stackoverflow before, in fact I had never seen the "int?" syntax before seeing it here, but no matter how I search I can't find the previous post, and it's driving me crazy.</p>
<p>It's possible that I've been eating the funny mushrooms by accident, but if I'm not, can someone please point out the previous post if they can find it or re-explain it? My stackoverflow search-fu is apparently too low....</p>
|
<p>int? is shorthand for <code>Nullable<int></code>.</p>
<p><a href="http://stackoverflow.com/questions/110229/how-do-nullable-types-work-in-c">This</a> may be the post you were looking for.</p>
|
What Exception should be thrown when an ADO.NET query cannot retrieve the requested data? <p>In an attempt to add some parameter validation and correct usage semantics to our application, we are trying to add correct exception handling to our .NET applications.</p>
<p>My question is this: When throwing exceptions in ADO.NET if a particular query returns no data or the data could not be found, what type of exception should I use?</p>
<p>Psuedocode:
(read, don't scrutinize the semantics of the code, I know it won't compile)</p>
<pre><code>public DataSet GetData(int identifier)
{
dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString();
DataSet ds = dataAdapter.Fill(ds);
if (ds.table1.Rows.Count == 0)
throw new Exception("Data not found");
return ds;
}
</code></pre>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms229021(VS.80).aspx" rel="nofollow">MSDN guidelines</a> state:</p>
<ul>
<li><p>Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types.</p></li>
<li><p>Do create and throw custom exceptions if you have an error condition that can be programmatically handled in a different way than any other existing exceptions. Otherwise, throw one of the existing exceptions.</p></li>
<li><p>Do not create and throw new exceptions just to have your team's exception.</p></li>
</ul>
<p>There is no hard and fast rule: but if you have a scenario for treating this exception differently, consider creating a custom exception type, such as DataNotFoundException <a href="http://stackoverflow.com/questions/121700/what-exception-should-be-thrown-when-an-adonet-query-cannot-retrieve-the-reques#121809">as suggested by Johan Buret</a>.</p>
<p>Otherwise you might consider throwing one of the existing exception types, such as System.Data.DataException or possibly even System.Collections.Generic.KeyNotFoundException.</p>
|
Remove Right Click Print Context Menu from Outlook 2007 <p><strong>Is there any way that I can remove the Print item from the context menu when you right-click on an email with VBA?</strong></p>
<p>I am forever right-clicking to reply to an email, only to accidentally click <code>Print</code> and have Outlook send it directly to the printer quicker than I can stop it.</p>
<p><img src="http://farm4.static.flickr.com/3221/2882658372_496d6e7a11_o.jpg" alt="alt text"></p>
<p><strong>NB:</strong> I am using Outlook 2007.</p>
|
<p>Based on the link TcKs provide, that was pretty simple.
In the example below I check the type of the item so that it only affects e-mails and not calendar items.
To enter the code in outlook, Type Alt + F11, then expand the Microsoft Office Outlook Objects in the Project pane. Then double click the ThisOutlookSession. Then paste this code into the code window. I don't like to check captions like this as you can run into issues with internationalization. But I didn't see an ActionID or anything on the Command. There was a FaceID but that is just the id of the printer icon.</p>
<pre class="lang-vb prettyprint-override"><code>Private Sub Application_ItemContextMenuDisplay(ByVal CommandBar As Office.CommandBar, ByVal Selection As Selection)
Dim cmdTemp As Office.CommandBarControl
If Selection.Count > 0 Then
Select Case TypeName(Selection.Item(1))
Case "MailItem"
For Each cmdTemp In CommandBar.Controls
If cmdTemp.Caption = "&Print" Then
cmdTemp.Delete
Exit For
End If
Next cmdTemp
Case Else
'Debug.Print TypeName(Selection.Item(1))
End Select
End If
End Sub
</code></pre>
|
Is there a way to get jadclipse working with Eclipse 3.4? <p>I'm a big fan of the Jadclipse plugin and I'd really like to upgrade to Eclipse 3.4 but the plugin currently does not work. Are there any other programs out there that let you use jad to view source of code you navigate to from Eclipse? (Very useful when delving into ambiguous code in stack traces).</p>
|
<p>Read attentively the documentation ... : </p>
<ol>
<li><p>The JadClipse plug-in is not activated when I start Eclipse.
You'll need to launch Eclipse with the -clean flag to allow the
environment to detect the plug-in. Subsequent launching of
Eclipse won't require the -clean flag.
<strong>eclipse -clean</strong></p></li>
<li><p>The Eclipse Class File Viewer instead of the JadClipse Class File Viewer is
opened. Go to <strong>Window > Preferences... > General > Editors > File Associations</strong>
and make sure that the JadClipse Class File Viewer has the DEFAULT file
association for *.class files. ( - press Default button !!!)</p></li>
</ol>
<p>It really helps :)))</p>
|
Is there an easy way to attach source in Eclipse? <p>I'm a big fan of the way Visual Studio will give you the comment documentation / parameter names when completing code that you have written and ALSO code that you are referencing (various libraries/assemblies).</p>
<p>Is there an easy way to get inline javadoc/parameter names in Eclipse when doing code complete or hovering over methods? Via plugin? Via some setting? It's extremely annoying to use a lot of libraries (as happens often in Java) and then have to go to the website or local javadoc location to lookup information when you have it in the source jars right there!</p>
|
<p>Short answer would be yes.</p>
<p>You can attach source using the properties for a project.</p>
<p>Go to Properties (for the Project) -> Java Build Path -> Libraries</p>
<p>Select the Library you want to attach source/javadoc for and then expand it, you'll see a list like so:</p>
<pre><code>Source Attachment: (none)
Javadoc location: (none)
Native library location: (none)
Access rules: (No restrictions)
</code></pre>
<p>Select Javadoc location and then click Edit on the right hahnd side. It should be quite straight forward from there.</p>
<p>Good luck :)</p>
|
What are reserved filenames for various platforms? <p>I'm not asking about general syntactic rules for file names. I mean gotchas that jump out of nowhere and bite you. For example, trying to name a file "COM<n>" on Windows?</p>
|
<p>From: <a href="http://www.grouplogic.com/knowledge/index.cfm/fuseaction/view_Info/docID/111" rel="nofollow">http://www.grouplogic.com/knowledge/index.cfm/fuseaction/view_Info/docID/111</a>.</p>
<blockquote>
<p>The following characters are invalid as file or folder names on Windows using NTFS: <code>/</code> <code>?</code> <code><</code> <code>></code> <code>\</code> <code>:</code> <code>*</code> <code>|</code> <code>"</code> and any character you can type with the Ctrl key.</p>
<p>In addition to the above illegal characters the caret <code>^</code> is also not permitted under Windows Operating Systems using the FAT file system.</p>
<p>Under Windows using the FAT file system file and folder names may be up to 255 characters long.</p>
<p>Under Windows using the NTFS file system file and folder names may be up to 256 characters long.</p>
<p>Under Window the length of a full path under both systems is 260 characters.</p>
<p>In addition to these characters, the following conventions are also illegal:</p>
<ul>
<li>Placing a space at the end of the name</li>
<li>Placing a period at the end of the name</li>
</ul>
<p>The following file names are also reserved under Windows:</p>
<ul>
<li><code>com1</code>,</li>
<li><code>com2</code>,</li>
<li>...</li>
<li><code>com9</code>,</li>
<li><code>lpt1</code>,</li>
<li><code>lpt2</code>,</li>
<li>...</li>
<li><code>lpt9</code>,</li>
<li><code>con</code>,</li>
<li><code>nul</code>,</li>
<li><code>prn</code></li>
</ul>
</blockquote>
|
What is a simple command line program or script to backup SQL server databases? <p>I've been too lax with performing DB backups on our internal servers. </p>
<p>Is there a simple command line program that I can use to backup certain databases in SQL Server 2005? Or is there a simple VBScript? </p>
|
<p>To backup a single database from the command line, use <a href="http://msdn.microsoft.com/en-us/library/aa214012.aspx">osql</a> or <a href="http://msdn.microsoft.com/en-us/library/ms162773.aspx">sqlcmd</a>.</p>
<pre><code>"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\osql.exe"
-E -Q "BACKUP DATABASE mydatabase TO DISK='C:\tmp\db.bak' WITH FORMAT"
</code></pre>
<p>You'll also want to read the documentation on <a href="http://msdn.microsoft.com/en-us/library/aa225964%28SQL.80%29.aspx">BACKUP</a> and <a href="http://msdn.microsoft.com/en-us/library/aa238405%28SQL.80%29.aspx">RESTORE</a> and <a href="http://msdn.microsoft.com/en-us/library/aa176762%28SQL.80%29.aspx">general procedures</a>.</p>
|
How to line up items of varied length in a resizable space in CSS? <p>I'd like to line up items approximately like this:</p>
<pre><code>item1 item2 i3 longitemname
i4 longitemname2 anotheritem i5
</code></pre>
<p>Basically items of varying length arranged in a table like structure. The tricky part is the container for these can vary in size and I'd like to fit as many as I can in each row - in other words, I won't know beforehand how many items fit in a line, and if the page is resized the items should re-flow themselves to accommodate. E.g. initially 10 items could fit on each line, but on resize it could be reduced to 5.</p>
<p>I don't think I can use an html table since I don't know the number of columns (since I don't know how many will fit on a line). I can use css to float them, but since they're of varying size they won't line up.</p>
<p>So far the only thing I can think of is to use javascript to get the size of largest item, set the size of all items to that size, and float everything left.</p>
<p>Any better suggestions?</p>
|
<p>This can be done using floated div's, calculating the max width, and setting all widths to the max. Here's jquery code to do it:</p>
<p>html:</p>
<pre><code><div class="item">something</div>
<div class="item">something else</div>
</code></pre>
<p>css:</p>
<pre><code>div.item { float: left; }
</code></pre>
<p>jquery:</p>
<pre><code>var max_width=0;
$('div.item').each( function() { if ($(this).width() > max_width) { max_width=$(this).width(); } } ).width(max_width);
</code></pre>
<p>Not too ugly but not too pretty either, I'm still open to better suggestions...</p>
|
how to determine if a record in every source, represents the same person <p>I have several sources of tables with personal data, like this:</p>
<pre><code>SOURCE 1
ID, FIRST_NAME, LAST_NAME, FIELD1, ...
1, jhon, gates ...
SOURCE 2
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
1, jon, gate ...
SOURCE 3
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
2, jhon, ballmer ...
</code></pre>
<p>So, assuming that records with ID 1, from sources 1 and 2, are the same person, my problem <strong>is how to determine if a record in every source, represents the same person</strong>. Additionally, sure not every records exists in all sources. All the names, are written in spanish, mainly.</p>
<p>In this case, the exact matching needs to be relaxed because we assume <em>the data sources has not been rigurously checked</em> against the official bureau of identification of the country. Also we need to assume <em>typos are common</em>, because the nature of the processes to collect the data. What is more, the amount of records is around 2 or 3 millions in every source...</p>
<p>Our team had thought in something like this: first, force exact matching in selected fields like ID NUMBER, and NAMES to know how hard the problem can be. Second, relaxing the matching criteria, and count how much records more can be matched, but is here where the problem arises: <strong>how to do to relax the matching criteria without generating too noise neither restricting too much?</strong></p>
<p>What tool can be more effective to handle this?, for example, do you know about some especific extension in some database engine to support this matching?
Do you know about clever algorithms like <a href="http://en.wikipedia.org/wiki/Soundex" rel="nofollow">soundex</a> to handle this approximate matching, but for spanish texts?</p>
<p>Any help would be appreciated!</p>
<p>Thanks.</p>
|
<p>This sounds like a <a href="http://en.wikipedia.org/wiki/Customer_Data_Integration" rel="nofollow">Customer Data Integration</a> problem. Search on that term and you might find some more information. Also, have a poke around inside <a href="http://www.tdwi.org/" rel="nofollow">The Data Warehousing Institude</a>, and you might find some answers there as well.</p>
<p><strong>Edit:</strong> In addition, <a href="http://www.javalobby.org/java/forums/t16936.html" rel="nofollow">here's</a> an article that might interest you on spanish phonetic matching.</p>
|
opening links in the same window or in a new (tab) <p>It has always been best practice to open links in the same window. Should that still be the rule now that most common browsers use tabs? Personally i prefer closing a tab/window over hitting the backbutton. What are your thoughts?</p>
|
<p>If you prefer closing a tab/window over hitting the back button, then by all means, click links with your middle mouse button. But please don't force your surfing preferences on others. Tabs don't change this principle in the slightest.</p>
|
Naming a "core" Assembly <p>I know that this is somewhat subjective, but I wonder if there is a generally accepted standard for naming assemblies which contain some "core" functions.</p>
<p>Let's say you got a larger Projects, with Assemblies like</p>
<ul>
<li>Company.Product.WebControls.dll</li>
<li>Company.Product.Net.dll</li>
<li>Company.Product.UserPages.dll</li>
</ul>
<p>and you have a Bunch of "Core" classes, like the Global Error Handler, the global Logging functionality etc.</p>
<p>How would such an assembly generally named? Here are some things I had in mind:</p>
<ul>
<li>Company.Product.dll</li>
<li>Company.Product.Core.dll</li>
<li>Company.Product.Global.dll</li>
<li>Company.Product.Administration.dll</li>
</ul>
<p>Now, while "just pick one and go on" will not cause Armageddon, I'd still like to know if there is an "accepted" way to name those assemblies.</p>
|
<p>All these "root", "core", "common" and so on are really <strong>bad naming-conventions</strong>.</p>
<p>Common stuff should lie in the root namespace, like in .NET, <code>string</code>, <code>int</code> and other things that are "core" or "common" lies in the root <code>System</code>-namespace.</p>
<p><strong>Don't use namespaces to more easily collapse your folders in Visual Studio</strong>, but structure it after <strong>what it contains and what it's used for</strong>.</p>
<p><code>System.Security</code> contains common security-things that, for example <code>System.Xml</code> doesn't need to know about, unless you want that functionality explicitly.</p>
<p><code>System.Security.Cryptography</code>is a sub-namespace. Cryptography is security, but <strong>security is not explicitly cryptography</strong>.</p>
<p>In this way <code>System.Security.Cryptography</code> has <strong>full insight into it's parent namespace</strong> and can <strong>implictly use all classes inside</strong> of its parent.</p>
<p>I would say <code>System.Core.dll</code> was a <strong>slip-up on Microsoft's side</strong>. They must have ran out of ideas or DLL-names.</p>
<p><strong>Update</strong>: MSDN has a somewhat updated <a href="http://msdn.microsoft.com/en-us/library/ms973231.aspx#assenamesp_topic5" rel="nofollow">article that tries to explain Microsoft's thinking on the subject</a>.</p>
|
Code analysis <p>Does anyone know where to find an explanation to the warnings in vs 2005 codeanalysis tool. I would like some documentation, explainning why it creates the warnings it does and what course of action one should take.</p>
|
<p>You should be able to right click the warnings it gives you in the Error List and view Error Help, right from within Visual Studio. There's also a <a href="http://msdn.microsoft.com/en-us/library/ee1hzekz(VS.80).aspx" rel="nofollow">section of MSDN articles</a>, if you'd prefer.</p>
|
Installing TFS 2008 Workgroup Edition on Windows Server 2003 with SQL Server 2008 <p>I ran into an issue when installing Team Foundation Server 2008 Workgroup Edition. I have a Windows Server 2003 SP2 machine that's practically new. I have installed SQL Server 2008 with almost all of the options. When I run through the TFS installation, it allows me to enter my SQL instance name and then goes through the verification process to ensure I have everything I need. However, I receive an error stating that </p>
<blockquote>
<p>A compatible version of SQL Server is not installed. </p>
</blockquote>
<p>I verified and I do have SQL Server 2008 running just fine. It's Standard edition and does have Full Text, Reporting, and Analysis services installed. The other errors I receive are with Full Text not being installed, running, or enabled.</p>
<p>Any help is appreciated.</p>
|
<p>To install Team Foundation Server 2008 against SQL Server 2008, you must use TFS 2008 Service Pack 1. However, currently Microsoft do not provide a "TFS with SP1" download - you must created your own slipstreamed installation by downloading the TFS 2008 media and then applying the service pack to the media before running the installer.</p>
<p>For more information see my blog post here</p>
<p><a href="http://www.woodwardweb.com/vsts/creating_a_tfs.html" rel="nofollow">http://www.woodwardweb.com/vsts/creating_a_tfs.html</a></p>
<p>Also note that TFS needs certain settings for its SQL Server. When installing a SQL instance for TFS I usually follow the guidance in the TFS Installation Guide pretty ridgedly just to be sure I have everything set up right. You can download the latest copy of the TFS install guide here</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=FF12844F-398C-4FE9-8B0D-9E84181D9923&displaylang=en" rel="nofollow">http://www.microsoft.com/downloads/details.aspx?FamilyID=FF12844F-398C-4FE9-8B0D-9E84181D9923&displaylang=en</a></p>
<p>Good luck,</p>
<p>Martin.</p>
|
Zabbix: is it possible to monitor arbitrary string variable? <p>We are using Zabbix for services monitoring.</p>
<p>There are some essential monitoring configured.
I want to have timeline of version strings of my service along with this monitorings. That would give me opportunity to see that upgrading to this version altered overall error-count.</p>
<p>Is it possible? </p>
|
<p>Yes, it's possible.</p>
<p>You can pass arbitrary data from your Zabbix agent to the Zabbix server by using "UserParameter" fields in zabbix_server.conf, i.e. agent configuration file. </p>
<p>General syntax is:</p>
<blockquote>
<p>UserParameter=section[id], command</p>
</blockquote>
<p>For example, let's assume you want to monitor how many users are logged in. You would use:</p>
<blockquote>
<p>UserParameter=sys[num_users], who | wc -l</p>
</blockquote>
<p>(I assume you know how to configure the Zabbix server to receive this data, it's pretty straightforward - just create a new item, bind it to a template and connect a template to a server or server group).</p>
<p>If you want to monitor some file for a specific string, just use grep, sed, cut, tr and other standard Unix tools. If you need more complex things, just write a shell script.</p>
|
Modifying Existing .NET Assemblies <p>Is there a way to modify existing .NET assemblies without resorting to 3rd party tools? I know that <a href="http://www.postsharp.org/">PostSharp</a> makes this possible but I find it incredibly wasteful that the developler of PostSharp basically had to rewrite the functionality of the whole <code>System.Reflection</code> namespace in order to make existing assemblies modifiable.</p>
<p><code>System.Reflection.Emit</code> only allows the creation of new, dynamic assemblies. However, all the builder classes used here inherit from the basic reflection classes (e.g. <code>TypeBuilder</code> inherits from <code>System.Type</code>). Unfortunately, there doesn't seem to be a way to coerce an existing, dynamically loaded type into a type builder. At least, there's no official, supported way.</p>
<p>So what about unsupported? Does anyone know of backdoors that allow to load existing assemblies or types into such builder classes?</p>
<p>Mind, I am <strong>not</strong> searching for ways to modify the current assembly (this <em>may</em> even be an unreasonable request) but just to modify existing assemblies loaded from disc. I fear there's no such thing but I'd like to ask anyway.</p>
<p>In the worst case, one would have to resort to <code>ildasm.exe</code> to disassemble the code and then to <code>ilasm.exe</code> for reassembly but there's no toolchain (read: IL reader) contained in .NET to work with IL data (or is there?).</p>
<p>/EDIT:</p>
<p>I've got no specific use case. I'm just interested in a general-purpose solution because patching existing assemblies is a quite common task. Take obfuscators for example, or profilers, or AOP libraries (yes, the latter <em>can</em> be implemented differently). As I've said, it seems incredibly wasteful to be forced to rewrite large parts of the already existing infrastructure in <code>System.Reflection</code>.</p>
<hr>
<h2>@Wedge:</h2>
<p>You're right. However, there's no specific use case here. I've modified the original question to reflect this. My interest was sparked by another question where the asker wanted to know how he could inject the instructions <code>pop</code> and <code>ret</code> at the end of every method in order to keep Lutz Roeder's Reflector from reengineering the (VB or C#) source code.</p>
<p>Now, this scenario can be realized with a number of tools, e.g. PostSharp mentioned above and the <a href="http://sebastien.lebreton.free.fr/reflexil/">Reflexil</a> plugin for Reflector, that, in turn, uses the <a href="http://www.mono-project.com/Cecil">Cecil</a> library.</p>
<p>All in all, I'm just not satisfied with the .NET framework.</p>
<h2>@Joel:</h2>
<p>Yes, I'm aware of this limitation. Thanks anyway for pointing it out, since it's important.</p>
<h2>@marxidad:</h2>
<p>This seems like the only feasible approach. However, this would mean that you'd still have to recreate the complete assembly using the builder classes, right? I.e. you'd have to walk over the whole assembly manually.</p>
<p>Hmm, I'll look into that.</p>
|
<p>Mono.Cecil also allows you to remove the strong name from a given assembly and save it back as an unsigned assembly. Once you remove the strong name from the assembly, you can just modify the IL of your target method and use the assembly as you would any other assembly. Here's the link for removing the strong name with Cecil:</p>
<p><a href="http://groups.google.com/group/mono-cecil/browse_thread/thread/3cc4ac0038c99380/b8ee62b03b56715d?lnk=gst&q=strong+named#b8ee62b03b56715d">http://groups.google.com/group/mono-cecil/browse_thread/thread/3cc4ac0038c99380/b8ee62b03b56715d?lnk=gst&q=strong+named#b8ee62b03b56715d</a></p>
<p>Once you've removed the strong name, you can pretty much do whatever you want with the assembly. Enjoy!</p>
|
What CLR/.NET bytecode tools exist? <p>I'm well aware of Java tools for manipulating, generating, decompiling JVM bytecode (ASM, cglib, jad, etc). What similar tools exist for the CLR bytecode? Do people do bytecode manipulation for the CLR? </p>
|
<p>Reflector is always good, but Mono.Cecil is the best tool you can possibly ask for overall. It's invaluable for manipulating CIL in any way.</p>
|
Ways to do "related searches" functionality <p>I've seen a few sites that list related searches when you perform a search, namely they suggest other search queries you may be interested in.</p>
<p>I'm wondering the best way to model this in a medium-sized site (not enough traffic to rely on visitor stats to infer relationships). My initial thought is to store the top 10 results for each unique query, then when a new search is performed to find all the historical searches that match some amount of the top 10 results but ideally not matching all of them (matching all of them might suggest an equivalent search and hence not that useful as a suggestion).</p>
<p>I imagine that some people have done this functionality before and may be able to provide some ideas of different ways to do this. I'm not necessarily looking for one winning idea since the solution will no doubt vary substantially depending on the size and nature of the site.</p>
|
<p>I've tried a number of different approaches to this, with various degrees of success. In the end, I think the best approach is highly dependent on the domain/topics being searched, and how the users form queries.</p>
<p>Your thought about storing previous searches seems reasonable to me. I'd be curious to see how it works in practice (I mean that in the most sincere way -- there are many nuances that can cause these techniques to fail in the "real world", particularly when data is sparse). </p>
<p>Here are some techniques I've used in the past, and seen in the literature:</p>
<ol>
<li>Thesaurus based approaches: Index into a thesaurus for each term that the user has used, and then use some heuristic to filter the synonyms to show the user as possible search terms.</li>
<li>Stem and search on that: Stem the search terms (eg: with the <a href="http://tartarus.org/~martin/PorterStemmer/" rel="nofollow">Porter Stemming Algorithm</a> and then use the stemmed terms instead of the initially provided queries, and given the user the option of searching for <em>exactly</em> the terms they specified (or do the opposite, search the exact terms first, and use stemming to find the terms that stem to the same root. This second approach obviously takes some pre-processing of a known dictionary, or you can collect terms as your indexing term finds them.)</li>
<li>Chaining: Parse the results found by the user's query and extract key terms from the top N results (<a href="http://www.nzdl.org/Kea/" rel="nofollow">KEA</a> is one library/algorithm that you can look at for keyword extraction techniques.)</li>
</ol>
|
Automatic newlines and formatting for blogging software <p>I'm writing by own blogging engine in PHP with a MYSQL backend database. MY question is: How would you go about making user comments and blog posts include newlines wherever they are appropriate?</p>
<p>For example, if a user hits the return key in the message/comments box how would this translate into a new line that would show in the browser when the comment is viewed?</p>
|
<p>PHP has a function: nl2br which turns new lines into <code><br /></code></p>
<p><a href="http://us2.php.net/nl2br" rel="nofollow">www.php.net/nl2br</a></p>
|
Is MEF a replacement for System.Addin? <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/835182/choosing-between-mef-and-maf-system-addin">Choosing between MEF and MAF (System.AddIn)</a> </p>
</blockquote>
<p>Is the Managed Extensibility Framework a replacement for System.Addin? Or are they complementary?</p>
|
<p>Short answer no it is not. System.Addin allows you to isolate add-ins in to a seprate app-domain / process. It also provides facilities for versioning. These capabilities are critical for many customers particularly large ISVs. MEF on the other hand is designed to be simple programming model for extensibility. The two can work together and complement each other.</p>
|
A Delphi/FreePascal lib or function that emulates the PHP's function parse_url <p>I'm doing a sitemap producer in Object Pascal and need a good function or lib to emulate the <a href="http://php.net/manual/en/function.parse-url.php" rel="nofollow">parse_url</a> function on PHP.</p>
<p>Does anyone know of any good ones?</p>
|
<p>I am not familiar with the parse_url function on PHP, but you might try the <a href="http://www.indyproject.org/docsite/html/TIdURI.html" rel="nofollow" title="Online documentation for TIdURI class">TIdURI</a> class that is included with <a href="http://www.indyproject.org/" rel="nofollow" title="Indy Project home page.">Indy</a> (which in turn is included with most recent Delphi releases). I think they ported it to FreePascal as well.</p>
<blockquote>
<p>TIdURI is a TObject descendant that encapsulates a Universal Resource Identifier, as described in the Internet Standards document: </p>
<blockquote>
<p><a href="http://www.rfc-editor.org/rfc/rfc1630.txt" rel="nofollow">RFC 1630 - Universal Resource Identifiers in WWW</a> </p>
</blockquote>
<p>TIdURI provides methods and properties for assembly and disassembly of URIs using the component parts that make up the URI, including: Protocol, Host, Port, Path, Document, and Bookmark.</p>
</blockquote>
<p>If that does not work, please give a specific example of what you are trying to accomplish - <em>what are you trying to parse out of a URL</em>.</p>
|
Best Practices of Test Driven Development Using C# and RhinoMocks <p>In order to help my team write testable code, I came up with this simple list of best practices for making our C# code base more testable. (Some of the points refer to limitations of Rhino Mocks, a mocking framework for C#, but the rules may apply more generally as well.) Does anyone have any best practices that they follow?</p>
<p>To maximize the testability of code, follow these rules:</p>
<ol>
<li><p><strong>Write the test first, then the code.</strong> Reason: This ensures that you write testable code and that every line of code gets tests written for it.</p></li>
<li><p><strong>Design classes using dependency injection.</strong> Reason: You cannot mock or test what cannot be seen.</p></li>
<li><p><strong>Separate UI code from its behavior using Model-View-Controller or Model-View-Presenter.</strong> Reason: Allows the business logic to be tested while the parts that can't be tested (the UI) is minimized.</p></li>
<li><p><strong>Do not write static methods or classes.</strong> Reason: Static methods are difficult or impossible to isolate and Rhino Mocks is unable to mock them.</p></li>
<li><p><strong>Program off interfaces, not classes.</strong> Reason: Using interfaces clarifies the relationships between objects. An interface should define a service that an object needs from its environment. Also, interfaces can be easily mocked using Rhino Mocks and other mocking frameworks.</p></li>
<li><p><strong>Isolate external dependencies.</strong> Reason: Unresolved external dependencies cannot be tested.</p></li>
<li><p><strong>Mark as virtual the methods you intend to mock.</strong> Reason: Rhino Mocks is unable to mock non-virtual methods.</p></li>
</ol>
|
<p>Definitely a good list. Here are a few thoughts on it:</p>
<blockquote>
<p><strong>Write the test first, then the code.</strong></p>
</blockquote>
<p>I agree, at a high level. But, I'd be more specific: "Write a test first, then write <em>just enough</em> code to pass the test, and repeat." Otherwise, I'd be afraid that my unit tests would look more like integration or acceptance tests.</p>
<blockquote>
<p><strong>Design classes using dependency injection.</strong></p>
</blockquote>
<p>Agreed. When an object creates its own dependencies, you have no control over them. Inversion of Control / Dependency Injection gives you that control, allowing you to isolate the object under test with mocks/stubs/etc. This is how you test objects in isolation.</p>
<blockquote>
<p><strong>Separate UI code from its behavior using Model-View-Controller or Model-View-Presenter.</strong></p>
</blockquote>
<p>Agreed. Note that even the presenter/controller can be tested using DI/IoC, by handing it a stubbed/mocked view and model. Check out <a href="http://www.atomicobject.com/pages/Presenter+First">Presenter First</a> TDD for more on that.</p>
<blockquote>
<p><strong>Do not write static methods or classes.</strong></p>
</blockquote>
<p>Not sure I agree with this one. It is possible to unit test a static method/class without using mocks. So, perhaps this is one of those Rhino Mock specific rules you mentioned.</p>
<blockquote>
<p><strong>Program off interfaces, not classes.</strong> </p>
</blockquote>
<p>I agree, but for a slightly different reason. Interfaces provide a great deal of flexibility to the software developer - beyond just support for various mock object frameworks. For example, it is not possible to support DI properly without interfaces. </p>
<blockquote>
<p><strong>Isolate external dependencies.</strong> </p>
</blockquote>
<p>Agreed. Hide external dependencies behind your own facade or adapter (as appropriate) with an interface. This will allow you to isolate your software from the external dependency, be it a web service, a queue, a database or something else. This is <em>especially</em> important when your team doesn't control the dependency (a.k.a. external).</p>
<blockquote>
<p><strong>Mark as virtual the methods you intend to mock.</strong> </p>
</blockquote>
<p>That's a limitation of Rhino Mocks. In an environment that prefers hand coded stubs over a mock object framework, that wouldn't be necessary.</p>
<p>And, a couple of new points to consider:</p>
<p><strong>Use creational design patterns.</strong> This will assist with DI, but it also allows you to isolate that code and test it independently of other logic.</p>
<p><strong>Write tests using <a href="http://weblogs.java.net/blog/wwake/archive/2003/12/tools_especiall.html">Bill Wake's Arrange/Act/Assert technique</a>.</strong> This technique makes it very clear what configuration is necessary, what is actually being tested, and what is expected.</p>
<p><strong>Don't be afraid to roll your own mocks/stubs.</strong> Often, you'll find that using mock object frameworks makes your tests incredibly hard to read. By rolling your own, you'll have complete control over your mocks/stubs, and you'll be able to keep your tests readable. (Refer back to previous point.)</p>
<p><strong>Avoid the temptation to refactor duplication out of your unit tests into abstract base classes, or setup/teardown methods.</strong> Doing so hides configuration/clean-up code from the developer trying to grok the unit test. In this case, the clarity of each individual test is more important than refactoring out duplication.</p>
<p><strong>Implement Continuous Integration.</strong> Check-in your code on every "green bar." Build your software and run your full suite of unit tests on every check-in. (Sure, this isn't a coding practice, per se; but it is an incredible tool for keeping your software clean and fully integrated.)</p>
|
Mysql results in PHP - arrays or objects? <p>Been using <strong>PHP/MySQL</strong> for a little while now, and I'm wondering if there are any specific advantages (performance or otherwise) to using <code>mysql_fetch_object()</code> vs <code>mysql_fetch_assoc()</code> / <code>mysql_fetch_array()</code>.</p>
|
<p>Performance-wise it doesn't matter what you use. The difference is that mysql_fetch_object returns object:</p>
<pre><code>while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
</code></pre>
<p>mysql_fetch_assoc() returns associative array:</p>
<pre><code>while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
}
</code></pre>
<p>and mysql_fetch_array() returns array:</p>
<pre><code>while ($row = mysql_fetch_array($result)) {
echo $row[0];
echo $row[1] ;
}
</code></pre>
|
How to do a rolling restart of a cluster of mongrels <p>Anybody know a nice way to restart a mongrel cluster via capistrano in a "rolling" style, eg, one mongrel at a time. Would be great to have a bit of wait time in there as well for each, to let the mongrel load the rails app up as well. </p>
<p>I've done some searching, and haven't found too much, so looking for help before I dive into the mongrel_cluster gem myself.</p>
<p>Thanks!</p>
|
<p>I agree with the seesaw approach more than the rolling approach you are seeking. The problem is that you end up in situations where load balancing can throw users back and forth between different versions of the application while you are transitioning.</p>
<p>The solutions we came up with (before finding SeeSaw, which we don't use) was to take half of the mongrels off line from the load balancer. Shut them down. Update them. Start them up. Put those mongrels back online in the load balancer and take the other half off. Shut the second half down. Update the second half. Start them up. This greatly minimizes the time where you have two different versions of the application running simultaneously.
I wrote a windows bat file to do this. (Deploying on Windows is not recommended, btw)</p>
<p>It is very important to note that having database migrations can make the whole approach a little dangerous. If you have only additive migrations, you can run those at any time before the deployment. If you are removing columns, you need to do it after the deployment. If you are renaming columns, it is better to split it into a create a new column and copy data into it migration to run before deployment and a separate script to remove the old column after deployment. In fact, it may be dangerous to use your regular migrations on a production database in general if you don't make a specific effort to organize them. All of this points to making more frequent deliveries so each update is lower risk and less complex, but that's a subject for another response. </p>
|
Is there any way to use XmlSiteMapProvider within WinForm/Console/VSTest application? <p>I wonder whether there is a workaround for using the standard XmlSiteMapProvider within a non asp.net application, like WinForm/Console or, in my case, VS Unit Test one.</p>
<p>The following code fails, because it cannot create a path to the <code>.sitemap</code> file inside a private <code>GetConfigDocument</code> method.</p>
<pre><code>XmlSiteMapProvider provider = new XmlSiteMapProvider();
NameValueCollection providerAttributes = new NameValueCollection();
providerAttributes.Add("siteMapFile", "Web.sitemap");
provider.Initialize("XmlSiteMapReader", providerAttributes);
provider.BuildSiteMap();
</code></pre>
<p>I feel the right solution is to write another provider.</p>
|
<p>I do not see why not. It is just a provider that implements an interface. You may not need many of the features, but you can access the API for what it provides you. Your WinForms screens can simply use the Urls for identification so that you can determine your place in the hierarchy.</p>
<p>What you may have to do is create a custom implementation of the provider because it will use the HttpContext to get the Url of the current web request to identify current placement while you will need to get that value differently. That is what could be tricky because your WinForm application could be displaying multiple windows at time. If you know there is only one window showing at a time you could use a static value which is set prior to accessing the SiteMap API.</p>
<p>Now you have to question the value of using an API if you have to do all of the work. There may not be enough benefit to make it worthwhile.</p>
|
What is the best way to run asynchronous jobs in a Rails application? <p>I know there are several plugins that do asynchronous processing. Which one is the best one and why?</p>
<p>The ones I know about are:</p>
<ul>
<li><a href="http://backgroundrb.rubyforge.org/">BackgrounDRb</a></li>
</ul>
|
<p>I'll add DJ (Delayed Job) to the list - <a href="http://blog.leetsoft.com/2008/2/17/delayed-job-dj">http://blog.leetsoft.com/2008/2/17/delayed-job-dj</a></p>
<p>The github guys recently gave it a great review: <a href="http://github.com/blog/197-the-new-queue">http://github.com/blog/197-the-new-queue</a></p>
|
WPF Diagramming Library <p>What free or open source WPF diagramming libraries have you used before? I'm working on my thesis and have no money to pay for the commercial alternatives.</p>
<p>Valid answers should support undo/redo, exporting to XML and hopefully good documentation.</p>
<p>I'm building an open source UML / database diagramming tool.</p>
<p>Thanks.</p>
|
<p>sukram has a excellent series on CodeProject... it's a MUST READ!</p>
<ul>
<li><a href="http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part1.aspx">Part 1</a></li>
<li><a href="http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part2.aspx">Part 2</a></li>
<li><a href="http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part3.aspx">Part 3</a></li>
<li><a href="http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part4.aspx">Part 4</a></li>
</ul>
|
Turn an array of pixels into an Image object with Java's ImageIO? <p>I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code:</p>
<pre><code>public Image getImageFromArray(int[] pixels, int width, int height) {
MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width);
Toolkit tk = Toolkit.getDefaultToolkit();
return tk.createImage(mis);
}
</code></pre>
<p><em>Is it possible to achieve the same result using classes from the ImageIO package(s) so I don't have to use the AWT Toolkit?</em></p>
<p>Toolkit.getDefaultToolkit() does not seem to be 100% reliable and will sometimes throw an AWTError, whereas the ImageIO classes should always be available, which is why I'm interested in changing my method.</p>
|
<p>You can create the image without using ImageIO. Just create a BufferedImage using an image type matching the contents of the pixel array.</p>
<pre><code>public static Image getImageFromArray(int[] pixels, int width, int height) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
WritableRaster raster = (WritableRaster) image.getData();
raster.setPixels(0,0,width,height,pixels);
return image;
}
</code></pre>
<p>When working with the PixelGrabber, don't forget to extract the RGBA info from the pixel array before calling <code>getImageFromArray</code>. There's an example of this in the <a href="http://java.sun.com/javase/6/docs/api/java/awt/image/PixelGrabber.html">handlepixelmethod</a> in the PixelGrabber javadoc. Once you do that, make sure the image type in the BufferedImage constructor to <code>BufferedImage.TYPE_INT_ARGB</code>. </p>
|
Have you integrated Mantis and Subversion? <p>I do mostly Windows development. We use <a href="http://www.mantisbt.org/">Mantis</a> and <a href="http://subversion.tigris.org/">Subversion</a> for our development but they aren't integrated together, in fact they are on different servers.</p>
<p>I did a little googling about integrating the two together and came across <a href="http://alt-tag.com/blog/archives/2006/11/integrating-mantis-and-subversion/">this post</a>. It looked interesting.</p>
<p>I was wondering if anyone is doing this or has done this and what your experience has been. If you've got a different solution, I'd be interested in knowing that too!</p>
<p>Thanks!</p>
|
<p>I use Mantis with SVN. Pretty much as that link says, though I put the regexp in the post-commit so it doesn't try to update the bug if the commit message is not relevant, that makes non-bug-updating commits respond slightly faster.</p>
<p>My Mantis install is on a different server too. I use <a href="http://curl.haxx.se/">curl</a> to <a href="http://www.mantisbt.org/bugs/view.php?id=8847">call the php</a> method in Mantis 1.1.6.</p>
<p>Put this in your post-commit.cmd hook (you'll need to download <a href="http://strawberryperl.com/">strawberry perl</a> and grab perl.exe and perl510.dll from it, you don't need the rest)</p>
<pre><code>c:\tools\perl c:\tools\mantis_urlencode.pl %1 %2 > c:\temp\postcommit_mantis.txt
if %ERRORLEVEL% NEQ 0 exit /b 0
c:\tools\curl -s -d user=svn -d @c:\temp\postcommit_mantis.txt http://swi-sgi-l-web1.ingrnet.com/mantis/core/checkincurl.php
</code></pre>
<p>and put this in mantis_urlencode.pl</p>
<pre><code>$url = `svnlook log -r $ARGV[1] $ARGV[0]`;
# check the string contains the matching regexp,
# quit if it doesn't so we don't waste time contacting the webserver
# this is the g_source_control_regexp value in mantis.
exit 1 if not $url =~ /\b(?:bug|issue|mantis)\s*[#]{0,1}(\d+)\b/i;
$url = $url . "\n" . `svnlook dirs-changed -r $ARGV[1] $ARGV[0]`;
#urlencode the string
$url =~ s/([^\w\-\.\@])/$1 eq " "?"+": sprintf("%%%2.2x",ord($1))/eg;
print "log=$url";
exit 0;
</code></pre>
<p>If you want to migrate from VSS, there are a load of scripts, including one I wrote on <a href="http://vss2svn.codeplex.com/Wiki/View.aspx">codeplex</a>.</p>
<p>It all works well, we use it all the time, and its quick enough not to notice its there. Just type "Fixed Mantis #1234" and it resolves the bug and adds a bugnote to it. The script also adds the directories that were modified to the bugnote too (I tried showing changed files but too many detract from easy understanding)</p>
|
What do you use to deploy your Web Applications? <p>We're looking to automate our deployment of Web Applications, particularly when going from local development to a remote server.</p>
<p>Our current stack is LAMP remotely, MAMP locally, but I'm interested in general what people are using for this task regardless of their environment?</p>
<p>I'm not just talking about moving files around, I also meant considering other tasks such as:</p>
<ul>
<li>Setting up Database schema</li>
<li>Managing configurations</li>
<li>Misc tasks required for deployment (creating log files etc.)</li>
</ul>
|
<p>When and where possible, <strong>I prefer an automated deployment</strong> such as with Ant, even FTP deployment can be fairly easily handled. Automating the deployment, much like an automated build, takes the guess work and error out of the process and by definition provides at least the bare minimum documentation necessary (i.e. the build script) for a new programmer to understand the process.</p>
|
Is it possible to prevent stack allocation of an object and only allow it to be instantiated with 'new'? <p>Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?</p>
|
<p>One way you could do this would be to make the constructors private and only allow construction through a static method that returns a pointer. For example:</p>
<pre><code>class Foo
{
public:
~Foo();
static Foo* createFoo()
{
return new Foo();
}
private:
Foo();
Foo(const Foo&);
Foo& operator=(const Foo&);
};
</code></pre>
|
What's the difference between Polymorphism and Multiple Dispatch? <p>...or are they the same thing? I notice that each has its own Wikipedia entry: <a href="http://en.wikipedia.org/wiki/Polymorphism_(computer_science)">[1]</a> <a href="http://en.wikipedia.org/wiki/Multiple_dispatch">[2]</a>, but I'm having trouble seeing how the concepts differ.</p>
<p><strong>Edit:</strong> And how does <a href="http://en.wikipedia.org/wiki/Overloaded">Overloading</a> fit into all this?</p>
|
<p>Polymorphism is the facility that allows a language/program to make decisions during runtime on which method to invoke based on the types of the parameters sent to that method. </p>
<p>The number of parameters used by the language/runtime determines the 'type' of polymorphism supported by a language. </p>
<p>Single dispatch is a type of polymorphism where only one parameter is used (the receiver of the message - <code>this</code>, or <code>self</code>) to determine the call.</p>
<p>Multiple dispatch is a type of polymorphism where in multiple parameters are used in determining which method to call. In this case, the reciever as well as the types of the method parameters are used to tell which method to invoke.</p>
<p>So you can say that polymorphism is the general term and multiple and single dispatch are specific types of polymorphism.</p>
<p>Addendum: Overloading happens during compile time. It uses the type information available during compilation to determine which type of method to call. Single/multiple dispatch happens during runtime.</p>
<p>Sample code:</p>
<pre><code>using NUnit.Framework;
namespace SanityCheck.UnitTests.StackOverflow
{
[TestFixture]
public class DispatchTypes
{
[Test]
public void Polymorphism()
{
Baz baz = new Baz();
Foo foo = new Foo();
// overloading - parameter type is known during compile time
Assert.AreEqual("zap object", baz.Zap("hello"));
Assert.AreEqual("zap foo", baz.Zap(foo));
// virtual call - single dispatch. Baz is used.
Zapper zapper = baz;
Assert.AreEqual("zap object", zapper.Zap("hello"));
Assert.AreEqual("zap foo", zapper.Zap(foo));
// C# has doesn't support multiple dispatch so it doesn't
// know that oFoo is actually of type Foo.
//
// In languages with multiple dispatch, the type of oFoo will
// also be used in runtime so Baz.Zap(Foo) will be called
// instead of Baz.Zap(object)
object oFoo = foo;
Assert.AreEqual("zap object", zapper.Zap(oFoo));
}
public class Zapper
{
public virtual string Zap(object o) { return "generic zapper" ; }
public virtual string Zap(Foo f) { return "generic zapper"; }
}
public class Baz : Zapper
{
public override string Zap(object o) { return "zap object"; }
public override string Zap(Foo f) { return "zap foo"; }
}
public class Foo { }
}
}
</code></pre>
|
Free/Open Source Test Generator for Java? <p>Are there any libraries for Java that can generate unit tests or unit test skeletons for existing code? I'm looking for something similar to <a href="http://pythoscope.org/">pythoscope</a>. Ideally it would generate code that follows JUnit4 or TestNG conventions.</p>
<p>It looks like <a href="http://www.agitar.com/">Agitar</a> does something like this, but I'm looking for something free.</p>
|
<p>Most IDEs will generate test method stubs for any class. I know Eclipse will.</p>
<p>New->JUnit Class
then you tell it which class you're testing and what methods you want to test.</p>
|
Any quirks I should be aware of in Drupal's XML-RPC and BlogAPI implementations? <p>I'm beginning work on a project that will access a <code>Drupal</code> site to create (and eventually edit) nodes on the site, via the <code>XML-RPC</code> facility and <code>BlogAPI</code> module shipped with <code>Drupal</code>. This includes file uploading, as the project is to allow people to upload pictures en mass to a <code>Drupal</code> site with minimal ado.</p>
<p>What I'd like to know is if there are any caveats I should look out for. Has anyone had experience targeting <code>Drupal's XML-RPC implementation</code>, or the implementation of any of the <code>blogging APIs</code> supported by its <code>BlogAPI module</code>? What advice would you give to others taking the same path?</p>
|
<p>While the XML-RPC facility is pretty stable and works well, the BlogAPI module has various issues, especially with discovery, that make using it for anything but regular blogs painful. Currently, there is no use of blogIds in the generated Really Simple Discovery document (of which only one exists for a site) or for the blogging APIs implemented in BlogAPI.</p>
<p>Which blog receives a post is determined by user credentials, which works fine as long as only one node type is available for access through BlogAPI, but when you try and have two or more node types available through the module, things tend to fall apart.</p>
<p>Looking at the state of BlogAPI in Drupal's HEAD on CVS, we might not see a solution to this until 8.x at the earliest. However, there are several people working on redeveloping BlogAPI as a third party module, perhaps to merge back in to Drupal core at some later date. If you want to use a well-known blogging API, it might be best to get involved with their effort. If it's something else, though, the XML-RPC facility provided through hook_xmlrpc() does a great job of letting you provide your own XML-RPC interfaces.</p>
|
MySQL search and replace some text in a field <p>What MySQL query will do a text search and replace in one particular field in a table?</p>
<p>ie search for 'foo' and replace with 'bar' so a record with a field with the value : 'hello foo' becomes: 'hello bar'.</p>
|
<p>Change <code>table_name</code> and <code>field</code> to match your table name and field in question:</p>
<pre><code>UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') > 0;
</code></pre>
|
Generic LINQ query predicate? <p>Not sure if this is possible or if I'm expressing correctly what I'm looking for, but I have the following piece of code in my library repeatedly and would like to practice some DRY.
I have set of SQL Server tables that I'm querying based on a simple user-supplied search field ala Google. I'm using LINQ to compose the final query based on what's in the search string. I'm looking for a way to use generics and passed in lambda functions to create a reusable routine out of this: </p>
<pre><code>string[] arrayOfQueryTerms = getsTheArray();
var somequery = from q in dataContext.MyTable
select q;
if (arrayOfQueryTerms.Length == 1)
{
somequery = somequery.Where<MyTableEntity>(
e => e.FieldName.StartsWith(arrayOfQueryTerms[0]));
}
else
{
foreach(string queryTerm in arrayOfQueryTerms)
{
if (!String.IsNullOrEmpty(queryTerm))
{
somequery = somequery
.Where<MyTableEntity>(
e => e.FieldName.Contains(queryTerm));
}
}
}
</code></pre>
<p>I was hoping to create a generic method with signature that looks something like:</p>
<pre><code>private IQueryable<T> getQuery(
T MyTableEntity, string[] arrayOfQueryTerms, Func<T, bool> predicate)
</code></pre>
<p>I'm using the same search strategy across all my tables, so the only thing that really differs from usage to usage is the MyTable & MyTableEntity searched and the FieldName searched. Does this make sense? Is there a way with LINQ to dynamically pass in the name of the field to query in the where clause? Or can I pass in this as a predicate lambda?</p>
<pre><code>e => e.FieldName.Contains(queryTerm)
</code></pre>
<p>I realize there a million and a half ways to do this in SQL, probably easier, but I'd love to keep everything in the LINQ family for this one. Also, I feel that generics should be handy for a problem like this. Any ideas?</p>
|
<p>It sounds like you're looking for Dynamic Linq. Take a look <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="nofollow">here</a>. This allows you to pass strings as arguments to the query methods, like:</p>
<pre><code>var query = dataSource.Where("CategoryID == 2 && UnitPrice > 3")
.OrderBy("SupplierID");
</code></pre>
<p>Edit: Another set of posts on this subject, using C# 4's Dynamic support: <a href="http://weblogs.asp.net/davidfowler/archive/2010/08/04/dynamic-linq-a-little-more-dynamic.aspx" rel="nofollow">Part 1</a> and <a href="http://weblogs.asp.net/davidfowler/archive/2010/08/19/dynamic-linq-part-2-evolution.aspx" rel="nofollow">Part 2</a>.</p>
|
Need to create a dynamic ConfigurationSection that also holds the type <p>I need to create a configuration section, that is able to store key-value pairs in an app.config file and the key-value pairs can be added runtime regardless of their type. It is also important that the value keeps its original type. I need to extend the following interface </p>
<pre><code>public interface IPreferencesBackend
{
bool TryGet<T>(string key, out T value);
bool TrySet<T>(string key, T value);
}
</code></pre>
<p>At runtime, I can say something like: </p>
<pre><code>My.Foo.Data data = new My.Foo.Data("blabla");
Pref pref = new Preferences();
pref.TrySet("foo.data", data);
pref.Save();
My.Foo.Data date = new My.Foo.Data();
pref.TryGet("foo.data", out data);
</code></pre>
<p>I tried with System.Configuration.Configuration.AppSettings, but the problem with that that it is storing the key-value pairs in a string array. </p>
<p>What I need is to have an implementation of System.Configuration.ConfigurationSection, where I can control the how the individual setting is serialized. I noticed that the settings generated by Visual Studio kind of do this. It is using reflection to create all the setting keys. what I need is to do this runtime and dynamically. </p>
<pre><code>[System.Configuration.UserScopedSettingAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.Configuration.DefaultSettingValueAttribute("2008-09-24")]
public global::System.DateTime DateTime {
get {
return ((global::System.DateTime)(this["DateTime"]));
}
set {
this["DateTime"] = value;
}
}
</code></pre>
|
<p>Phil Haack has a great article on <a href="http://haacked.com/archive/2007/03/12/custom-configuration-sections-in-3-easy-steps.aspx" rel="nofollow">Creating Custom Configuration Sections</a></p>
|
Deploy multiple instance of reporting services or connect to multiple versions of DLLs <p>Is there any way in SSRS2008 to deploy multiple instances of the ReportServer running separate code sets?</p>
<p>I'm developing a very specific deployment of reporting services where I have a number of custom extensions plugged in. But, my company typically deploys multiple versions of a release at once on the same server. I'm at a little bit of a loss of a good way to do this with reporting services.</p>
<p>I know that I have a few alternatives:</p>
<ul>
<li>Run multiple instances of Reporting Services with different code sets</li>
</ul>
<p>The downside to this is that it's a little bit of a headache to upgrade and I'd rather not have multiple instances of the reporting databases. I'm not sure if they would play well together if they were targeting the same databases.</p>
<ul>
<li>Invoke/include the version specific DLLs on demand by reading from an HTTPRequest variable. (Assembly.LoadFile)</li>
</ul>
<p>I have a feeling that this could have performance issues and it also sounds like a potential debugging nightmare. I have also not used Assembly.LoadFile before and I'm unsure of how much code I'd have to write that was unversioned to control the versioning system.</p>
<p>Anyone out there have experience with any of this?</p>
|
<p>You can install multiple RS front ends onto one DB backend.</p>
<p>It works well. We use it to have 2 primary RS boxes (load balanced) with 3rd BCP/DR hot standby box. They are all in the farm.</p>
<p>You can have multiple instances on the same box too.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms159114(SQL.90).aspx" rel="nofollow">How to: Configure a Report Server Scale-Out Deployment (Reporting Services Configuration)</a></p>
|
SQL Job Status <p>I am actually working on SP in SQL 2005. Using SP i am creating a job and am scheduling it for a particular time. These jobs take atleast 5 to 10 min to complete as the database is very huge. But I am not aware of how to check the status of the Job. I want to know if it has got completed successfully or was there any error in execution. On exception i also return proper error code. But i am not aware of where i can check for this error code.</p>
|
<p>This is what I could find, maybe it solves your problem:</p>
<ol>
<li>SP to get the current job activiity.</li>
</ol>
<blockquote>
<pre><code> exec msdb.dbo.sp_help_jobactivity @job_id = (your job_id here)
</code></pre>
</blockquote>
<p>You can execute this SP and place the result in a temp table and get the required result from there.</p>
<p>Otherwise have a look at these tables:</p>
<ul>
<li><p>msdb.dbo.sysjobactivity</p></li>
<li><p>msdb.dbo.sysjobhistory</p></li>
</ul>
<p>Run the following to see the association between these tables. </p>
<blockquote>
<p>exec sp_helptext sp_help_jobactivity</p>
</blockquote>
|
What are the advantages of using the C++ Boost libraries? <p>So, I've been reading through and it appears that the Boost libraries get used a lot in practice (not at my shop, though). Why is this? and what makes it so wonderful? </p>
|
<p><a href="http://www.boost.org/">Boost</a> is used so extensively because:</p>
<ul>
<li>It is open-source and peer-reviewed. </li>
<li>It provides a <a href="http://www.boost.org/doc/libs">wide range</a> of platform agnostic functionality that STL missed.</li>
<li>It is a complement to STL rather than a replacement.</li>
<li>Many of Boost developers are on the C++ standard committee. In fact, many parts of Boost is considered to be included in the next C++ standard library.</li>
<li>It is documented nicely.</li>
<li>Its <a href="http://en.wikipedia.org/wiki/Boost_Software_License">license</a> allows inclusion in open-source and closed-source projects.</li>
<li>Its features are not <em>usually</em> dependent on each other so you can link only the parts you require. [<a href="http://stackoverflow.com/users/15934/luc-hermitte">Luc Hermitte</a>'s comment]</li>
</ul>
|
How can I hyperlink to a file that is not in my Web Application? <p>Ok, my web application is at <strong>C:\inetpub\wwwroot\website</strong></p>
<p>The files I want to link to are in <strong>S:\someFolder</strong></p>
<p>Can I make a link in the webapp that will direct to the file in <strong>someFolder</strong>?</p>
|
<p>If its on a different drive on the server, you will need to make a <a href="http://www.zerog.com/ianetmanual/IISVDirs_O.html" rel="nofollow">virtual directory</a> in IIS. You would then link to "<code>/virtdirect/somefolder/</code>"</p>
|
Piece together several images into one big image <p>I'm trying to put several images together into one big image, and am looking for an algorithm which determines the placing most optimally. The images can't be rotated or resized, but the position in the resulting image is not important.</p>
<p>edit: added no resize constraint</p>
|
<p>Possibly you are looking for something like this: <a href="http://www.alistapart.com/articles/magazinelayout" rel="nofollow">Automatic Magazine Layout</a>.</p>
|
How can I programatically manipulate any Windows application's common dialog box? <p>My ultimate goal here is to write a utility that lets me quickly set the folder on <em>any</em> dialog box, choosing from a preset list of 'favorites'. As I'm just a hobbyist, not a pro, I'd prefer to use .NET as that's what I know best. I do realize that some of this stuff might require something more than what I could do in C#.</p>
<p>I have seen some applications that are able to extend the common dialog box (specifically for Save As.. and File Open) either by adding buttons to the toolbar (eg: <a href="http://www.win-utilities.com/dba/index.html" rel="nofollow">Dialog Box Assistant</a>) or by putting extra buttons in the title bar beside the minimize, maximize, and/or close buttons. Either would be good option though I don't have the foggiest idea where to begin.</p>
<p>One approach I've tried is to 'drag' the folder name from an app I wrote to the file name textbox on the dialog box, highlighting it using a mouse hook technique I picked up from Corneliu Tusnea's <a href="http://readify.net/tech-zone/tech-tools/hawkeye-the-net-runtime-object-editor/Default.aspx" rel="nofollow">Hawkeye Runtime Object Editor</a>, and then prepending the path name by pinvoking SendMessage with WM_SETTEXT. It (sort of) works but feels a bit klunky.</p>
<p>Any advice on technique or implementation for this would be much appreciated. Or if there's an existing utility that already does this, please let me know!</p>
<p><strong>Update</strong>: When all is said and done, I think I'll probably got with an existing utility. However, I would like to know if there <em>is</em> a way to do this programmatically.</p>
|
<p>Sounds like a job for <a href="http://www.autohotkey.com">AutoHotkey</a> to me.</p>
<p>I am a "pro" (at least I get paid to program), but I would first look at using AutoHotkeys' many well tested functions to access windows, rather then delving into C#/.NET and most likey the WinAPI via PInvoke.</p>
<p>AutoHotkey even provides some basic user interface controls and is free.</p>
<p>Here's an <a href="http://www.autohotkey.com/docs/scripts/FavoriteFolders.htm">AutoHotkey script</a> that is very similar to what you are asking for.</p>
|
Why do I get an error when starting ruby on rails app with mongrel_rails <p>Why do I get following error when trying to start a ruby on rails application with <pre>mongrel_rails start</pre>?</p>
<pre>
C:\RailsTest\cookbook2>mongrel_rails start
** WARNING: Win32 does not support daemon mode.
** Daemonized, any open files are closed. Look at log/mongrel.pid and log/mongr
el.log for info.
** Starting Mongrel listening at 0.0.0.0:3000
c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../lib/mongrel/t
cphack.rb:12:in `initialize_without_backlog': Only one usage of each socket addr
ess (protocol/network address/port) is normally permitted. - bind(2) (Errno::EAD
DRINUSE)
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../
lib/mongrel/tcphack.rb:12:in `initialize'
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../
lib/mongrel.rb:93:in `new'
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../
lib/mongrel.rb:93:in `initialize'
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../
lib/mongrel/configurator.rb:139:in `new'
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../
lib/mongrel/configurator.rb:139:in `listener'
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon
grel_rails:99:in `cloaker_'
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../
lib/mongrel/configurator.rb:50:in `call'
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../
lib/mongrel/configurator.rb:50:in `initialize'
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon
grel_rails:84:in `new'
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon
grel_rails:84:in `run'
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../
lib/mongrel/command.rb:212:in `run'
from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon
grel_rails:281
from c:/ruby/bin/mongrel_rails:19:in `load'
from c:/ruby/bin/mongrel_rails:19
</pre>
|
<p>I don't use mongrel on windows myself, but I guess that error is the equivalent of Linux' "port in use" error. Are you trying to bind the server to a port where something else is already listening?</p>
|
Adapt an Apache mod_rewrite RewriteRule not to act on physical directories <p>I have this RewriteRule that works too well :-)</p>
<pre><code>RewriteRule ^([^/]*)/$ /script.html?id=$1 [L]
</code></pre>
<p>The bad thing about this rule is that it also matches physical directories which I don't want.</p>
<p>How can I tell the <code>mod_rewrite</code> to ignore physical directories and apply the above rule only when the directory matched does not exist?</p>
|
<p>Take a look at <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond" rel="nofollow">RewriteCond</a>. Put the following before your rule to exempt out directories and files</p>
<pre><code>RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
</code></pre>
|
Can anyone recommend a C++ std::map replacement container? <p>Maps are great to get things done easily, but they are memory hogs and suffer from caching issues. And when you have a map in a critical loop that can be bad.</p>
<p>So I was wondering if anyone can recommend another container that has the same API but uses lets say a vector or hash implementation instead of a tree implementation. My goal here is to swap the containers and not have to rewrite all the user code that relies on the map.</p>
<p>Update: performance wise the best solution would be a tested map facade on a std::vector</p>
|
<p>You can use std::tr1::unordered_map, which is already present in most STL implementations, and is part of the C++0x standard.</p>
<p>Here is it's current signature :</p>
<pre><code>template <class Key,
class T,
class Hash = std::tr1::hash<Key>,
class Pred = std::equal_to<Key>,
class Alloc = std::allocator<std::pair<const Key, T> > >
class unordered_map;
</code></pre>
|
UML connector Direction <p>When modelling an architecture in UML component diagrams, how do you show various attributes of connectors simultaneously? Like </p>
<ul>
<li>business object information flow (A->B, B->A, A<->B)</li>
<li>request/response direction</li>
<li>synchronous/asynchronous behaviour</li>
</ul>
<p>I am aware of other diagram types like sequence diagrams. However, having this information visible in component diagrams would have value. </p>
<p>What is possible beyond associations (merely showing that components are connected) or "lollipops" (request/response)?</p>
|
<p>For a start, <strong>don't</strong> try to explain these dynamic collaborations using the connectors on your class diagram. </p>
<p>The direction of the arrow connectors on the class diagram just specifies the <em>who knows who</em>. That means, the dependencies between classes. With those arrows you can communicate which classes need what other classes, but you don't have to explain there <em>how</em> are the dynamics of the collaboration between those clases. That's what UML dynamic diagrams are for.</p>
<p>Start with your class diagram, which is the <em>static</em> view of the system, and then add some dynamic diagrams.</p>
<p>As dynamic diagrams, together with sequence diagrams that are the most common, you can also use:</p>
<ul>
<li>Activity diagrams</li>
<li>State diagrams</li>
<li>Collaboration diagrams</li>
</ul>
<p>Each has its own point of interest, and the main strategy is that you reuse some of the objects defined in your class diagram in order to describe specific scenarios.</p>
<p>For each one of the 'interesting' scenarios on your system, you should make one of these dynamic diagrams to describe what happens between the objects that you specified on your class diagram.</p>
<p>Typically, each use case will be described by one class diagram and one or more dynamic diagrams. All these design information together is called <em>the use case realization</em>, because they describe the design that will make your use case <em>real</em> when the code is built.</p>
<p>Check out <a href="http://rads.stackoverflow.com/amzn/click/020165783X" rel="nofollow">Fowler's UML Distilled</a> for a concise but excellent explanation of this design workflow using UML.</p>
|
Decode an UTF8 email header <p>I have an email subject of the form:</p>
<pre><code>=?utf-8?B?T3.....?=
</code></pre>
<p>The body of the email is utf-8 base64 encoded - and has decoded fine.
I am current using Perl's Email::MIME module to decode the email.</p>
<p>What is the meaning of the =?utf-8 delimiter and how do I extract information from this string?</p>
|
<p>The <a href="http://en.wikipedia.org/wiki/MIME#Encoded-Word"><code>encoded-word</code></a> tokens (as per <a href="http://www.faqs.org/rfcs/rfc2047.html">RFC 2047</a>) can occur in values of some headers. They are parsed as follows:</p>
<pre><code>=?<charset>?<encoding>?<data>?=
</code></pre>
<p>Charset is UTF-8 in this case, the encoding is <code>B</code> which means base64 (the other option is <code>Q</code> which means Quoted Printable).</p>
<p>To read it, first decode the base64, then treat it as UTF-8 characters.</p>
<p>Also read the various Internet Mail RFCs for more detail, mainly <a href="http://www.faqs.org/rfcs/rfc2047.html">RFC 2047</a>.</p>
<p>Since you are using Perl, <a href="https://metacpan.org/pod/Encode::MIME::Header">Encode::MIME::Header</a> could be of use:</p>
<blockquote>
<p>SYNOPSIS</p>
<pre><code>use Encode qw/encode decode/;
$utf8 = decode('MIME-Header', $header);
$header = encode('MIME-Header', $utf8);
</code></pre>
<p>ABSTRACT</p>
<p>This module implements RFC 2047 Mime
Header Encoding. There are 3 variant
encoding names; MIME-Header, MIME-B
and MIME-Q. The difference is
described below</p>
<pre><code> decode() encode()
MIME-Header Both B and Q =?UTF-8?B?....?=
MIME-B B only; Q croaks =?UTF-8?B?....?=
MIME-Q Q only; B croaks =?UTF-8?Q?....?=
</code></pre>
</blockquote>
|
How to efficiently count the number of keys/properties of an object in JavaScript? <p>What's the fastest way to count the number of keys/properties of an object? It it possible to do this without iterating over the object? i.e. without doing</p>
<pre><code>var count = 0;
for (k in myobj) if (myobj.hasOwnProperty(k)) count++;
</code></pre>
<p>(Firefox did provide a magic <code>__count__</code> property, but this was removed somewhere around version 4.)</p>
|
<p>To do this in any ES5-compatible environment, such as <a href="http://nodejs.org">Node</a>, Chrome, IE 9+, FF 4+, or Safari 5+:</p>
<pre class="lang-js prettyprint-override"><code>Object.keys(obj).length
</code></pre>
<ul>
<li><a href="http://kangax.github.com/es5-compat-table/">Browser compatibility</a></li>
<li><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys">Object.keys documentation</a>
<ul>
<li>(includes a method you can add to non-ECMA5 browsers)</li>
</ul></li>
</ul>
|
The Clean programming language in the real world? <p>Are there any real world applications written in the <a href="http://clean.cs.ru.nl/" rel="nofollow">Clean</a> programming language? Either open source or proprietary.</p>
|
<p>This is not a direct answer, but when I checked last time (and I find the language very interesting) I didn't find anything ready for real-world.</p>
<p>The idealist in myself always wants to try out new languagages, very hot on my list (apart from the aforementioned very cool Clean Language) is currently (random order) <a href="http://www.iolanguage.com/">IO</a>, <a href="http://www.fandev.org/">Fan</a> and <a href="http://www.scala-lang.org/">Scala</a>...</p>
<p>But in the meantime I then get my pragmatism out and check the <a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html">Tiobe Index</a>. I know you can discuss it, but still: It tells me what I will be able to use in a year from now and what I possibly won't be able to use...</p>
<p>No pun intended!</p>
|
Resources and guides to UI virtualization in WPF <p>UI Virtualization is an awkward terminology that describes WPF UI controls that load and and dispose child elements on demand (based on their visibility) to reduce memory footprint. ListBox and ListView use a class called VirtualizingStackPanel by default to achieve higher performance. </p>
<p>I found <a href="http://blogs.msdn.com/jgoldb/archive/2008/03/08/performant-virtualized-wpf-canvas.aspx">this control</a>, which is really helpful, a virtualized canvas which produces a scrollable Canvas object that manages its children with a quadtree. It produces some great results and can easily be tweaked to your needs.</p>
<p>Are there any other guides or sample wpf controls that deal with this issue? Maybe generic one's that deal with dynamic memory allocation of gui objects in other languages and toolkits?</p>
|
<p>Dan Crevier has a small tutorial on building a <a href="http://blogs.msdn.com/dancre/archive/tags/VirtualizingTilePanel/default.aspx">VirtualisingTilePanel</a>.</p>
<p>Ben Constable has written a tutorial on IScrollInfo, which is an essential part of the virtualisation: <a href="http://blogs.msdn.com/bencon/archive/2006/01/05/509991.aspx">Part 1</a>, <a href="http://blogs.msdn.com/bencon/archive/2006/01/06/510355.aspx">Part 2</a>, <a href="http://blogs.msdn.com/bencon/archive/2006/01/07/510530.aspx">Part 3</a> and <a href="http://blogs.msdn.com/bencon/archive/2006/12/09/iscrollinfo-tutorial-part-iv.aspx">Part 4</a>.</p>
|
Objections against Java Webstart? <p>Since the release of Adobe AIR I am wondering why Java Web Start has not gained more attention in the past as to me it seems to be very similar, but web start is available for a much longer time.</p>
<p>Is it mainly because of bad marketing from Sun, or are there more technical concerns other than the need of having the right JVM installed? Do you have bad experiences using Web Start? If yes, which? What are you recommendations when using Web Start for distributing applications?</p>
|
<p>In my company we used Java Web Start to deploy Eclipse RCP applications. It was a pain to setup, but it works very well once in place. So the only recommendation I could make is to start small, to get the hang of it. Deploying one simple application first. Trying to deploy a complete product that is already made without experience with JWS gets complicated rather quickly.</p>
<p>Also, learning how to pass arguments to the JWS application was invaluable for debugging. Setting the Environment variable JAVAWS_VM_ARGS allows setting any arbitrary property to the Java Virtual machine. In my case:</p>
<p>-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=4144</p>
<p>Helpful when you need to check problems during start-up (suspend=y)</p>
<p>I think the main problem for the acceptance of Java Web Start is that it is relatively difficult to setup. Also, somehow there is this dissonance: When you have a desktop application, people expects a installer they can double click. When you have a web application, people expects they can use it right from the browser. Java Web Start is neither here not there...</p>
<p>It is widely used in intranets, though.</p>
|
Undoing specific revisions in Subversion <p>Suppose I have a set of commits in a repository folder...</p>
<pre><code>123 (250 new files, 137 changed files, 14 deleted files)
122 (150 changed files)
121 (renamed folder)
120 (90 changed files)
119 (115 changed files, 14 deleted files, 12 added files)
118 (113 changed files)
117 (10 changed files)
</code></pre>
<p>I want to get a working copy that includes all changes from revision 117 onward but does NOT include the changes for revisions 118 and 120.</p>
<p>EDIT: To perhaps make the problem clearer, I want to undo the changes that were made in 118 and 120 while retaining all other changes. The folder contains thousands of files in hundreds of subfolders.</p>
<p>What is the best way to achieve this?</p>
<p><strong>The answer</strong>, thanks to Bruno and Bert, is the command (in this case, for removing 120 after the full merge was performed)</p>
<pre><code>svn merge -c -120 .
</code></pre>
<p>Note that the revision number must be specified with a leading minus. '-120' not '120'</p>
|
<p>To undo revisions 118 and 120:</p>
<pre><code>svn up -r HEAD # get latest revision
svn merge -c -120 . # undo revision 120
svn merge -c -118 . # undo revision 118
svn commit # after solving problems (if any)
</code></pre>
<p>Also see the description in <a href="http://svnbook.red-bean.com/en/1.5/svn.branchmerge.basicmerging.html#svn.branchmerge.basicmerging.undo">Undoing changes</a>.</p>
<p>Note the minus in the <code>-c -120</code> argument. The <code>-c</code> (or <code>--change</code>) switch is supported since Subversion 1.4, older versions can use <code>-r 120:119</code>.</p>
|
How to secure MS SSAS 2005 for HTTP remote access via Internet? <p>We are building an hosted application that uses MS SQL Server Analysis Services 2005 for some of the reporting, specifically OLAP cube browsing. Since it is designed to be used by very large global organizations, security is important.</p>
<p>It seems that Microsoft's preferred client tool for browsing OLAP cubes is Excel 2007 and the whole infrastructure is geared around Windows Integrated Authentication. We, however, are trying to build an internet-facing web application and do not want to create Windows Accounts for every user.</p>
<p>It also seems that there are not many nice AJAXy web-based OLAP cube browsing tools (fast, drag-and-drop for dimensions, support for actions, cross-browser etc.) As an aside, we're currently using <a href="http://www.dundas.com/Products/Chart/NET/OLAP/index.aspx" rel="nofollow">Dundas OLAP Grid</a> but have also considered <a href="http://www.radar-soft.com/products/radaraspnet_MSAS.aspx" rel="nofollow">RadarCube</a> and other more expensive commercial solutions and are still thinking of taking on <a href="http://www.sqlserveranalysisservices.com/cellsetgrid/cellsetgridintro.htm" rel="nofollow">CellSetGrid</a> and developing it further - if you know of any other cheap/open solutions please let me know!</p>
<p>We are therefore planning on providing two modes of access to the cube data:</p>
<ol>
<li>Through our own Web Application using one of these 3rd party Web-based OLAP browsing tools. </li>
<li>Direct access from Excel over HTTPS via the msmdpump.dll data pump, for when the web version is too slow/clunky or user needs more powerful analysis.</li>
</ol>
<p>For the web app access, the connection to the SSAS data source happens from the web server so we can happily pass a CustomData item on the Connection String which indicates which user is connecting. Since we potentially have too many combinations of rights to create individual SSAS roles for, we have implemented <strong>dynamic dimension security</strong> that uses a "Cube Users" dimension in conjunction with the CustomData item from the connection string and limits the Allowed Set of various other dimension members accordingly (via other Many-to-Many dinemsion relationships with Measure Groups that contain the 'rights mapping')</p>
<p>See Mosha on Dimension Security:
<a href="http://www.sqljunkies.com/WebLog/mosha/archive/2004/12/16/5605.aspx" rel="nofollow">http://www.sqljunkies.com/WebLog/mosha/archive/2004/12/16/5605.aspx</a></p>
<p>This all seems to work fine so far.</p>
<p>For the 'direct connection' from Excel, we set up the data pump for HTTP access
(see the <a href="http://www.microsoft.com/technet/prodtechnol/sql/2005/httpasws.mspx" rel="nofollow">MS Technet article</a>) but have enabled anonymous access, relying again on the Connection String to control access since we don't have windows accounts.
However, in this case, the connection string is controlled by the user (we push a .odc file from the web app, but a curious user could view & change it), so we cannot rely on users to be good and keep the [email protected] from changing to [email protected]. As it turns out, this also causes the same problem with Roles, since these are also specified on the connection string if you are <strong>not</strong> using Windows Integrated Authentication.</p>
<p>The question therefore boils down to this: is there a way of getting basic authentication in IIS working without windows accounts in such a way that it can be used with the SSAS data pump to let SSAS know which user is connecting so that dynamic dimension security can be used successfully?</p>
<p>(This is my first q on StackOverflow and probably the most complicated question I've ever asked: let me know where I haven't explained myself very well and I'll attempt to clarify)</p>
|
<p>Basic authentication will work with local user accounts (non-domain) and even support passthrough authentication if the local accounts exist on different machines, however you should force SSL as basic authentication sends passwords in plaintext. </p>
<p>You can use non-windows accounts with basic authentication in IIS with add-on such as <a href="http://www.codeplex.com/CustomBasicAuth" rel="nofollow">http://www.codeplex.com/CustomBasicAuth</a>, but SSAS will still need to know who that user is and as far as I know SSAS uses only Windows authentication.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.