input
stringlengths
51
42.3k
output
stringlengths
18
55k
opengl set texture color with vertex color <p>Because I need to display a <a href="http://codeflow.org/ubuntu.png" rel="nofollow">huge number of labels</a> that <a href="http://www.youtube.com/watch?v=A_ah-SE-cNY" rel="nofollow">move independently</a>, I need to render a label in <a href="http://pyglet.org" rel="nofollow">pyglet</a> to a texture (otherwise updating the vertex list for each glyph is too slow).</p> <p>I have a solution to do this, but my problem is that the texture that contains the glyphs is black, but I'd like it to be red. See the example below:</p> <pre><code>from pyglet.gl import * def label2texture(label): vertex_list = label._vertex_lists[0].vertices[:] xpos = map(int, vertex_list[::8]) ypos = map(int, vertex_list[1::8]) glyphs = label._get_glyphs() xstart = xpos[0] xend = xpos[-1] + glyphs[-1].width width = xend - xstart ystart = min(ypos) yend = max(ystart+glyph.height for glyph in glyphs) height = yend - ystart texture = pyglet.image.Texture.create(width, height, pyglet.gl.GL_RGBA) for glyph, x, y in zip(glyphs, xpos, ypos): data = glyph.get_image_data() x = x - xstart y = height - glyph.height - y + ystart texture.blit_into(data, x, y, 0) return texture.get_transform(flip_y=True) window = pyglet.window.Window() label = pyglet.text.Label('Hello World!', font_size = 36) texture = label2texture(label) @window.event def on_draw(): hoff = (window.width / 2) - (texture.width / 2) voff = (window.height / 2) - (texture.height / 2) glClear(GL_COLOR_BUFFER_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(0.0, 1.0, 0.0, 1.0) window.clear() glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture.id) glColor4f(1.0, 0.0, 0.0, 1.0) #I'd like the font to be red glBegin(GL_QUADS); glTexCoord2d(0.0,1.0); glVertex2d(hoff,voff); glTexCoord2d(1.0,1.0); glVertex2d(hoff+texture.width,voff); glTexCoord2d(1.0,0.0); glVertex2d(hoff+texture.width,voff+texture.height); glTexCoord2d(0.0,0.0); glVertex2d(hoff, voff+texture.height); glEnd(); pyglet.app.run() </code></pre> <p>Any idea how I could color this?</p>
<p>You want to set <code>glEnable(GL_COLOR_MATERIAL)</code>. This makes the texture color mix with the current OpenGL color. You can also use the <code>glColorMaterial</code> function to specify whether the front/back/both of each polygon should be affected. Docs <a href="http://www.glprogramming.com/blue/ch05.html#id37922" rel="nofollow">here</a>.</p>
AJAX console window with ANSI/VT100 support? <p>I'm planning to write gateway web application, which would need "terminal window" with VT100/ANSI escape code support. Are there any AJAX based alternatives for such a task?</p> <p>I'm thinking something like this: <a href="http://tryruby.hobix.com/">http://tryruby.hobix.com/</a></p> <p>My preferred backend for the system is Python/Twisted/Pylons, but since I'm just planning, I will explore every option.</p>
<p>Try</p> <p><a href="http://wiki.kartbuilding.net/index.php/Anyterm">AnyTerm</a></p> <p><a href="http://wiki.kartbuilding.net/index.php/Ajaxterm">AjaxTerm</a></p> <p><a href="http://www-personal.umich.edu/~mressl/webshell/">WebShell</a></p>
Autocomplete on SQL Management Studio? <p>Does anyone know if there's an add-in that does autocomplete for queries on SQL Management Studio?</p>
<p>You can also try Devart's free SQL Complete. </p> <p><a href="http://www.devart.com/dbforge/sql/sqlcomplete/">http://www.devart.com/dbforge/sql/sqlcomplete/</a></p>
Can you modify CPU registers from within VS2008 IDE? <p>Was just wondering if there was a way to edit the CPU registers (i.e. EAX, EBX, ECX, etc) or flags (OV, UP, erc) from within the Visual Studio IDE. I know you can <strong>view</strong> them using the Registers pane (ctrl-shift-G) and you can cycle through them with TAB or ENTER, but I don't seem to be able to change any of them while debugging (yes, program execution is halted :)).</p> <p>I don't really have a strong need to do so, it's just that: I can see the assembly... I used to be able to do this (VC++6)... why can't I now, kind'a thing!</p> <p>Thanks!</p>
<p>yes, you can....</p> <p>from the help (you know...the f1 key)</p> <p>To change the value of a register </p> <ul> <li>In the Registers window, use the TAB key or the mouse to move the insertion point to the value you want to change. When you start to type, the cursor must be located in front of the value you want to overwrite. </li> <li>Type the new value. </li> <li>Press ENTER. </li> </ul>
Strategic Advice: Upgrading the Design of a Web App <p>I have an ASP.NET web site dedicated to reporting on PBX extension stats. It comprises many report pages, with HTML generated almost purely by code-behind (setting a Label control's Text property instead of using Response.Write), using un-parameterised string literal SQL queries that populate By Reference DataTable parameters.</p> <p>Maintenance pages at least comprise DataGrids and detail forms, but use the same DAL, on e thing for which can be said is that it supports multiple DB servers, with sub-classes each overriding these access methods with their own string literal queries.</p> <p>What do I need to consider cleaning up this mess? I've already made an almost obvious decision to use a third party reporting solution, and move the queries to stored procs in their respective DB languages, narrowing the diversity of the different DAL classes, and to separate CSS out to shared files, as lots of it is very hidden in C# files!</p>
<p>For your back-end design, I suggest having a class to represent each main table of your database (i.e. a Report class and a User class, for example). Anything that's not an event handler should go in the back-end class files / namespace.</p> <p>For your GUI, looks like you're on the right track using ASP.NET controls instead of just streaming your data out to the user. However, you may consider objectifying the areas of the page. For example, one of my favorite tricks is to open semitransparent "popup" panels when requiring user input or a something like the Information Bar when displaying a short message.</p> <p>Consider AJAX and the AJAX Control Toolkit. It's easy to implement (especially in the case of a rewrite) and provides great flexibility. Specifically, I've found Accordions - sometimes even nested within other Accordions - are excellent at organizing overabundances of information.</p> <p>Edit: </p> <p>Note that if you were to use AJAX, you basically can't even consider using response.write anymore.</p> <p>As far as having too much content on the screen, remember Panels have a "Scrollbar" property and DIVs don't without some heavy changes.</p> <p>Also, I tend to separate my code files by Namespace; but the popular trend is to do so by Class. This is a better option if you have many Developers or if it's likely several classes within a namespace will be checked out or simultaneously modified by different people.</p>
Variable LIMIT Clause in MySQL <p>I am writing a stored procedure where I have an input parameter called my_size that is an int, I want to be able to use in a limit clause in a select statement. Apparently this is not supported, is there a way to work around this?</p> <pre><code># I want something like: SELECT * FROM some_table LIMIT my_size; # Instead of hardcoding a permanent limit: SELECT * FROM some_table LIMIT 100; </code></pre>
<p>For those, who cannot use MySQL 5.5.6+ and don't want to write a stored procedure, there is another variant. We can add where clause on a subselect with ROWNUM.</p> <pre><code>SET @limit = 10; SELECT * FROM ( SELECT instances.*, @rownum := @rownum + 1 AS rank FROM instances, (SELECT @rownum := 0) r ) d WHERE rank &lt; @limit; </code></pre>
Subversion vs CVS <p>I've used both SVN and CVS a little bit, but will need to choose one for a new project I will be starting.</p> <p>Can anyone who has used both extensively please offer some pros and cons and which they think is better? Best learning resources would be appreciated too.</p> <p>This will be for a small project, just one or two developers to start.</p>
<p>I've used both. There is no comparison; you want svn. The only reason to use CVS is because you are entering or taking over a legacy system with management that does not want to change the status quo. If you are starting on a new project, it is virtually a logical impossibility to argue that CVS is better than Subversion.</p> <p>If you google around, you should find plenty of comparisons, and rationales for using Subversion over CVS. Some of the advantages of Subversion over CVS:</p> <ul> <li>can move or rename files or directories cleanly</li> <li>atomic commits</li> <li>"cheap" copying and branching</li> <li>commits are changesets on the whole tree (not just histories on individual files)</li> </ul> <p>Having said all this, I recommend you also explore some of the distributed VCSs like Bazaar, Mercurial and git. I personally use git on all my projects.</p>
NSApplication and -applicationDidFinishLaunching: <p>I have an application where I have a <code>main.m</code> that returns <code>NSApplicationMain(argc, (const char **) argv);</code>.</p> <p>I want to run code on <code>-applicationDidFinishLaunching:</code>, but I just dont see how to do it. </p> <p>Can anyone help or have an example? </p> <p>Thanks! -Jason</p>
<p>The applicationDidFinishLaunching: method of the NSApplication delegate will be called when the app has finished loading. Many of the project templates setup a delegate. If you are using one just add the appropriate method to it.</p> <p>If your project does not have an app delegate set up you will need to do that yourself. First, make a new class to act as your delegate (you can use an exiting one if there is something logically appropriate). Now make sure that class is instantiated in your MainMenu.nib. Finally, hook the delegate property of the "File's Owner" object to the instantiate delegate in IB.</p>
dimensions of loaded swf's stage <p>Here's the situation - I've got a shell that loads an external .swf. Now, that .swf is 800x600, but it's an animation piece, and there are elements that extends off the stage. When I load the .swf into the shell and call its width attribute, it returns 1200 - because it's including the elements that break out of the stage.</p> <p>This isn't what I want - ideally, there would be two properties, one to return the 'calculated width' and one to return the 'default width'. Do these properties exist, and if not, what's the best workaround?</p>
<p>The width and height of the loaded SWF as defined by the FLA it was created with can be found in the <code>Loader</code> object in which you've loaded the SWF into.</p> <pre><code>swfLoader.contentLoaderInfo.width swfLoader.contentLoaderInfo.height </code></pre> <p>This will always show you the dimensions as defined in the FLA properties. It makes no difference if any images, MovieClips, or what have you extend off the stage.</p> <p>The <code>stage.stageWidth</code> and <code>stage.stageHeight</code> properties will always return the width of the stage, the stage is always the top most SWF. In other words, it will always represent the dimensions of the shell's stage. There is only ever one stage in a Flash application.</p>
Using a Single system() Call to Execute Multiple Commands in C <p>In an information security lab I'm working on, I've been tasked with executing multiple commands with a single call to "system()" (written in C, running on Fedora). What is the syntax that will allow me to execute more than command through system()? (The idea being you could execute arbitrary commands through a program running on a remote computer, if the program interacts with the OS through the system() call.)</p> <p>I.e.:</p> <pre><code>char command[] = "????? \r\n"; system(command); </code></pre>
<p>That depends on the shell being invoked to execute the commands, but in general most shells use <code>;</code> to separate commands so something like this should work:</p> <pre><code>command1; command2; command3 </code></pre> <p>[EDIT]</p> <p>As @dicroce mentioned, you can use <code>&amp;&amp;</code> instead of <code>;</code> which will stop execution at the first command that returns a non-zero value. This may or may not be desired (and some commands may return non-zero on success) but if you are trying to handle commands that can fail you should probably not string multiple commands together in a system() call as you don't have any way of determining where the failure occured. In this case your best bet would either be to execute one command at a time or create a shell script that performs the appropriate error handling and call that instead.</p>
Which variables should I typecast when doing math operations in C/C++? <p>For example, when I'm dividing two ints and want a float returned, I superstitiously write something like this:</p> <pre><code>int a = 2, b = 3; float c = (float)a / (float)b; </code></pre> <p>If I do not cast <code>a</code> and <code>b</code> to floats, it'll do integer division and return an int.</p> <p>Similarly, if I want to multiply a signed 8-bit number with an unsigned 8-bit number, I will cast them to signed 16-bit numbers before multiplying for fear of overflow:</p> <pre><code>u8 a = 255; s8 b = -127; s16 = (s16)a * (s16)b; </code></pre> <p>How exactly does the compiler behave in these situations when not casting at all or when only casting one of the variables? Do I really need to explicitly cast all of the variables, or just the one on the left, or the one on the right?</p>
<h3>Question 1: Float division</h3> <pre><code>int a = 2, b = 3; float c = static_cast&lt;float&gt;(a) / b; // need to convert 1 operand to a float </code></pre> <h3>Question 2: How the compiler works</h3> <p>Five rules of thumb to remember:</p> <ul> <li>Arithmetic operations are always performed on values of the same type.</li> <li>The result type is the same as the operands (after promotion)</li> <li>The smallest type arithmetic operations are performed on is int.</li> <li>ANSCI C (and thus C++) use value preserving integer promotion.</li> <li><b>Each operation is done in isolation</b>.</li> </ul> <p>The ANSI C rules are as follows:<br> Most of these rules also apply to C++ though not all types are officially supported (yet).</p> <ul> <li>If either operand is a <b>long double</b> the other is converted to a <b>long double</b>.</li> <li>If either operand is a <b>double</b> the other is converted to a <b>double</b>.</li> <li>If either operand is a <b>float</b> the other is converted to a <b>float</b>.</li> <li>If either operand is a <b>unsigned long long</b> the other is converted to <b>unsigned long long</b>.</li> <li>If either operand is a <b>long long</b> the other is converted to <b>long long</b>.</li> <li>If either operand is a <b>unsigned long</b> the other is converted to <b>unsigned long</b>.</li> <li>If either operand is a <b>long</b> the other is converted to <b>long</b>.</li> <li>If either operand is a <b>unsigned int</b> the other is converted to <b>unsigned int</b>.</li> <li><b>Otherwise both</b> operands are converted to <b>int</b>.</li> </ul> <h3>Overflow</h3> <p>Overflow is always a problem. Note. The type of the result is the same as the input operands so all the operations can overflow, so yes you do need to worry about it (though the language does not provide any explicit way to catch this happening.</p> <p>As a side note:<br> Unsigned division can not overflow but signed division can.<br></p> <pre><code>std::numeric_limits&lt;int&gt;::max() / -1 // No Overflow std::numeric_limits&lt;int&gt;::min() / -1 // Will Overflow </code></pre>
OOP Problems to use for Coding Tests during interviews <p>As a second interview I get people to sit down and write code...I try to make the problem really technology independent.</p> <p>My programming problems that I have don't really exercise peoples OO abilities. I tend to try and keep the coding problem solvable within 2 hours ish. So, I've struggled to find a problem small enough and involved enough that it exposes peoples OO design skills.</p> <p>Any suggestions?</p>
<p>This is a problem that I use with some trainings, looks simple but is tricky OOP-wise:</p> <p>Create model classes that will properly represent the following constructs:</p> <ol> <li>Define a Shape object, where the object is any two dimensional figure, and has the following characteristics: a name, a perimeter, and a surface area.</li> <li>Define a Circle, retaining and accurately outputting the values of the aforementioned characteristics of a Shape.</li> <li>Define a Triangle. This time, the name of the triangle should take into account if it is equilateral (all 3 sides are the same length), isoceles (only 2 sides are the same length), or scalene (no 2 sides are the same).</li> </ol> <p>You can go on and on with quadrelaterals (which include squares, rectangles, rhombi, etc) and other polygons.</p> <p>The way that they would solve the above problems would reveal the people who understand OOP apart from those who don't.</p>
Rename files in sub directories <p>Is there any way of batch renaming files in sub directories?</p> <p>Example: </p> <p>Rename *.html to *.htm in a folder which has directories and sub directories.</p>
<p>Windows command prompt: (If inside a batch file, change %x to %%x)</p> <pre><code>for /r %x in (*.html) do ren "%x" *.htm </code></pre> <p>This also works for renaming the middle of the files</p> <pre><code>for /r %x in (website*.html) do ren "%x" site*.htm </code></pre>
send key for right arrow <p>what is the syntax for the sendkey for rightarrow in .net?</p>
<p>{RIGHT} </p> <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx</a></p>
Button text in JTable renderer not visible. Why? <p>I have a custom cell renderer set in JTable and it works but instead an "x" visible on buttons being table cells I see "..." (three dots). What did I miss ??</p> <pre><code> /*************************************************************************** * Listener reagujący na dodanie nowej wartości **************************************************************************/ private static class ButtonRenderer extends JButton implements TableCellRenderer { /*********************************************************************** * Konstruktor **********************************************************************/ public ButtonRenderer() { super("x"); } /*********************************************************************** * @see TableCellRenderer#getTableCellRendererComponent(JTable, Object, * boolean, boolean, int, int) **********************************************************************/ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { return this; } } </code></pre>
<p>The size of the button isn't large enough to contain the rendered "x" plus the padding around it. </p> <p>A solution would be to enlarge the table cell or reduce the padding (always assuming that the button has the same size as the table cell).</p>
EBNF to fluent interface <p>I have recently had the need to write a fluent interface for C# that will essentially mirror SQL. Yes, I am aware of LINQ to SQL, but I'm interesting in getting "closer to the metal"--having something that essentially provides nothing more than an Intellisensified SQL shim <em>within</em> C#.</p> <p>E.g.,</p> <pre><code>var fq = new FluentQuery(); Expression&lt;Action&gt; = () =&gt; fq.SELECT.DISTINCT(Foo.ID).FROM(Foo).WHERE(Foo.Age &gt; 22); </code></pre> <p>Now, I was thinking that this concept could be generalised--that is, how about a general EBNF to fluent interface generator? Does anyone know if such a beast exists?</p>
<p>I like it, but you have to make sure to return types like HasFromAndSelect or something like that so you don't end up with <code>fq.SELECT(Foo.ID).SELECT(Foo.Age).WHERE(Foo.Age &gt; 22)</code> or <code>fq.WHERE(Foo.Age &gt; 22).SELECT(Foo.ID)</code>, etc.</p> <p>There's much more thought that needs to go into this, including the fact that the CAPS LOCK MODE is hurting my eyes :)</p>
How do I set up a test project for a Eclipse plugin project <p>I'm working on a eclipse plug-in and I've tried to create another test project seperate from the plug-in. The reason I do this is to not let the plug-in depend on jUnit when it is exported. However, I can't access the Eclipse Plug-in API when I do the testing. Whenever I try to add Plug-in dependencies the import list to that is empty.</p> <p>Does anyone know how to import Eclipse plug-in API to an existing project? The workspace layout looks like this at the moment:</p> <pre><code>+- com.foo.myplugin | | | +- JRE System Library | | | +- Plug-in Dependencies | | | +- src | | | +- icons, META-INF, plugin.xml, etc... | +- com.foo.myplugin.test | +- JRE System Library | +- JUnit 4 | +- src </code></pre>
<p>The recomended way of ding this seems to be with Plug-in fragments:</p> <p><a href="http://rcpquickstart.com/2007/06/20/unit-testing-plug-ins-with-fragments/">http://rcpquickstart.com/2007/06/20/unit-testing-plug-ins-with-fragments/</a></p> <p>The fragment gets a high-degree of access to your plugin's code and separates the testing logic / dependencies from the plugin itsself.</p> <p>Now if only I could find a way to test them in an automated system... (see: <a href="http://stackoverflow.com/questions/255370/automating-unit-tests-junit-for-eclipse-plugin-deveopment">http://stackoverflow.com/questions/255370/automating-unit-tests-junit-for-eclipse-plugin-deveopment</a> )</p>
What is the worst abuse you've seen of LINQ syntax? <p>On a recent <a href="http://www.dotnetrocks.com/default.aspx?showNum=383">Dot Net Rocks podcast</a>, Jon Skeet mentioned possible abuses of LINQ syntax. What examples have people seen where crazy things are being done with LINQ?</p>
<p>It has to be a <a href="http://blogs.msdn.com/lukeh/archive/2007/10/01/taking-linq-to-objects-to-extremes-a-fully-linqified-raytracer.aspx">ray-tracer implemented in a single LINQ expression</a>. Clever, beautiful, and scary all at the same time!</p>
Is void** an acceptable type in ANSI-C? <p>I have seen a function whose prototype is:</p> <pre><code>int myfunc(void** ppt) </code></pre> <p>This function is called in a C file as a = myfunc(mystruct **var1);</p> <p>where mystruct is typedef for one of structure we have. </p> <p>This works without any compilation errors in MSVC6.0, But when I compile it with some other C compiler, it gives an error at the place where this function is called with error message:</p> <p><strong>Argument of type mystruct ** is incompatible with parameter of type void **</strong></p> <p>The argument of myfunc() is kept as void** because it seems to be a generic malloc kind of function to be called with various structure variable types for memory allocation </p> <ol> <li>Is there any type such as void ** allowed in C standard/any C compilers?</li> <li>How do I fix this? [I tried casting the function call argument to <code>mystruct**</code>, but it didn't work]</li> </ol> <p>-AD</p>
<p>The <a href="http://c-faq.com/">comp.lang.c FAQ</a> addresses this issue in detail in <a href="http://c-faq.com/ptrs/genericpp.html">Question 4.9</a>. In short, they say <strong>it's not strictly portable</strong> to cast an arbitrary pointer-to-pointer to a <code>void **</code>; they go on to explain that "code like this may work and is sometimes recommended, but it relies on all pointer types having the same internal representation (which is common, but not universal)." They go on to explain that "any <code>void **</code> value you play with must be the address of an actual <code>void *</code> value somewhere; casts like <code>(void **)&amp;dp</code>, though they may shut the compiler up, are nonportable (and may not even do what you want)."</p> <p>So, you can safely/portably achieve the desired behavior with code like:</p> <pre><code>some_type *var1 = foo(); void *tmp_void_ptr = (void *)var1; myfunc(&amp;tmp_void_ptr); </code></pre>
Looking for a Report Designer that allows connection to a RESTful webservice <p>I'm looking for a Report Designer that will allow me to connect to a RESTful webservice. Ideally I would like one that has a royalty-free End-User Report Designer. WE will be hosting it in an ASP.NET web site. So something compatable with that would be ideal ;)</p> <p>We used to use <a href="http://www.datadynamics.com/Products/ProductOverview.aspx?Product=ARNET3" rel="nofollow">Data Dynamics Active Reports</a>. However this doesn't allow connections to webservices.</p> <p>Any help, very much appreciated.</p> <p>Thanks in advance.</p> <p>Crafty</p>
<p>I'm not sure what you mean by asking for a report generator that can connect to a web service. </p> <p>Web services aren't something you can report on. They're just a source of data. What do you want to connect to and what data are you expecting to get back?</p> <p>The problem with RESTful web services is you don't know what you're going to get back (there's no schema as with a DB table).</p> <p>The good thing about RESTful web services is you're probably going to get back some XML, and the Active Reports product you mention seems to do things with XML files.</p> <p>"ActiveReports for .NET 3.0 supports many XML-based files for data input."</p> <p>Cam you call the web services for the information you need and squirrel it away in some files (or a DB) first?</p> <p>Or are you in essence asking for something that can query a RESTful web service in some reasonably complex way and return the results of the query in some structured way that a report generator can then consume?</p> <p>Do you have specific RESTful web services in mind, and if so do you know what format they will return data in? Then your question is really about report generators that can handle that returned format, perhaps.</p> <p>Or something else and I've missed the point?</p>
Symfony app - how to add calculated fields to Propel objects? <p>What is the best way of working with calculated fields of Propel objects?</p> <p>Say I have an object "Customer" that has a corresponding table "customers" and each column corresponds to an attribute of my object. What I would like to do is: add a calculated attribute "Number of completed orders" to my object when using it on View A but not on Views B and C.</p> <p>The calculated attribute is a COUNT() of "Order" objects linked to my "Customer" object via ID.</p> <p>What I can do now is to first select all Customer objects, then iteratively count Orders for all of them, but I'd think doing it in a single query would improve performance. But I cannot properly "hydrate" my Propel object since it does not contain the definition of the calculated field(s).</p> <p>How would you approach it?</p>
<p>There are several choices. First, is to create a view in your DB that will do the counts for you, similar to my answer <a href="http://stackoverflow.com/questions/234785/#235267">here</a>. I do this for a current Symfony project I work on where the read-only attributes for a given table are actually much, much wider than the table itself. This is my recommendation since grouping columns (max(), count(), etc) are read-only anyway.</p> <p>The other options are to actually build this functionality into your model. You absolutely CAN do this hydration yourself, but it's a bit complicated. Here's the rough steps</p> <ol> <li>Add the columns to your <em>Table</em> class as protected data members.</li> <li>Write the appropriate getters and setters for these columns</li> <li>Override the hydrate method and within, populate your new columns with the data from other queries. Make sure to call parent::hydrate() as the first line</li> </ol> <p>However, this isn't much better than what you're talking about already. You'll still need <em>N</em> + 1 queries to retrieve a single record set. However, you can get creative in step #3 so that <em>N</em> is the number of calculated columns, not the number of rows returned.</p> <p>Another option is to create a custom selection method on your <em>Table</em>Peer class.</p> <ol> <li>Do steps 1 and 2 from above.</li> <li>Write custom SQL that you will query manually via the Propel::getConnection() process.</li> <li>Create the dataset manually by iterating over the result set, and handle custom hydration at this point as to not break hydration when use by the doSelect processes.</li> </ol> <p>Here's an example of this approach</p> <pre><code>&lt;?php class TablePeer extends BaseTablePeer { public static function selectWithCalculatedColumns() { // Do our custom selection, still using propel's column data constants $sql = " SELECT " . implode( ', ', self::getFieldNames( BasePeer::TYPE_COLNAME ) ) . " , count(" . JoinedTablePeer::ID . ") AS calc_col FROM " . self::TABLE_NAME . " LEFT JOIN " . JoinedTablePeer::TABLE_NAME . " ON " . JoinedTablePeer::ID . " = " . self::FKEY_COLUMN ; // Get the result set $conn = Propel::getConnection(); $stmt = $conn-&gt;prepareStatement( $sql ); $rs = $stmt-&gt;executeQuery( array(), ResultSet::FETCHMODE_NUM ); // Create an empty rowset $rowset = array(); // Iterate over the result set while ( $rs-&gt;next() ) { // Create each row individually $row = new Table(); $startcol = $row-&gt;hydrate( $rs ); // Use our custom setter to populate the new column $row-&gt;setCalcCol( $row-&gt;get( $startcol ) ); $rowset[] = $row; } return $rowset; } } </code></pre> <p>There may be other solutions to your problem, but they are beyond my knowledge. Best of luck!</p>
How do I convert big numbers to decimal? <p>0x34363932353433373538323038353135353439</p>
<p>From the Unix / cygwin command line, you can use bc.</p> <pre><code>$ bc ibase=16 34363932353433373538323038353135353439 1164362276596472215941024063897591129839055929 </code></pre> <p>There is also <a href="http://sciencesoft.at/bc/?lang=en" rel="nofollow">an online version</a>. If you want to do it in code you should use an arbitrary precision library facility, like Java's BigInteger, Perl's Math::BigInt, Tcl's math::bignum, or of the many multiple precision arithmetic libraries that are available for C, like <a href="http://gmplib.org/" rel="nofollow">GNU GMP</a>, or <a href="http://spinning-yarns.org/michael/mpi" rel="nofollow">MPI</a>.</p>
Is there an equivalent of ComboBoxRenderer for NumericUpDown? <p>I want to draw spinner controls, such as those found on a NumericUpDown, on a custom component. If I want to draw a drop-down button, I can use ComboBoxRenderer. Is there an equivalent of ComboBoxRenderer for NumericUpDown?</p>
<p>Turns out there is. See the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.visualstyles.visualstyleelement.spin.aspx" rel="nofollow">VisualStyleElement.Spin class</a>.</p>
Is SPRING.Net the best framework for Aspect Oriented Programming(AOP)? <p>Please give me the advantages and disadvantages of using the particular framework.</p> <p>Can give me examples of successes where you have used AOP in you .net applications?</p>
<p>An older post, but might help you see some of the pro/cons of products and AOP implementations.</p> <p><a href="http://ayende.com/Blog/archive/2007/07/02/7-Approaches-for-AOP-in-.Net.aspx" rel="nofollow">http://ayende.com/Blog/archive/2007/07/02/7-Approaches-for-AOP-in-.Net.aspx</a></p>
Detect when JavaScript is disabled in ASP.NET <p>In the Render method of an ASP.NET web-control, I need to alter the output of the Html based on whether JavaScript is enabled or disabled on the clients browser,</p> <p>Does anyone know the right incantation to figure that out?</p>
<p>The problem with using script to check whether javascript is enabled is that you only find that out after the script hasn't run.</p> <p>Some solutions try the opposite - they use javascript to set a value and then supply Javascript enabled controls if that value is later detected. However, this fails with javascript-sometimes-enabled tools like the Firefox NoScript plugin.</p> <p>A more robust solution is to always send the plain-HTML compatible control, and then have javascript run on page load to add the correct event handlers/extra DOM elements/etc.</p> <p>However I don't know how this fits in with the ASP.NET approach takes to controls.</p>
How do I find a user's Active Directory display name in a C# web application? <p>I'm writing a web application which uses windows authentication and I can happily get the user's login name using something like:</p> <pre><code> string login = User.Identity.Name.ToString(); </code></pre> <p>But I don't need their login name I want their DisplayName. I've been banging my head for a couple hours now...</p> <p>Can I access my organisation's AD via a web application?</p>
<p>How about this:</p> <pre><code>private static string GetFullName() { try { DirectoryEntry de = new DirectoryEntry("WinNT://" + Environment.UserDomainName + "/" + Environment.UserName); return de.Properties["fullName"].Value.ToString(); } catch { return null; } } </code></pre>
Apache/Tomcat error - wrong pages being delivered <p>This error has been driving me nuts. We have a server running Apache and Tomcat, serving multiple different sites. Normally the server runs fine, but sometimes an error happens where people are served the wrong page - <strong>the page that <em>somebody else</em> requested!</strong></p> <p>Clues:</p> <ul> <li>The pages being delivered are those that another user requested recently, and are otherwise delivered correctly. It's been known for two simultaneous requests to be swapped. As far as I can tell, none of the pages being incorrectly delivered are older than a few minutes.</li> <li>It only affects the files that are being served by Tomcat. Static files like images are unaffected.</li> <li>It doesn't happen all the time. When it does happen, it happens for everybody.</li> <li>It seems to happen at times of peak demand. However, the demand is not yet very high - it's certainly well within the bounds of what Apache can cope with.</li> <li>Restarting Tomcat fixed it, but only for a few minutes. Restarting Apache fixed it, but only for a few minutes.</li> <li>The server is running Apache 2 and Tomcat 6, using a Java 6 VM on Gentoo. The connection is with AJP13, and <code>JkMount</code> directives within <code>&lt;VirtualHost&gt;</code> blocks are correct.</li> <li>There's nothing of use in any of the log files.</li> </ul> <p><hr /></p> <p><strong>Further information:</strong></p> <p>Apache does not have any form of caching turned on. All the caching-related entries in httpd.conf and related imports say, for example:</p> <pre><code>&lt;IfDefine CACHE&gt; LoadModule cache_module modules/mod_cache.so &lt;/IfDefine&gt; </code></pre> <p>While the options for Apache don't include that flag:</p> <pre><code>APACHE2_OPTS="-D DEFAULT_VHOST -D INFO -D LANGUAGE -D SSL -D SSL_DEFAULT_VHOST -D PHP5 -D JK" </code></pre> <p>Tomcat likewise has no caching options switched on, that I can find.</p> <p><a href="http://stackoverflow.com/questions/246540/apachetomcat-error-wrong-pages-being-delivered#246566">toolkit's suggestion</a> was good, but not appropriate in this case. What leads me to believe that the error can't be within my own code is that it isn't simply a few values that are being transferred - it's the entire request, including the URL, parameters, session cookies, the whole thing. People are getting pages back saying "You are logged in as John", when they clearly aren't.</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>Based on suggestions from several people, I'm going to add the following HTTP headers to Tomcat-served pages to disable all forms of caching:</p> <pre><code>Cache-Control: no-store Vary: * </code></pre> <p>Hopefully these headers will be respected not just by Apache, but also by any other caches or proxies that may be in the way. Unfortunately I have no way of deliberately reproducing this error, so I'm just going to have to wait and see if it turns up again.</p> <p>I notice that the following headers are being included - could they be related in any way?</p> <pre><code>Connection: Keep-Alive Keep-Alive: timeout=5, max=66 </code></pre> <p><hr /></p> <p><strong>Update:</strong></p> <p>Apparently this happened again while I was asleep, but has stopped happening now I'm awake to see it. Again, there's nothing useful in the logs that I can see, so I have no clues to what was actually happening or how to prevent it.</p> <p>Is there any extra information I can put in Apache or Tomcat's logs to make this easier to diagnose?</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>Since this has happened again a couple of times, we've changed how Apache connects to Tomcat to see if it affects things. We were using <code>mod_jk</code> with a directive like this:</p> <pre><code>JkMount /portal ajp13 </code></pre> <p>We've switched now to using <code>mod_proxy_ajp</code>, like so:</p> <pre><code>ProxyPass /portal ajp://localhost:8009/portal </code></pre> <p>We'll see if it makes any difference. This error was always annoyingly unpredictable, so we can never definitively say if it's worked or not.</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>We just got the error briefly on a site that was left using <code>mod_jk</code>, while a sister site on the same server using <code>mod_proxy_ajp</code> didn't show the error. This doesn't prove anything, but it does provide evidence that swithing to <code>mod_proxy_ajp</code> may have helped.</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>We just got the error again last night on a site using <code>mod_proxy_ajp</code>, so clearly that hasn't solved it - <code>mod_jk</code> wasn't the source of the problem. I'm going to try the anonymous suggestion of turning off persistent connections:</p> <pre><code>KeepAlive Off </code></pre> <p>If that fails as well, I'm going to be desperate enough to start investigating GlassFish.</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>Dammit! The problem just came back. I hadn't seen it in a while, so I was starting to think we'd finally sorted it. I hate heisenbugs.</p>
<p>Could it be the thread-safety of your servlets?</p> <p>Do your servlets store any information in instance members.</p> <p>For example, something as simple as the following may cause thread-related issues:</p> <pre><code>public class MyServlet ... { private String action; public void doGet(...) { action = request.getParameter("action"); processAction(response); } public void processAction(...) { if (action.equals("foo")) { // send foo page } else if (action.equals("bar")) { // send bar page } } } </code></pre> <p>Because the serlvet is accessed by multiple threads, there is no guarantee that the action instance member will not be clobbered by someone elses request, and end up sending the wrong page back.</p> <p>The simple solution to this issue is to use local variables insead of instance members:</p> <pre><code>public class MyServlet ... { public void doGet(...) { String action = request.getParameter("action"); processAction(action, response); } public void processAction(...) { if (action.equals("foo")) { // send foo page } else if (action.equals("bar")) { // send bar page } } } </code></pre> <p><strong>Note: this extends to JavaServer Pages too, if you were dispatching to them for your views?</strong></p>
How to implement a singleton in C#? <p>How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.</p>
<p>If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.</p> <pre><code>public static class GlobalSomething { public static int NumberOfSomething { get; set; } public static string MangleString( string someValue ) { } } </code></pre> <p>Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.</p>
How do I tag a database component in UML? <p>In an UML component diagram, how does one tag or identify a component as a database, so that it's easily recognizable? In the old days there was the cylinder symbol for showing database but that's not part of the UML. Same goes for an application server for instance, how would that be shown?</p> <p>Are stereotypes applicable here? Can the component symbol be enhanced with graphical elements?</p>
<p>Just use the <code>&lt;&lt;database&gt;&gt;</code> for the component diagram.</p> <p>For a more detailed information check out this article: <a href="http://www.sparxsystems.com.au/resources/uml_datamodel.html" rel="nofollow">http://www.sparxsystems.com.au/resources/uml_datamodel.html</a></p>
Team foundation and 64-bit windows, can't install? <p>So is it a certified answer that you can't install Team foundation on windows 2008 64-bit?</p> <p><b>Update</b></p> <p>Is it better just do install it on windows 2003 or 2008?</p>
<p>short answer is <a href="http://blogs.msdn.com/granth/archive/2008/09/15/can-i-run-tfs-on-a-64-bit-os.aspx" rel="nofollow">no</a></p> <p>Rereading I need to make clear for double negative, read link, official is that you can't but there is a workaround if desired.</p>
ASP.NET Menu Parent Menu Item Highlighting on Hover when Flyouts are enabled <p>I have a ASP.Net Menu Control with three levels and flyouts enabled. I want to highlight the parent items (right upto the top level parent) whenever a user hovers over the menu items.</p> <p>I do not want to use a client side solution as described here: <a href="http://www.codeproject.com/KB/webforms/AspMenuParentHighlighting.aspx" rel="nofollow">http://www.codeproject.com/KB/webforms/AspMenuParentHighlighting.aspx</a></p> <p>Is there an elegant server side solution?</p> <p>Kind regards.</p>
<p>The only server side solution I can think of would be to set the client side solution on page load. </p> <p>Is there a reason that you would want to build this server side rather than client side? Because forcing an event like this to occur server side is, by definition, rather inelegant. </p>
VS2008 Express: How to save as UTF-8 all files by default? <p>Is there any way to make Visual Studio 2008 Express store all the files as UTF-8 by default?</p> <p>Thanks for your time. Best regards.</p>
<p>If you create a new file inside VS it will be UTF8 by default, but if the file is already created by other enconding you have to "Save as", and then change the enconding by pressing the down arrow in the "Save" button, and then selecting "Save with enconding..."</p>
"Simple" SQL Query <p>Each of my clients can have many todo items and every todo item has a due date.</p> <p>What would be the query for discovering the next undone todo item by due date for each file? In the event that a client has more than one todo, the one with the lowest id is the correct one.</p> <p>Assuming the following minimal schema:</p> <pre><code>clients (id, name) todos (id, client_id, description, timestamp_due, timestamp_completed) </code></pre> <p>Thank you.</p>
<p>This question is the classic <strong><em>pick-a-winner for each group</em></strong>. It gets posted about twice a day.</p> <pre><code>SELECT * FROM todos t WHERE t.timestamp_completed is null and ( SELECT top 1 t2.id FROM todos t2 WHERE t.client_id = t2.client_id and t2.timestamp_completed is null --there is no earlier record and (t.timestamp_due &gt; t2.timestamp_due or (t.timestamp_due = t2.timestamp_due and t.id &gt; t2.id) ) ) is null </code></pre>
Bookmarked page redirect <p>I recently converted a site from asp to CF. Unfortunately, alot of the old users had the "homepage" bookmarked. www.example.com/homepage.asp</p> <p>Is there a sort of catch all way I could redirect any traffic from that page to the current index.cfm?</p> <p>I would normally just delete those files, but the owner(s) wanted to keep it around for their own comparison reasons.</p> <p>Any ideas?</p> <p>Thanks</p>
<p>Put this in the old homepage.asp</p> <pre><code>&lt;%@ Language=VBScript %&gt; &lt;% Response.Status="301 Moved Permanently" Response.AddHeader "Location", "/index.cfm" %&gt; </code></pre>
Is there any difference between a GUID and a UUID? <p>I see these 2 acronyms thrown around, and I was wondering if there are any differences between a GUID and a UUID?</p>
<p>The <strong>simple answer</strong> is: <strong>no difference</strong>, they are the same thing. Treat them as a 16 byte (128 bits) value that is used as a unique value. In Microsoft-speak they are called GUIDs, but call them UUIDs when not using Microsoft-speak.</p> <p>Even the authors of the UUID specification and Microsoft claim they are synonyms:</p> <ul> <li><p>From the introduction to IETF <a href="http://tools.ietf.org/rfc/rfc4122.txt">RFC 4122</a> "<em>A Universally Unique IDentifier (UUID) URN Namespace</em>": "a Uniform Resource Name namespace for UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier)."</p></li> <li><p>From the <a href="http://www.itu.int/ITU-T/studygroups/com17/oid.html">ITU-T Recommendation X.667, ISO/IEC 9834-8:2004 International Standard</a>: "UUIDs are also known as Globally Unique Identifiers (GUIDs), but this term is not used in this Recommendation."</p></li> <li><p>And Microsoft even <a href="http://msdn.microsoft.com/en-us/library/cc246025%28v=PROT.13%29.aspx">claims</a> a GUID is specified by the UUID RFC: "In Microsoft Windows programming and in Windows operating systems, a globally unique identifier (GUID), as specified in [RFC4122], is ... The term universally unique identifier (UUID) is sometimes used in Windows protocol specifications as a synonym for GUID."</p></li> </ul> <p>But the <strong>correct answer</strong> depends on what the question means when it says "UUID"...</p> <p>The first part depends on what the asker is thinking when they are saying "UUID".</p> <p>Microsoft's claim implies that all UUIDs are GUIDs. But are all GUIDs real UUIDs? That is, is the set of all UUIDs just a proper subset of the set of all GUIDs, or is it the exact same set?</p> <p>Looking at the details of the RFC 4122, there are four different "variants" of UUIDs. This is mostly because such 16 byte identifiers were in use before those specifications were brought together in the creation of a UUID specification. From section 4.1.1 of <a href="http://tools.ietf.org/rfc/rfc4122.txt">RFC 4122</a>, the four <em>variants</em> of UUID are:</p> <ol> <li>Reserved, Network Computing System backward compatibility</li> <li>The <em>variant</em> specified in RFC 4122 (of which there are five sub-variants, which are called "versions")</li> <li>Reserved, Microsoft Corporation backward compatibility</li> <li>Reserved for future definition.</li> </ol> <p>According to RFC 4122, all UUID <em>variants</em> are "real UUIDs", then all GUIDs are real UUIDs. To the literal question "is there any difference between GUID and UUID" the answer is definitely no for RFC 4122 UUIDs: <strong>no difference</strong> (but subject to the second part below).</p> <p>But not all GUIDs are <em>variant</em> 2 UUIDs (e.g. Microsoft COM has GUIDs which are variant 3 UUIDs). If the question was "is there any difference between GUID and variant 2 UUIDs", then the answer would be yes -- they can be different. Someone asking the question probably doesn't know about <em>variants</em> and they might be only thinking of <em>variant</em> 2 UUIDs when they say the word "UUID" (e.g. they vaguely know of the MAC address+time and the random number algorithms forms of UUID, which are both <em>versions</em> of <em>variant</em> 2). In which case, the answer is <strong>yes different</strong>.</p> <p>So the answer, in part, depends on what the person asking is thinking when they say the word "UUID". Do they mean variant 2 UUID (because that is the only variant they are aware of) or all UUIDs?</p> <p>The second part depends on which specification being used as the definition of UUID.</p> <p>If you think that was confusing, read the <a href="http://www.itu.int/ITU-T/studygroups/com17/oid.html">ITU-T X.667 ISO/IEC 9834-8:2004</a> which is supposed to be aligned and fully technically compatible with <a href="http://tools.ietf.org/rfc/rfc4122.txt">RFC 4122</a>. It has an extra sentence in Clause 11.2 that says, "All UUIDs conforming to this Recommendation | International Standard shall have variant bits with bit 7 of octet 7 set to 1 and bit 6 of octet 7 set to 0". Which means that only <em>variant</em> 2 UUID conform to that Standard (those two bit values mean <em>variant</em> 2). If that is true, then not all GUIDs are conforming ITU-T/ISO/IEC UUIDs, because conformant ITU-T/ISO/IEC UUIDs can only be <em>variant</em> 2 values.</p> <p>Therefore, the real answer also depends on which specification of UUID the question is asking about. Assuming we are clearly talking about all UUIDs and not just variant 2 UUIDs: there is <strong>no difference</strong> between GUID and IETF's UUIDs, but <strong>yes difference</strong> between GUID and <em>conforming</em> ITU-T/ISO/IEC's UUIDs!</p> <p><strong>Binary encodings could differ</strong></p> <p>When encoded in binary (as opposed to the human-readable text format), the GUID <a href="http://en.wikipedia.org/wiki/Globally_unique_identifier">may be stored</a> in a structure with four different fields as follows. This format differs from the <a href="http://tools.ietf.org/html/rfc4122">UUID standard</a> only in the byte order of the first 3 fields.</p> <pre><code>Bits Bytes Name Endianness Endianness (GUID) RFC 4122 32 4 Data1 Native Big 16 2 Data2 Native Big 16 2 Data3 Native Big 64 8 Data4 Big Big </code></pre>
How to debug ORA-01775: looping chain of synonyms? <p>I'm familiar with the issue behind ORA-01775: looping chain of synonyms, but is there any trick to debugging it, or do I just have to "create or replace" my way out of it? </p> <p>Is there a way to query the schema or whatever to find out what the current definition of a public synonym is? </p> <p>Even more awesome would be a graphical tool, but at this point, anything would be helpful.</p>
<p>As it turns out, the problem wasn't actually a looping chain of synonyms, but the fact that the synonym was pointing to a view that did not exist.</p> <p>Oracle apparently errors out as a looping chain in this condition.</p>
Looking for suggestions for building a secure REST API within Ruby on Rails <p>I'm getting started on building a REST API for a project I'm working on, and it led me to do a little research as to the best way to build an API using RoR. I find out pretty quickly that by default, models are open to the world and can be called via URL by simply putting a ".xml" at the end of the URL and passing appropriate parameters.</p> <p>So then the next question came. How do I secure my app to prevent unauthorized changes? In doing some research I found a couple articles talking about <code>attr_accessible</code> and <code>attr_protected</code> and how they can be used. The particular URL I found talking about these was posted back in May of '07 (<a href="http://railscasts.com/episodes/26-hackers-love-mass-assignment">here</a>). </p> <p>As with all things ruby, I'm sure that things have evolved since then. So my question is, is this still the best way to secure a REST API within RoR?</p> <p>If not what do you suggest in either a "new project" or an "existing project"scenario?</p>
<p>There are several schemes for authenticating API requests, and they're different than normal authentication provided by plugins like restful_authentication or acts_as_authenticated. Most importantly, clients will not be maintaining sessions, so there's no concept of a login.</p> <p><strong>HTTP Authentication</strong></p> <p>You can use basic HTTP authentication. For this, API clients will use a regular username and password and just put it in the URL like so:</p> <pre><code>http://myusername:mypass@www.someapp.com/ </code></pre> <p>I believe that restful_authentication supports this out of the box, so you can ignore whether or not someone is using your app via the API or via a browser.</p> <p>One downside here is that you're asking users to put their username and password in the clear in every request. By doing it over SSL, you can make this safe.</p> <p>I don't think I've ever actually seen an API that uses this, though. It seems like a decently good idea to me, especially since it's supported out of the box by the current authentication schemes, so I don't know what the problem is.</p> <p><strong>API Key</strong></p> <p>Another easy way to enable API authentication is to use API keys. It's essentially a username for a remote service. When someone signs up to use your API, you give them an API key. This needs to be passed with each request.</p> <p>One downside here is that if anyone gets someone else's API key, they can make requests as that user. I think that by making all your API requests use HTTPS (SSL), you can offset this risk somewhat.</p> <p>Another downside is that users use the same authentication credentials (the API key) everywhere they go. If they want to revoke access to an API client their only option is to change their API key, which will disable all other clients as well. This can be mitigated by allowing users to generate multiple API keys.</p> <p><strong>API Key + Secret Key signing</strong></p> <p><em>Deprecated(sort of) - see OAuth below</em></p> <p>Significantly more complex is signing the request with a secret key. This is what Amazon Web Services (S3, EC2, and such do). Essentially, you give the user 2 keys: their API key (ie. username) and their secret key (ie. password). The API key is transmitted with each request, but the secret key is not. Instead, it is used to sign each request, usually by adding another parameter.</p> <p>IIRC, Amazon accomplishes this by taking all the parameters to the request, and ordering them by parameter name. Then, this string is hashed, using the user's secret key as the hash key. This new value is appended as a new parameter to the request prior to being sent. On Amazon's side, they do the same thing. They take all parameters (except the signature), order them, and hash using the secret key. If this matches the signature, they know the request is legitimate.</p> <p>The downside here is complexity. Getting this scheme to work correctly is a pain, both for the API developer and the clients. Expect lots of support calls and angry emails from client developers who can't get things to work.</p> <p><strong>OAuth</strong></p> <p>To combat some of the complexity issues with key + secret signing, a standard has emerged called <a href="http://oauth.net/">OAuth</a>. At the core OAuth is a flavor of key + secret signing, but much of it is standardized and has been included into <a href="http://oauth.net/code/">libraries for many languages</a>.</p> <p>In general, it's much easier on both the API producer and consumer to use OAuth rather than creating your own key/signature system.</p> <p>OAuth also inherently segments access, providing different access credentials for each API consumer. This allows users to selectively revoke access without affecting their other consuming applications.</p> <p>Specifically for Ruby, there is an <a href="http://oauth.rubyforge.org/">OAuth gem</a> that provides support out of the box for both producers and consumers of OAuth. I have used this gem to build an API and also to consume OAuth APIs and was very impressed. If you think your application needs OAuth (as opposed to the simpler API key scheme), then I can easily recommend using the OAuth gem.</p>
Load multiple external websites into one webpage via re-using ONE IFrame + Ajax <p>I am trying to embed multiple external websites into one web page. Using an IFRAME works ok, but once you get past 10 embedded iframes, the memory fottprint starts to get too big.</p> <p>So I was thinking, is it possible via ajax/javascript, to re-use the same iframe to load the collection of websites one after enother, and display the results in a div on the main webpage? Or is this explicitly blocked for security reasons?</p> <p>EDIT: I don't want to go the screen scraping route, as I was planning to make this a semi public site, and I don't want to incur all the bandwidth on my server and would rather have that done on the client, if it is possible.</p>
<p>You are trying to use a hammer to put screws in the wall. Maybe some will go, but it won't be pretty. Your best option would be either a screen scraper or web services in order to retrieve the data from the external sites. Perhaps include more details about the situation such as, are the external sites your own. Do they offer syndication of their content that you are after. Are offline services available to you so you can consume this content?</p>
When using keytool to generate a CSR file, does it have to be generated on the hosting server? <p>I was under the impression that I could run it on any machine, but a guy from our hosting company is saying that the csr has to be generated on the server hosting the site.</p> <p>Can anyone clear this one up for me?</p> <p>Thanks.</p>
<p>The bottom line is you do not need to generate CSRs on the server hosting an SSL certificate. A CSR is a CSR and you could actually generate it using something like OpenSSL and then import both the key and certificate once it is created into the keystore. The problem is that they probably don't understand now to get the key into the keychain. See if this <a href="http://conshell.net/wiki/index.php/Keytool_to_OpenSSL_Conversion_tips" rel="nofollow">KeyTool and OpenSSL tips</a> helps.</p>
How to (de)serialise JSON data in Silverlight using a different name to member variable <p>I have the following members defined in a class that I'm trying to deserialise:</p> <pre><code>[DataMemberAttribute(Name = "cust_title")] public String Title { get; set; } [DataMemberAttribute(Name = "cust_description")] public String Description { get; set; } </code></pre> <p>For some reason, the deserialisation fails (it seems to ignore the DataMemberAttribute).</p> <p>Does anyone know how to get this working?</p>
<p>I've just found the answer out by a bit of trial and error. In order to use the <code>[DataMemberAttribute]</code> you must also put <code>[DataContractAttribute]</code> above your class definition:</p> <pre><code>[DataContractAttribute] public class MyClass { [DataMemberAttribute(Name="test_test")] public String Test { get; set; } } </code></pre>
Available Build Tools (make, etc)? <p>There's a lot of questions on here regarding various niche build needs (.NET, continuous integration, etc) but, of course, my niche need is different.</p> <p>Rather than asking a very specific question right now, I'd like a survey of available build tools (such as make, ant, etc) so I can ask a follow up question more intelligently if needed.</p> <p>In your answer, please include:</p> <ul> <li><strong>ONE</strong> build tool</li> <li>Link to the main page about that tool</li> <li>If you know some pros and cons (ie, runs on windows with cygwin, or .NET specific, etc) then list some (not required - the name and link are required)</li> </ul> <p>If your build tool is already in an answer, comment on it adding pros/cons/limitations/experiences. Feel free to add as many answers as you like as long as they don't already exist - but don't put several build tools into one answer.</p> <p>Please be aware that if you duplicate answers you may be downvoted - add additional information about a given build in the comments. Ideally these comments will be incorporated into the answer over time.</p>
<p><a href="http://www.scons.org/" rel="nofollow">SCons</a></p> <p>Build scripts are Python scripts. Supposed to work on Linux, Windows, Mac OS X.</p>
Matlab copy constructor <p>Is there a better way to implement copy construcor for matlab for a handle derived class other than adding a constructor with one input and explicitly copying its properties?</p> <pre><code>obj.property1 = from.property1; obj.property2 = from.property2; </code></pre> <p>etc.</p> <p>Thanks, Dani</p>
<p>If you want a quick-and-dirty solution that assumes all properties can be copied, take a look at the PROPERTIES function. Here's an example of a class that automatically copies all properties:</p> <pre><code>classdef Foo &lt; handle properties a = 1; end methods function F=Foo(rhs) if nargin==0 % default constructor F.a = rand(1); else % copy constructor fns = properties(rhs); for i=1:length(fns) F.(fns{i}) = rhs.(fns{i}); end end end end end </code></pre> <p>and some test code:</p> <pre><code>f = Foo(); [f.a Foo(f).a] % should print 2 floats with the same value. </code></pre>
Images & Hyperlink Borders - Ghost 1px x 1px Border <p>I've an image that is wrapped in an anchor tag that, through jQuery, triggers an action somewhere else on the page. When I click on the image, two tiny 1px by 1px boxes show up in the upper and lower left corners of the image.</p> <p>My CSS styles explicitly state no borders for images: <code>a,img { border: 0; }</code></p> <p>It also seems to only happen in Firefox 3. Anyone else had this issue?</p> <hr> <p>Here's a screenshot of the left part of the image (the graphic has a white background):</p> <p><img src="http://neezer.net/img/ss.png" alt="alt text"></p> <p>It's not the background, or the border of any other element. I checked.</p>
<p>Is your anchor tag under or overlining?</p> <p>Set the a and a:hover in that situation to text-decoration: none.</p> <p>Happened to me, and the reason it was two tiny boxes is because the width of the element didn't quite extend, or something.</p> <p>Good luck!</p> <p>D'oh: I see it's upper- and lower- LEFT boxes. Might be something else, like background or border of containing element peeking through.</p>
ASP.NET aspx page code runs impersonated though impersonation is disabled <p>I have a blank test app created in VS 2005 as ASP.NET application. <a href="http://msdn.microsoft.com/en-us/library/ms998351.aspx" rel="nofollow">MSDN says</a> that </p> <blockquote> <p>By default, ASP.NET does not use impersonation, and your code runs using the ASP.NET application's process identity.</p> </blockquote> <p>And I have the following web.config</p> <pre><code>&lt;configuration&gt; &lt;appSettings/&gt; &lt;connectionStrings/&gt; &lt;system.web&gt; &lt;!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --&gt; &lt;compilation debug="true" defaultLanguage="c#" /&gt; &lt;!-- The &lt;authentication&gt; section enables configuration of the security authentication mode used by ASP.NET to identify an incoming user. --&gt; &lt;authentication mode="Windows"/&gt; &lt;identity impersonate="false"/&gt; &lt;!-- The &lt;customErrors&gt; section enables configuration of what to do if/when an unhandled error occurs during the execution of a request. Specifically, it enables developers to configure html error pages to be displayed in place of a error stack trace. &lt;customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"&gt; &lt;error statusCode="403" redirect="NoAccess.htm" /&gt; &lt;error statusCode="404" redirect="FileNotFound.htm" /&gt; &lt;/customErrors&gt; --&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>So it seem impersonation is disabled just like <a href="http://msdn.microsoft.com/en-us/library/ms998351.aspx" rel="nofollow">the article</a> is suggesting.</p> <p>My aspx is blank default and the codebehind is</p> <pre><code>namespace TestWebapp { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { System.Diagnostics.Debug.WriteLine(String.Format("Before1: Current Princupal = {0}", Thread.CurrentPrincipal.Identity.Name)); WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(IntPtr.Zero); try { int a = 0; System.Diagnostics.Debug.WriteLine(String.Format("After: Current Princupal = {0}", Thread.CurrentPrincipal.Identity.Name)); } finally { ctx.Undo(); } } } } </code></pre> <p>When I reload the page I get the following debug output:</p> <blockquote> <p>[5288] Before1: Current Princupal = DOMAIN\User [5288] After: Current Princupal = DOMAIN\User</p> </blockquote> <p>Output is the same with</p> <pre><code>&lt;identity impersonate="false"/&gt; </code></pre> <p>The web site uses Default Application Pool and the pool is set up to use NETWORK SERVICE account for its worker processes. I'm sure the application uses the web.config it should use and the w3p.exe worker process is running under NETWORK SERVICE.</p> <p>What can be wrong in this case?</p> <p>Thanks!</p> <p>@Edit: Rob, thanks for the tip! The $user shortcut shows me that everything is happening as I expect: with impersonation on I have the process running user NT AUTHORITY\NETWORK SERVICE and the thread has DOMAIN\User before WindowsIdentity.Impersonate(IntPtr.Zero) and "No Token. Thread not impersonating." after. But Thread.CurrentPrincipal.Identity.Name and HttpContext.Current.User.Identity.Name still give me DOMAIN\User in both places.</p> <p>@Edit: I've found out that to get Thread.CurrentPrincipal and HttpContext.Current.User changed I have to manually do it:</p> <pre><code>Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); HttpContext.Current.User = Thread.CurrentPrincipal; </code></pre> <p>I'm not sure what's the point here, but anyway. I now have a problem with sharepoint shared services manage user profile permission but that's another question.</p>
<p>Seems odd, A few things to try:</p> <ul> <li>While in on a breakpoint in Debug type $user in a watch window, that will show you the process and thread identities.</li> <li><p>Your use of impersonate is incorrect, try this code:</p> <pre><code>// Declare the logon types as constants const long LOGON32_LOGON_INTERACTIVE = 2; const long LOGON32_LOGON_NETWORK = 3; // Declare the logon providers as constants const long LOGON32_PROVIDER_DEFAULT = 0; const long LOGON32_PROVIDER_WINNT50 = 3; const long LOGON32_PROVIDER_WINNT40 = 2; const long LOGON32_PROVIDER_WINNT35 = 1; [DllImport("advapi32.dll", EntryPoint = "LogonUser")] private static extern bool LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); public static WindowsImpersonationContext ImpersonateCurrentUserBegin(System.Net.NetworkCredential credential) { WindowsImpersonationContext impersonationContext = null; if (credential == null || credential.UserName.Length == 0 || credential.Password.Length == 0 || credential.Domain.Length == 0) { throw new Exception("Incomplete user credentials specified"); } impersonationContext = Security.Impersonate(credential); if (impersonationContext == null) { return null; } else { return impersonationContext; } } public static void ImpersonateCurrentUserEnd(WindowsImpersonationContext impersonationContext) { if (impersonationContext != null) { impersonationContext.Undo(); } } </code></pre></li> </ul>
Retrieving python module path <p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
<pre><code>import a_module print a_module.__file__ </code></pre> <p>Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do</p> <pre><code>import os path = os.path.dirname(amodule.__file__) </code></pre> <p>You can also try</p> <pre><code>path = os.path.abspath(amodule.__file__) </code></pre> <p>To get the directory to look for changes.</p>
Override Default Constructor of Partial Class with Another Partial Class <p>I don't think this is possible, but if is then I need it :)</p> <p>I have a auto-generated proxy file from the wsdl.exe command line tool by Visual Studio 2008.</p> <p>The proxy output is partial classes. I want to override the default constructor that is generated. I would rather not modify the code since it is auto-generated.</p> <p>I tried making another partial class and redefining the default constructor, but that doesn't work. I then tried using the override and new keywords, but that doesn't work.</p> <p>I know I could inherit from the partial class, but that would mean I'd have to change all of our source code to point to the new parent class. I would rather not have to do this.</p> <p>Any ideas, work arounds, or hacks? </p> <pre><code>//Auto-generated class namespace MyNamespace { public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol { public MyWebService() { string myString = "auto-generated constructor"; //other code... } } } //Manually created class in order to override the default constructor namespace MyNamespace { public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol { public override MyWebService() { //this doesn't work string myString = "overridden constructor"; //other code... } } } </code></pre>
<p>I had a similar prolem, with my generated code being created by a dbml file (I'm usng Linq-to-SQL classes).</p> <p>In the generated class it calls a partial void called OnCreated() at the end of the constructor.</p> <p>Long story short, if you want to keep the important constructor stuff the generated class does for you (which you probably should do), then in your partial class create the following:</p> <pre><code>partial void OnCreated() { // Do the extra stuff here; } </code></pre>
Is there a free Visual Studio addin for Nunit? <p>I'm cheap and don't want to pay for ReSharper or TestDriven.NET, is there a free visual Studio addin for NUnit?</p>
<p>You can create a blank project (Choose console application for example) and in the property of the project you can select DEBUG tag and select "Start External Program". Put the path of Nunit. Than, in the start option, the command line arguments select the DLL that contain all your test (mine is always in the nunit\bin...). Than select "enable unmanaged code debugging" and you will be able to start the projet inside VS and even use the debugger step-by-step.</p> <p>This is a free solution.</p>
Lisp DO variable syntax reasoning <p>In Peter Seibel's <em>Practical Common Lisp</em>, he gives this example:</p> <pre><code>(do ((nums nil) (i 1 (1+ i))) ((&gt; i 10) (nreverse nums)) (push i nums)) </code></pre> <p>I can see how it works, using nums inside the loop but not giving it a step-form. Why would you put nums in the variable-definition rather than do this:</p> <pre><code>(let (nums) (do ((i 1 (+ i 1))) ((&gt; i 10) (nreverse nums)) (push i nums))) </code></pre> <p>I'm sure there's a good reason, but I don't get it yet.</p>
<p>Because it's convenient and saves indentation. Furthermore, the accumulator conceptually belongs to the loop, so why not put it there?</p>
Using "this" with jQuery Selectors <p>I have some HTML that looks like this:</p> <pre><code>&lt;ul class="faq"&gt; &lt;li class="open"&gt; &lt;a class="question" href=""&gt;This is my question?&lt;/a&gt; &lt;p&gt;Of course you can, it will be awesome. &lt;/p&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Using CSS I'm setting the 'p' tag to display:none;. I want to use jQuery to display or hide the 'p' tag when the anchor is clicked, but I'm having some troubles with the sibling selector. </p> <p>Just trying to get the selector working, I tried:</p> <pre><code>$("a.question").click(function () { $(this + " ~ p").css("background-color", "red"); }); </code></pre> <p>to test it out. Seemingly, the sibling selector can't really be used like that, and as I'm completely new to jQuery I don't know the appropriate means to make that happen. </p> <p>Thanks in advance!</p>
<p>Try using: </p> <pre><code>$(this).siblings('p').css() </code></pre>
Config values in DB or File? <p>I have some configuration values for an asp.net web app. They will be maintained by a system admin once the system goes live. Should I store these values in the database or in a config file? Is there a best practice for this sort of thing?</p>
<p>It's easy and convenient to create a robust interface to edit the values in the database.</p> <p>It's less easy to create a good one for the config file.</p> <p>So I would usually you want to store everything which you would like your users/administrators to be able to edit later in the database. Everything which only needs to be touched during serious changes like re-installation etc is better off in the config file.</p>
How do I change the locale that JasperReports uses? <p>The windows installed on my machine has the locale <code>en_AU</code> and that's what JasperReports uses. I already tried changing the locale of all users, including the Administrator but it still uses <code>en_AU</code>.</p> <p>How can I change that locale? Is it possible to change the <code>REPORT_LOCALE</code> parameter on my report?</p>
<p>The locale is set during execution, not in the JRXML.</p> <p>Using Java, set the <code>REPORT_LOCALE</code> parameter for the report's parameter map. For example:</p> <pre><code>InputStream reportTemplate = getReportTemplate(); JRDataSource dataSource = getDataSource(); java.util.Map parameters = getParameters(); java.util.Locale locale = new Locale( "en", "US" ); parameters.put( JRParameter.REPORT_LOCALE, locale ); JasperFillManager.fillReport( reportTemplate, parameters, dataSource ); </code></pre> <p>Using Jaspersoft Studio, open the project properties dialog to the <strong>Report Execution</strong> area:</p> <p><a href="http://i.stack.imgur.com/DRjFS.png" rel="nofollow"><img src="http://i.stack.imgur.com/DRjFS.png" alt="Project Properties"></a></p> <p>Using iReport, set the report locale in the Options window under the "Report execution options" section in the General tab. This will set the report locale when run.</p>
Finding composite numbers <p>I have a range of random numbers. The range is actually determined by the user but it will be up to 1000 integers. They are placed in this:</p> <pre><code>vector&lt;int&gt; n </code></pre> <p>and the values are inserted like this:</p> <pre><code>srand(1); for (i = 0; i &lt; n; i++) v[i] = rand() % n; </code></pre> <p>I'm creating a separate function to find all the non-prime values. Here is what I have now, but I know it's completely wrong as I get both prime and composite in the series.</p> <pre><code>void sieve(vector&lt;int&gt; v, int n) { int i,j; for(i = 2; i &lt;= n; i++) { cout &lt;&lt; i &lt;&lt; " % "; for(j = 0; j &lt;= n; j++) { if(i % v[j] == 0) cout &lt;&lt; v[j] &lt;&lt; endl; } } } </code></pre> <p>This method typically worked when I just had a series of numbers from 0-1000, but it doesn't seem to be working now when I have numbers out of order and duplicates. Is there a better method to find non-prime numbers in a vector? I'm tempted to just create another vector, fill it with n numbers and just find the non-primes that way, but would that be inefficient?</p> <p>Okay, since the range is from 0-1000 I am wondering if it's easier to just create vector with 0-n sorted, and then using a sieve to find the primes, is this getting any closer?</p> <pre><code>void sieve(vector&lt;int&gt; v, BST&lt;int&gt; t, int n) { vector&lt;int&gt; v_nonPrime(n); int i,j; for(i = 2; i &lt; n; i++) v_nonPrime[i] = i; for(i = 2; i &lt; n; i++) { for(j = i + 1; j &lt; n; j++) { if(v_nonPrime[i] % j == 0) cout &lt;&lt; v_nonPrime[i] &lt;&lt; endl; } } } </code></pre>
<p>In this code:</p> <pre><code>if(i % v[j] == 0) cout &lt;&lt; v[j] &lt;&lt; endl; </code></pre> <p>You are testing your index to see if it is divisible by v[j]. I think you meant to do it the other way around, i.e.:</p> <pre><code>if(v[j] % i == 0) </code></pre> <p>Right now, you are printing random divisors of i. You are not printing out random numbers which are known not to be prime. Also, you will have duplicates in your output, perhaps that is ok.</p>
What are good ways to design or diagram state? <p>The issue that prompted me to ask this is a web form that was not persisting data the way I expected it to. That's vague, but the point is, what do you like to do to model state, flow of data, and so forth?</p>
<p>I'll second the whiteboard answer and add that explaining what is <em>supposed</em> to be happening, following by verbalizing what the the code is <em>actually</em> doing, along with a basic graphic is hugely helpful for any project.</p>
Bash script, match on dates like? <p>I'm writing a script to remove some build artifacts older than 1 week. </p> <p>The files have names in the form <em>artifact-1.1-200810391018.exe</em>.</p> <p>How do I go about removing only the files that are greater than 1 week old, excluding the time in hours and minutes at the end of the date-time-stamp?</p> <p>Currently it is removing all of the files in the directory.</p> <pre><code>#!/bin/sh NIGHTLY_LOCATIONS=( "/foo" "/bar" ) ARTIFACT_PREFIX="artifact-*-" NUM_TO_KEEP=7 for home in $(seq 0 $((${#NIGHTLY_LOCATIONS[@]} - 1))); do echo "Removing artifacts for" ${NIGHTLY_LOCATIONS[$location]} for file in `find ${NIGHTLY_LOCATIONS[$location]} -name "$ARTIFACT_PREFIX*"`; do keep=true for day in $(seq 0 $((${NUM_TO_KEEP} - 1))); do date=`date --date="$day days ago" +%Y%m%d` echo $(basename $file ".exe") " = " $ARTIFACT_PREFIX$date if [ "$(basename $file ".exe")" != "$ARTIFACT_PREFIX$date" ]; then keep=false fi done if [ !$keep ]; then echo "Removing file" rm -f $file fi done done </code></pre>
<p>You mean, something along the line of:</p> <pre><code>find /path/to/files -name "artifact*" -type f -mtime +7 -exec rm {} \; </code></pre> <p>?</p>
Netbeans GUI Designer & Fixed-Size Application Panels <p>I'm having a problem, creating a fixed-size overall panel for a touchscreen GUI application that has to take up the entire screen. In a nutshell, the touchscreen is 800 x 600 pixels, and therefore I want the main GUI panel to be that size.</p> <p>When I start a new GUI project in NetBeans, I set the properties of the main panel for min/max/preferred size to 800 x 600, and the panel within the 'Design' view changes size. However, when I launch the app, it is resized to the original default size.</p> <p>Adding this code after initComponents() does not help:</p> <pre><code>this.mainPanel.setSize(new Dimension(800,600)); this.mainPanel.setMaximumSize(new Dimension(800,600)); this.mainPanel.setMinimumSize(new Dimension(800,600)); this.mainPanel.repaint(); </code></pre> <p>I've peeked into all of the resource files and cannot seem to find values that would override these (which seems somewhat impossible anyway, given that I'm setting them after initComponents() does its work). I'm using the FreeDesign layout, because I wanted complete control over where I put things.</p> <p>I suspect the layout manager is resizing things based upon how many widgets I have on the screen, because different prototyped screens come in at differing sizes. </p> <p>Help is appreciated!</p>
<p>Have you tried <a href="http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html" rel="nofollow">java full screen mode</a>?</p>
Does the concept of shared sessions exist in ASP.NET? <p>I am working on a web application (ASP.NET) game that would consist of a single page, and on that page, there would be a game board akin to Monopoly. I am trying to determine what the best architectural approach would be. The main requirements I have identified thus far are:</p> <ul> <li>Up to six users share a single game state object.</li> <li>The users need to keep (relatively) up to date on the current state of the game, i.e. whose turn it is, what did the active user just roll, how much money does each other user have, etc.</li> </ul> <p>I have thought about keeping the game state in a database, but it seems like overkill to keep updating the database when a game state object (say, in a cache) could be kept up to date. For example, the flow might go like this:</p> <ol> <li>Receive request for data from a user.</li> <li>Look up data in database. Create object from that data.</li> <li>Verify user has permissions to perform request based on the game's state (i.e. make sure it's really their turn or have enough money to buy that property).</li> <li>Update the game object.</li> <li>Write the game object back to the database.</li> <li>Repeat for every single request.</li> </ol> <p><em>Consider that a single server would be serving several concurrent games.</em></p> <ol> <li>I have thought about using AJAX to make requests to an an ASP.NET page.<br></li> <li>I have thought about using AJAX requests to a web service using silverlight.<br></li> <li>I have thought about using WCF duplex channels in silverlight.</li> </ol> <p>I can't figure out what the best approach is. All seem to have their drawbacks. Does anyone out there have experience with this sort of thing and care to share those experiences? Feel free to ask your own questions if I am being too ambiguous! Thanks.</p> <p><strong>Update: Does anyone have any suggestions for how to implement this connection to the server based on the three options I mention above?</strong></p>
<p>You could use the ASP.Net Cache or the Application state to store the game object since these are shared between users. The cache would probably be the best place since objects can be removed from it to save memory. </p> <p>If you store the game object in cache using a unique key you can then store the key in each visitors Session and use this to retrieve the shared game object. If the cache has been cleared you will recreate the object from the database. </p>
Is there something between a normal user account and root? <p>I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and the debugger as root (double-ugh). Is there a nice way for the end-user to run these under a non-root account? I strongly dislike the size of the attack surface presented by GTK, wxPython, Python, and my application when it runs as root.</p> <p>I have looked into capabilities, but they look half-baked and I'm not sure if I'd be able to use them in Python, especially if they are on a thread basis. The only option I haven't explored is a daemon that has the setuid bit set and does all the root-type stuff on behalf of the UI. I'm hesitant to introduce that complexity this early in the project, as running as root is not a dealbreaker for the users.</p>
<p>Your idea about the daemon has much merit, despite the complexity it introduces. As long as the actions don't require some user interface interaction <em>as root</em>, a daemon allows you to control what operations are allowed and disallowed.</p> <p>However, you can use SUDO to create a controlled compromise between ROOT and normal users... simply grant SUDO access to the users in question for the specific tools they need. That reduces the attack surface by allowing only "permitted" root launches.</p>
VB6 Editor changing case of variable names! <p>I'm not much of a Visual Basic person, but I am tasked with maintaining an old VB6 app. Whenever I check out a file, the editor will replace a bunch of the uppercase variable names with lowercase automatically. How can I make this stop!? I don't want to have to change them all back, and it's a pain to have these changes show up in SourceSafe "Differences" when I'm trying to locate the REAL differences.</p> <p>It is changing it automatically in the definition, too: Dim C as Control becomes Dim c as Control. Dim X&amp; becomes Dim x&amp;. But it doesn't do it all the time; for example, three lines down from Dim x&amp;, there's a Dim Y&amp;, uppercase, which it did not change. Why's it do this to me?</p>
<p>Continuing from <a href="http://stackoverflow.com/questions/248760/vb6-editor-changing-case-of-variable-names#248773">DJ's answer</a>...</p> <p>And it won't only change the case of variables in the same scope either.</p> <p>It will change the case of all variables with the same name in your entire project. So even if they're declared in uppercase in one place, another module might have different variables using the same variable names in lowercase, causing all variables in your project to change to lowercase, depending on which of the declarations was loaded (?) or edited last.</p> <p>So the reason your C and X variables are changing case, while the Y isn't, is probably because C and X are declared somewhere else in your project too, but in lowercase, while Y isn't.</p> <p>There's another mention of it <a href="http://www.programmingtalk.com/showthread.php?t=47839">here</a>, where they mostly seem concerned with such variable names conflicting when case is being used to differentiate local from global variables. They end up going for prefixes instead.</p> <p>The only alternative I can think of is to use some other editor with VB6-highlighting capabilities to do your editing...</p>
How can I enable set the timeout on file uploads in SWF to greater than 3 min? <p>I'm using SWFUpload to handle file uploads and have run into a problem where any file upload >= 3 min will time out. As far as I can tell, Apache and PHP are configured properly to handle large files. Are there any settings with Flash that might affect this? Does Flash have some sort of timeout value I could change?</p>
<p>If the PHP script is timing out, then you can adjust the php time_limit by calling set_time_limit(int seconds). If you set it equal to -1 then the script will execute indefinitely, if that's what you want / need.</p> <p>If the Flash is timing out, you might want to take a look at the following:</p> <p><a href="http://www.aflax.org/forums/topic.php?id=38" rel="nofollow">http://www.aflax.org/forums/topic.php?id=38</a></p> <p><a href="http://www.kirupa.com/forum/archive/index.php/t-262299.html" rel="nofollow">http://www.kirupa.com/forum/archive/index.php/t-262299.html</a></p>
Python: using a recursive algorithm as a generator <p>Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences.</p> <p>Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one:</p> <pre><code>def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation </code></pre> <p>(Please don't care about inefficiency, this is only an example.)</p> <p>Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list:</p> <pre><code>def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation </code></pre> <p>This code does <em>not</em> work (the function behaves like an empty generator).</p> <p>Am I missing something? Is there a way to turn the above recursive algorithm into a generator <em>without replacing it with an iterative one</em>?</p>
<pre><code>def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:], prefix+string[i]): yield perm </code></pre> <p>Or without an accumulator:</p> <pre><code>def getPermutations(string): if len(string) == 1: yield string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:]): yield string[i] + perm </code></pre>
Shortcut for commenting CSS in VS 2008 <p>When I press the standard Ctrl + E, C (an other variants) in VS2008 whilst editing a CSS file, it says that command is not available. How do I setup a shortcut to apply a plain old /* */ comment to selected text in VS? Thanks</p>
<p>Within Visual Studio, hit Alt-F11 to open the Macro IDE and add a new module by right-clicking on MyMacros and selecting Add|Add Module...</p> <p>Paste the following in the source editor:</p> <pre><code>Imports System Imports EnvDTE Imports EnvDTE80 Imports EnvDTE90 Imports System.Diagnostics Public Module CommentCSS Sub CommentCSS() Dim selection As TextSelection selection = DTE.ActiveDocument.Selection Dim selectedText As String selectedText = selection.Text If selectedText.Length &gt; 0 Then selection.Text = "/*" + selectedText + "*/" End If End Sub End Module </code></pre> <p>You can create a keyboard shortcut by going to Tools|Options... and selecting <strong>Keyboard</strong> under the <strong>Environment</strong> section in the navigation on the left. Select your macro and assign any shortcut you like. </p> <p>You can also add your macro to a menu or toolbar by going to Tools|Customize... and selecting the <strong>Macros</strong> section in the navigation on the left. Once you locate your macro in the list, you can drag it to any menu or toolbar, where it its text or icon can be customized to whatever you want.</p>
Summarize aggregated data <p>I have a table like as follows:</p> <pre> SoftwareName Count Country Project 15 Canada Visio 12 Canada Project 10 USA Visio 5 USA </pre> <p>How do I query it to give me a summary like...</p> <pre> SoftwareName Canada USA Total Project 15 10 25 Visio 12 5 17 </pre> <p>How to do in T-SQL?</p>
<pre><code>SELECT SoftwareName, SUM( CASE Country WHEN 'Canada' THEN [Count] ELSE 0 END ) AS Canada, SUM( CASE Country WHEN 'USA' THEN [Count] ELSE 0 END ) AS USA, SUM( [Count] ) AS Total FROM [Table] GROUP BY SoftwareName; </code></pre>
How do I make UITableViewCellAccessoryDisclosureIndicator visible in black background? <pre><code>cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; </code></pre> <p>in this method</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; </code></pre> <p>but I can only see it when I select that cell otherwise it's not visible.and it work perfectly when background is white. I am sure that I need to set a property, but I don't know which property I need to change to make this thing work.</p> <p>thanks in advance.</p> <p>cheers.</p>
<p>I ran into this same issue, and just create a UIImageView out of a UIView’s imageWithName @"AccDisclosure.png" using the following hastily mocked-up graphic which you're free to copy: <a href="http://thinkingman.com/db/downloads/AccDisclosure.png">http://thinkingman.com/db/downloads/AccDisclosure.png</a> (if you just click that link, you'll probably see nothing, as it's a white image with a transparent background, but if you save it and view against a dark background, you'll see the alpha).</p>
Django: Arbitrary number of unnamed urls.py parameters <p>I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:</p> <pre><code>/browse/&lt;name1&gt;/&lt;value1&gt;/&lt;name2&gt;/&lt;value2&gt;/ .... etc .... </code></pre> <p>where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match.</p> <p>Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs.</p> <p>Ideally each name/value pair will be passed to the view function as a parameter named <code>name1</code>, <code>name2</code>, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there?</p> <p>So, it seems I need to do something like this:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>... and got the same problem, but this time <code>*args</code> only includes the last matched pattern.</p> <p>Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.*) pattern?</p>
<p>A possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view. As an example:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?P&lt;match&gt;.+)/$', 'app.views.view', name='model_browse'), ) def view(request, match): pieces = match.split('/') # even indexed pieces are the names, odd are values ... </code></pre> <p>No promises about the regexp I used, but I think you understand what I mean.</p> <p>(Edited to try and fix the regexp.)</p>
What is the fastest webserver solution with the lowest memory footprint? <p>I need a webserver to serve up very simple POST/GET requests as JSON. I don't need MVC, Rails, Django. I need something that takes up very little memory, preferrably around 5K per reqeust. The webserver will talk to backend services like Scribe using Facebook Thrift. Each http request will also access a SQLLite database, one for each user and user's data do not overlap. It will serve up static html files as well as the json webservice.</p> <p>I am considering the following:</p> <ul> <li>Njinx with PHP,</li> <li>Kepler from Lua,</li> <li>rolling my own with libevent or libev perhaps calling out to Lua, or</li> <li>MochiWeb.</li> </ul> <p>Which of these options are best and what other options are out there? I can use PHP, python, or Lua for basic scripting and even could do basic C. I am leaning towards some sort of Erlang solution.</p>
<p>I've had a good experience with nginx (<a href="http://nginx.net/" rel="nofollow">http://nginx.net/</a>), that said, when choosing a webserver, you should look closely at your requirements and make an informed decision as these things can be very application specific.</p> <p>You'll notice that in this question that a lot of people recommend g-wan, Webmachine, etc... these are all things you should look at and benchmark to see if they are faster for your use case.</p> <p>This is the kind of question that encourages cheerleading, there is no "right answer".</p>
What is the best .net Micro Framework dev board, for under $300? <p>I'm looking for a relativity cheap .net Micro Framework development board for use on a personal robotics project. I'd don't need much for I/O, but I want at least one serial port and one Ethernet port. </p> <p>I would prefer not to have to spend more than $300 on the board, but if there is an obvious reason to get a better one I'm flexible. </p> <p>Currently I'm looking at <a href="http://www.sjjmicro.com/EDK.html">this device from SJJ Embedded Micro Solutions</a>. Has anyone had experience with this device?</p>
<p>This looks very cool. And only 30$.</p> <p><a href="http://www.netduino.com/">http://www.netduino.com/</a></p> <p>And this Plus version with ethernet.</p> <p><a href="http://www.netduino.com/netduinoplus/specs.htm">http://www.netduino.com/netduinoplus/</a></p>
Translate SVN path to local file system path in Python <p>I'm writing a utility in Python that will attach changed files in Subversion to an email and send it when a subset of folders that are under source control in SVN have been changed. I am using the pysvn library to access the repository.</p> <p>I have a copy of the files on my local file system and I do an update to check if the files have changed since the last time the utility was run.</p> <p>I am at the point where I am translating the path names in SVN to the path names on my local copy.</p> <p>Currently I have written the following to do the job:</p> <pre><code>def formatPaths(self, paths): newPaths = list() for path in paths: path = path[len(self.basePath):] path = path.replace("/", "\\") newPaths.append(path) return newPaths </code></pre> <p>self.basePath would be something like "/trunk/project1" and I'm looking to just get the relative path of a subset of folders (I.e. folder1 under "/trunk/project1").</p> <p>Is this a good way to solve this problem or is there some magical function I missed?</p>
<p>Stay with the slice operator, but do not change the loop variable inside the loop. for fun, try the generator expression (or keep the listcomp).</p> <pre><code>baselen = len(self.basePath) return (path[baselen:].replace("/", "\\") for path in paths) </code></pre> <p>Edit: `lstrip()' is not relevant here. From the <a href="http://docs.python.org/library/stdtypes.html#string-methods" rel="nofollow">manual</a>:</p> <blockquote> <p>str.lstrip([chars])</p> <p>Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the beginning of the string this method is called on.</p> </blockquote>
unions declaration C code <p>I have seen some declaration of a union inside a struct as follows. Example code given below.</p> <p>My questions is does it help in any memory savings(typical use for which a union is used for)? I do not see the benefit. </p> <pre><code>typedef struct { int x1; unsigned int x2; ourstruct1 ov1; ourstruct1 ov2; union { struct { mystruct1 v1; mystruct2 v2; mystruct3 v3; int* ctxSC; mystruct4 v4; Bool v5; Long v6; Long v7; Long v8; Long v9; }mystr; }; }structvar1; </code></pre> <p>-AD</p>
<p>This is not a typical use for a union at all. Unions are variant types - you can put many different kind of types into them and retrieve them. <strong>Putting only one type into a union gives you nothing</strong>, except weird looking code.</p>
Debugging a Direct3D Model <p>I am trying to render a model in Direct3D using <code>DrawIndexedPrimitives</code>. However, I am not able to see it on screen. What are the usual methods used to debug a Direct3D model?</p> <p>I've tried the following:</p> <ul> <li>Switched off back face culling</li> <li>Used <code>PrimitiveType.LineStrip</code> instead of <code>PrimitiveType.TriangleStrip</code></li> <li>Several combinations of View and Projection matrices.</li> <li>Used AutoCAD to plot the vertices as tiny spheres</li> </ul>
<p>Use PIX tool from DX SDK. It's <em>absolutely awesome</em>.</p> <p>Probably you'll want to use single frame capture mode. Then on the draw call PIX will show the model before vertex processing takes place, after vertex processing takes place, complete state of your device, resulting pixels rendered, etc.</p>
Prevent long word to add horizontal scroll to html view <p>On Windows Mobile, I am displaying my output in HTML. This includes lots of user-generated strings. Occasionally there are situations where a really large string is part of the output that has no whitespaces or punctuation. </p> <p>Unfortunately the Windows Mobile's HTML view (htmlview.dll, based on Pocket Internet Explorer) does not break these long words down so they fit on screen. Instead a horizontal scrollbar is added and the user has to scroll sideways to see the whole word. This also affects other output which now also is spread along this larger screen width.</p> <p>Is there any possibility to either make the htmlview behave differently, or to force the word to break? CSS can be used. Regarding the forcing: The &amp;shy; tag is ALWAYS inserting a "-" character and never causes a breaks, the &lt;WBR&gt; tag is not doing anything at all, &amp;8203; is output as &amp;8203:, empty tags like <B></B> also do nothing. Also it should be noted that this code is running on multiple screen sizes and due to other parts of the HTML output I am not 100% sure how much screen width I have left.</p> <p>P.S.: My app is compiled using the WM 5.0 SDK and is written in C++/Win32/MFC.</p>
<p>Besides the shy hypen as mentioned by nickf, you can always use CSS to hide overshooting words by settings the box's style to <code>overflow: hidden</code>. Good news: no scrollbar, ma. Bad news: word is cut. For the shy hypen, I wouldn't go with the entity, though. Instead, use the character directly in your text: its character code is 0xAD (Unicode +00AD). (Entities are generally deprecated by the use of a correct encoding.)</p>
JavaME: Convert String to camelCase <p>What would be a simple implementation of a method to convert a String like "Hello there everyone" to "helloThereEveryone". In JavaME support for String and StringBuffer utility operations are quite limited.</p>
<p>Quick primitive implementation. I have no idea of restrictions of J2ME, so I hope it fits or it gives some ideas...</p> <pre><code>String str = "Hello, there, everyone?"; StringBuffer result = new StringBuffer(str.length()); String strl = str.toLowerCase(); boolean bMustCapitalize = false; for (int i = 0; i &lt; strl.length(); i++) { char c = strl.charAt(i); if (c &gt;= 'a' &amp;&amp; c &lt;= 'z') { if (bMustCapitalize) { result.append(strl.substring(i, i+1).toUpperCase()); bMustCapitalize = false; } else { result.append(c); } } else { bMustCapitalize = true; } } System.out.println(result); </code></pre> <p>You can replace the convoluted uppercase append with:</p> <pre><code>result.append((char) (c - 0x20)); </code></pre> <p>although it might seem more hackish.</p>
Looking for a better way than virtual inheritance in C++ <p>OK, I have a somewhat complicated system in C++. In a nutshell, I need to add a method to a third party abstract base class. The third party also provides a ton of derived classes that also need the new functionality.</p> <p>I'm using a library that provides a standard Shape interface, as well as some common shapes.</p> <pre><code>class Shape { public: Shape(position); virtual ~Shape(); virtual position GetPosition() const; virtual void SetPosition(position); virtual double GetPerimeter() const = 0; private: ... }; class Square : public Shape { public: Square(position, side_length); ... }; class Circle, Rectangle, Hexagon, etc </code></pre> <p>Now, here's my problem. I want the Shape class to also include a GetArea() function. So it seems like I should just do a:</p> <pre><code>class ImprovedShape : public virtual Shape { virtual double GetArea() const = 0; }; class ImprovedSquare : public Square, public ImprovedShape { ... } </code></pre> <p>And then I go and make an ImprovedSquare that inherits from ImprovedShape and Square. Well, as you can see, I have now created the dreaded <a href="http://en.wikipedia.org/wiki/Diamond_problem" rel="nofollow">diamond inheritance problem</a>. This would easily be fixed if the third party library used <a href="http://en.wikipedia.org/wiki/Virtual_inheritance" rel="nofollow">virtual inheritance</a> for their Square, Circle, etc. However, getting them to do that isn't a reasonable option.</p> <p>So, what do you do when you need to add a little functionality to an interface defined in a library? Is there a good answer?</p> <p>Thanks!</p>
<p>Why does this class need to derive from shape?</p> <pre><code>class ImprovedShape : public virtual Shape { virtual double GetArea() const = 0; }; </code></pre> <p>Why not just have</p> <pre><code>class ThingWithArea { virtual double GetArea() const = 0; }; </code></pre> <p>ImprovedSquare is a Shape and is a ThingWithArea</p>
How to present credentials in order to open file? <p>How do I specify the username and password in order for my program to open a file for reading? The program that needs to access the file is running from an account that does not have read access to the folder the file is in. Program is written in C# and .NET 2, running under XP and file is on a Windows Server 2003 machine.</p>
<p>You want to impersonate a user who does have the rights to access the file.</p> <p>I recommend using a class like this - <a href="http://www.codeproject.com/KB/cs/zetaimpersonator.aspx">http://www.codeproject.com/KB/cs/zetaimpersonator.aspx</a>. It hides all the nasty implementation of doing impersonation.</p> <pre><code>using (new Impersonator("myUsername", "myDomainname", "myPassword")) { string fileText = File.ReadAllText("c:\test.txt"); Console.WriteLine(fileText); } </code></pre>
How can I record what process or kernel activity is using the disk in GNU/Linux? <p>On a particular Debian server, iostat (and similar) report an unexpectedly high volume (in bytes) of disk writes going on. I am having trouble working out which process is doing these writes.</p> <p>Two interesting points:</p> <ol> <li><p>Tried turning off system services one at a time to no avail. Disk activity remains fairly constant and unexpectedly high.</p></li> <li><p>Despite the writing, do not seem to be consuming more overall space on the disk.</p></li> </ol> <p>Both of those make me think that the writing may be something that the kernel is doing, but I'm not swapping, so it's not clear to me what Linux might try to write.</p> <p>Could try out atop:</p> <p><a href="http://www.atcomputing.nl/Tools/atop/">http://www.atcomputing.nl/Tools/atop/</a></p> <p>but would like to avoid patching my kernel.</p> <p>Any ideas on how to track this down?</p>
<p>iotop is good (great, actually). </p> <p>If you have a kernel from before 2.6.20, you can't use most of these tools.</p> <p>Instead, you can try the following (which should work for almost any 2.6 kernel IIRC):</p> <pre> sudo -s dmesg -c /etc/init.d/klogd stop echo 1 > /proc/sys/vm/block_dump rm /tmp/disklog watch "dmesg -c >> /tmp/disklog" CTRL-C when you're done collecting data echo 0 > /proc/sys/vm/block_dump /etc/init.d/klogd start exit (quit root shell) cat /tmp/disklog | awk -F"[() \t]" '/(READ|WRITE|dirtied)/ {activity[$1]++} END {for (x in activity) print x, activity[x]}'| sort -nr -k2 </pre> <p>The dmesg -c lines clear your kernel log . The logger is then shut off, manually (using watch) dumped to a disk (the memory buffer is small, which is why we need to do this). Let it run for about five minutes or so, and then CTRL-c the watch process. After shutting off the logging and restarting klogd, analyze the results using the little bit of awk at the end.</p>
How do I add fitnesse pages to version-control? <p>What is the recommended practice? Should I add the my sub-folder under the fitnesse folder to version control? </p> <p><em>Context: working on a single developer rails pet project. I've my rails project under version-control (Subversion) however my fitnesse wiki pages lie under the fitnesse program folder.</em></p> <p>Fitnesse seems to have its own version-control... (I see numbered zips along with each of my wiki pages) Is it reliable? Where does it store the revisions?</p>
<p>Use the <code>-d</code> switch (<em>which is surprisingly low profile on a google search</em>)</p> <pre><code>Fitnesse20081201&gt;run -p 8080 -d c:/projects/MyProjectNeedsAcceptanceTests </code></pre> <p>This will create a subfolder in the specified folder called FitnesseRoot if it doesn't already exist, with all the stuff it needs to run.</p> <p>Fitnesse should be up. Switch to your browser. Go ahead and create your pages.</p> <ul> <li>You will have a subfolder for every Fitnesse page you create. </li> <li>Each folder would have a <code>content.txt</code> (which is the wiki content) and a <code>properties.xml</code> (which are the Fitnesse Properties for that page). </li> <li>All subpages would be subfolders under the folder for the parent page. </li> </ul> <p>Directories and Files...You're all setup for your first check-in to version control. Also set up your version control to ignore certain types of files</p> <ul> <li>FitnesseRoot/files</li> <li>FitnesseRoot/ErrorLog</li> <li>*.zip</li> </ul> <p><em>(The .zip files are how Fitnesse keeps track of edits to wiki pages.. a short term local version control. VCS like svn, git, cvs, etc.. should take care of this for us. So we don't need to check in the zip files)</em></p> <p>Hope that made sense.. If not I suggest you take 15 mins off to listen to the following screencast from UncleBob himself<br /> <strong>Source:</strong> <a href="http://vimeo.com/2765514">Robert Martin - Version Control and Development Environment for Fitnesse</a></p>
Efficient way to recursively calculate dominator tree? <p>I'm using the Lengauer and Tarjan algorithm with path compression to calculate the dominator tree for a graph where there are millions of nodes. The algorithm is quite complex and I have to admit I haven't taken the time to fully understand it, I'm just using it. Now I have a need to calculate the dominator trees of the direct children of the root node and possibly recurse down the graph to a certain depth repeating this operation. I.e. when I calculate the dominator tree for a child of the root node I want to pretend that the root node has been removed from the graph.</p> <p>My question is whether there is an efficient solution to this that makes use of immediate dominator information already calculated in the initial dominator tree for the root node? In other words I don't want to start from scratch for each of the children because the whole process is quite time consuming.</p> <p>Naively it seems it must be possible since there will be plenty of nodes deep down in the graph that have idoms just a little way above them and are unaffected by changes at the top of the graph.</p> <p>BTW just as aside: it's bizarre that the subject of dominator trees is "owned" by compiler people and there is no mention of it in books on classic graph theory. The application I'm using it for - my FindRoots java heap analyzer - is not related to compiler theory.</p> <p>Clarification: I'm talking about directed graphs here. The "root" I refer to is actually the node with the greatest reachability. I've updated the text above replacing references to "tree" with "graph". I tend to think of them as trees because the shape is <em>mainly</em> tree-like. The graph is actually of the objects in a java heap and as you can imagine is reasonably hierarchical. I have found the dominator tree useful when doing OOM leak analysis because what you are interested in is "what keeps this object alive?" and the answer ultimately is its dominator. Dominator trees allow you to &lt;ahem&gt; see the wood rather than the trees. But sometimes lots of junk floats to the top of the tree so you have a root with thousands of children directly below it. For such cases I would like to experiment with calculating the dominator trees rooted at each of the direct children (in the original graph) of the root and then maybe go to the next level down and so on. (I'm trying not to worry about the possibility of back links for the time being :)</p>
<p><a href="http://www.boost.org/doc/libs/1_36_0/libs/graph/doc/lengauer_tarjan_dominator.htm"><code>boost::lengauer_tarjan_dominator_tree_without_dfs</code></a> might help.</p>
How to convert a Unix timestamp to DateTime and vice versa? <p>There is this example code, but then it starts talking about millisecond / nanosecond problems.</p> <p>The same question is on MSDN, <em><a href="http://blogs.msdn.com/brada/archive/2004/03/20/93332.aspx">Seconds since the Unix epoch in C#</a></em>.</p> <p>This is what I've got so far:</p> <pre><code>public Double CreatedEpoch { get { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime(); TimeSpan span = (this.Created.ToLocalTime() - epoch); return span.TotalSeconds; } set { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime(); this.Created = epoch.AddSeconds(value); } } </code></pre>
<p>Here's what you need:</p> <pre><code>public static DateTime UnixTimeStampToDateTime( double unixTimeStamp ) { // Unix timestamp is seconds past epoch System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc); dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime(); return dtDateTime; } </code></pre> <p>Or, for Java (which is different):</p> <pre><code>public static DateTime JavaTimeStampToDateTime(double javaTimeStamp) { // Java timestamp is millisecods past epoch System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc); dtDateTime = dtDateTime.AddSeconds(Math.Round(javaTimeStamp / 1000)).ToLocalTime(); return dtDateTime; } </code></pre>
Align element under other element through css <p>I have a really simple search form with the following</p> <ul> <li>Label ("Search")</li> <li>Textbox (fixed width)</li> <li>Submit button</li> <li>"Advanced" link</li> </ul> <p>Label, textbox and submit are all on one horizontal line and centered. Now I would like my advanced link to be under the submit button.</p> <p>Any ideas?</p>
<p>If I understand the question you want:</p> <pre><code> Search [xxxxxxxxxxxxxxxx] [Submit] Advanced </code></pre> <p>You'll have to add some more elements in to do that:</p> <pre><code>&lt;div style="width: 300px; margin: auto; text-align: center;"&gt; Search [xxxxxxxxxxxxxxx] [Submit] &lt;div style="text-align: right"&gt;Advanced&lt;/div&gt; &lt;/div&gt; </code></pre>
Restrict adding control on Panel <p>How can i restrict adding controls in Panel in C# window controls? I have to restrict user to add controls in a panel at design time.</p>
<p>If you want to limit the types of controls or number of controls one can add to the panel you can make your own subclass of the panel and check the Control type or Control count in an overload of the Controls.Add method. </p> <p>Edit: Overloading the Controls.Add method was not as easy as I thought, but you can make a new class that extends the Panel class and override the OnControlAdded method to check the type of control that was added. Something like this should work:</p> <pre><code>class MyPanel : Panel { public MyPanel() { } protected override void OnControlAdded(ControlEventArgs e) { base.OnControlAdded(e); if (!(e.Control is Label)) { MessageBox.Show("control " + e.Control.Name + " is not a label but a " + e.Control.GetType().ToString()); Controls.Remove(e.Control); } } } </code></pre>
An alternative to alert/confirm/error dialogs? <p>We all know that alerts are bad. If you didn't know it read <a href="http://www.codinghorror.com/blog/archives/000114.html" rel="nofollow">this</a></p> <p>Alerts are used to communicate with the user. So if we don't use them what is a good alternative? </p> <p>I'd like to get a nice list of good alternatives to choose from when implementing something that requires user communications.</p> <p>I'll give one myself as an example and for everyone to use:</p> <p><strong>Case:</strong> we need to validate user input before we can proceed.</p> <p><strong>Solution:</strong> instead of showing an alert box when user clicks ok/next/submit show a clearly styled (eg. red on a white bg) "frame" around/next to the user input that has the invalid input with an informative text on what is wrong. To make it easier on the user the input in question should gain focus and if necessary moved back into view.</p>
<p>Here’s the hierarchy for dealing with user errors or warnings, applied to validating user input to a field.</p> <ol> <li><p>Remove the element that may result in an error. Do you really need the user’s birth date? Can you get by just as well with something else that won’t require validation, such as option buttons for “Under 18 years old,” and “18 or over”?</p></li> <li><p>Prevent the error. Make it impossible to enter invalid input in the first place. For example, use a dropdown list, or “picture” the field, refusing any unacceptable characters (e.g., letters for a phone number).</p></li> <li><p>Accept the input and possibly correct it automatically and echoing the result back to the user. Make <em>something</em> out of the input. If the user types 4--14#008 for a date, auto-correct it to be April 14 2008. If the format doesn’t match a version number, check if it’s a Release Number and lookup the corresponding Version number. If it doesn’t fit your idea of a valid address, well, just assume that it is (maybe it’s for a foreign country). Does it really matter if the user’s birth date mangled?</p></li> <li><p>Provide Undo, not verification, showing clearly the implications of what the user did and providing a clear path to reverse it. When the user enters the number of stock shares to trade, show the dollar value beside it, in case the user confused shares with dollars. Keep the fields editable so the user can fix it.</p></li> <li><p>Provide warning and error text in the primary window or web page itself; text should be apparent without being disorienting, non-modal, and disappear automatically when the error is corrected. When a unrecognized date is entered, underline it in red and put text beside it saying “unrecognized date,” perhaps including a Help link for more information.</p></li> <li><p>Modal message box.</p></li> </ol>
Best programming methodology for very fast timeline and little requirements? <p>What is a good programming methodology for custom applications that need to be coded very fast and very customized? I realize the lack of requirements is a problem no matter what. Also how do you convince management to change their practices? Next question is how to you get people to stop writing 5000 line single file programs? </p>
<p>run... like hell</p>
Is asp.net session information stored in a cookie? <p>If I write <code>Session["asdf"] = 234;</code></p> <p>In my asp.net web app, does this mean the client will have a cookie stored on their browser?</p>
<p>Yes, but 234 won't be stored in the cookie. The cookie will only contain a unique ID (for example, <code>lit3py55t21z5v55vlm25s55</code>). Every time ASP.NET sees that unique ID, it will look up the corresponding session information.</p> <p>If you don't want to use cookies, you can put the session ID in the URL. Read this <a href="http://msdn.microsoft.com/en-us/library/ms178581.aspx" rel="nofollow">MSDN article's</a> section on Cookieless SessionIDs.</p>
ASP.NET Ajax: close window after Ajax call? <p>I'm using ASP.NET Ajax. How can I <strong>tell the browser to close the current window</strong> after the server call finishes (server-side code)?</p> <p>I managed to do this using the ASP.NET Ajax's ScriptManager method "RegisterDataItem" in the server method (inside a button click handler):</p> <pre><code>sm.RegisterDataItem(ActionLabel, "action:closewindow") </code></pre> <p>and a hidden Label and handling it this way on the client:</p> <pre><code>function PageLoadingHandler(sender, args) { var dataItems = args.get_dataItems(); if (dataItems['ActionLabel'] == 'action:closewindow') { window.close() } } Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(PageLoadingHandler); </code></pre> <p>But it feels <strong>dirty</strong>. There must be a more elegant way to do this.</p> <p>Thanks for any advice.</p>
<p>If I understood you right, registering <code>window.close()</code> with <code>ScriptManagers</code> <code>RegisterStartupScript</code> method on event handler should work. For details on using <code>ScriptManager.RegisterStartupScript</code> see <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerstartupscript.aspx" rel="nofollow">MSDN</a></p>
Single instance Amazon EC2 <p>We're running a lightweight web app on a single EC2 server instance, which is fine for our needs, but we're wondering about monitoring and restarting it if it goes down.</p> <p>We have a separate non-Amazon server we'd like to use to monitor the EC2 and start a fresh instance if necessary and shut down the old one. All our user data is on Elastic Storage, so we're not too worried about losing anything.</p> <p>I was wondering if anyone has any experience of using EC2 in this way, and in particular of automating the process of starting the new instance? We have no problem creating something from scratch, but it seems like it should be a solved problem, so I was wondering if anyone has any tips, links, scripts, tutorials, etc to share.</p> <p>Thanks.</p>
<p>You should have a look at <a href="http://reductivelabs.com/trac/puppet/wiki/PuppetIntroduction">puppet</a> and its support for <a href="http://reductivelabs.com/trac/puppet/wiki/Recipes/AmazonWebService">AWS</a>. I would also look at the <a href="http://rightaws.rubyforge.org/">RightScale AWS library</a> as well as this post about <a href="http://blog.rightscale.com/2007/08/07/configuring-servers-with-rightscripts/">starting a server with the RightScale scripts</a>. You may also find this article on <a href="http://www.mikebrittain.com/blog/2008/07/19/web-hosting-on-ec2/">web serving with EC2</a> useful. I have done something similar to this but without the external monitoring, the node monitored itself and shut down when it was no longer needed then a new one would start up later when there was more work to do.</p>
Capistrano: How to Include common settings in multiple project deploy.rb files <p>this is probably a newbie ruby question. I have several libraries and apps that I need to deploy to several different hosts. All of the apps and libs will share some common settings for those hosts-- e.g. host name, database server/user/pass, etc.</p> <p>My goal is to do something like:</p> <pre><code>cap host1 stage deploy cap host2 stage deploy cap host1 prod deploy # ... </code></pre> <p>My question is how do you include these common settings in all of your deploy.rb files? More specifically, I want to create a an rb file that I can include that has some common settings and several host specific task definitions:</p> <pre><code>set :use_sudo, false # set some other options task :host1 do role :app, "host1.example.com" role :web, "host1.example.com" role :db, "host1.example.com", :primary =&gt; true set :rodb_host, "dbhost" set :rodb_user, "user" set :rodb_pass, "pass" set :rodb_name, "db" end task :host2 do #... end deploy.task :carsala do transaction do setup update_code symlink end end </code></pre> <p>And then "include" this file in all of my deploy.rb files where I define stage, prod, etc and overwrite any "common" configuration parameters as necessary. Any suggestions would be appreciated. I've tried a few different things, but I get errors from cap for all of them. </p> <p>Edit: I've tried </p> <pre><code>require 'my_module' </code></pre> <p>But I get errors complaining about an undefined task object.</p>
<p>I just experimented with it a little more and what I discovered is that you have to:</p> <pre><code>load 'config/my_module' </code></pre> <p>I can put all of my common definitions here and just load it into my deploy.rb.</p> <p>It appears from the docs that load loads and executes the file. Alternatively, require attempts to load the library specified. I'm not totally sure about real difference, but it appears that there is some separation between the current app symbol space and the library require'd (hence the errors about the undefined task object) that isn't a problem when you do a load. </p>
Correct approach to Properties <p>I am working in Java on a fairly large project. My question is about how to best structure the set of Properties for my application.</p> <p>Approach 1: Have some static Properties object that's accessible by every class. (Disadvantages: then, some classes lose their generality should they be taken out of the context of the application; they also require explicit calls to some static object that is located in a different class and may in the future disappear; it just doesn't <em>feel</em> right, am I wrong?)</p> <p>Approach 2: Have the Properties be instantiated by the main class and handed down to the other application classes. (Disadvantages: you end up passing a pointer to the Properties object to almost every class and it seems to become very redundant and cumbersome; I don't <em>like</em> it.)</p> <p>Any suggestions?</p>
<p>I like using Spring dependency injection for many of the properties. You can treat your application like building blocks and inject the properties directly into the component that needs them. This preserves (encourages) encapsulation. Then, you assemble your components together and create the "main class". </p> <p>A nice side effect of the dependency injection is that your code should be more easily testable.</p>
JS Regex For Human Names <p>I'm looking for a good JavaScript RegEx to convert names to proper cases. For example:</p> <pre><code>John SMITH = John Smith Mary O'SMITH = Mary O'Smith E.t MCHYPHEN-SMITH = E.T McHyphen-Smith John Middlename SMITH = John Middlename SMITH </code></pre> <p>Well you get the idea.</p> <p>Anyone come up with a comprehensive solution?</p>
<p>Something like this?</p> <pre><code>function fix_name(name) { var replacer = function (whole,prefix,word) { ret = []; if (prefix) { ret.push(prefix.charAt(0).toUpperCase()); ret.push(prefix.substr(1).toLowerCase()); } ret.push(word.charAt(0).toUpperCase()); ret.push(word.substr(1).toLowerCase()); return ret.join(''); } var pattern = /\b(ma?c)?([a-z]+)/ig; return name.replace(pattern, replacer); } </code></pre>
Is it possible to communicate with a sub subprocess with subprocess.Popen? <p>I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like:</p> <pre><code>sudo mod args </code></pre> <p>where mod is a perl script; so in python I would do </p> <pre><code>proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE) </code></pre> <p>The problem is that this mod script needs a few questions answered. For this I thought that the traditional </p> <pre><code>(stdout, stderr) = proc.communicate(input='y') </code></pre> <p>would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?</p>
<p>I would choose to go with Pexpect. </p> <pre><code>import pexpect child = pexpect.spawn ('sudo mod -p -c noresource -u dtt -Q') child.expect ('First question:') child.sendline ('Y') child.expect ('Second question:') child.sendline ('Yup') </code></pre>
Lean Software (Webapplication) Release Engineering <p>I'm looking to re-organize the way we release our internal software. All of the code (PHP webapps, some Java apps and Perl scripts) is checked into Subversion repositories but there are no branches or tags, everything is checked into trunk (only around 1-3 devs per app). On the production linux servers, the software is just directly run from a working svn copy (actually most of the changes happen there as well).</p> <p>Since we have a lot of small apps and release very often small changes to the running system, I'm looking for a very lean or transparent way to do some release engineering and to clean up this mess abit.</p> <p>Are there any tools out there that may help me to do so in a heterogenous environment (language-wise) like that? Or has anyone an idea how to do this in a proper way?</p> <p>Otherwise I'd thought of writing some release (shell) scripts that automatically create subversion tags from trunk and then do a checkout of the corresponding tag to the production servers. But that sounds kinda hack'ish as well to me.</p> <p>Thanks,</p> <p>Haes.</p>
<p>Use tags and branches; make it a part of the development cycle. When you update that "stable-1.0" branch, have tested the change(s) and tagged it "release-1.0.5", you simply do "svn switch" on the server to the new tag. Didn't work, despite having tested it? Switch back, and figure out what's wrong.</p> <p>But beware, branching in subversion can be a pain, at least pre version 1.5. If you or your developers are not experienced with branches, expect a bit of hassle and/or mistakes in the beginning. But as long as you've committed no code should be lost (at worst simply difficult to merge).</p> <p>Your developers really should learn how to use branching; it can be very useful for a variety of purposes (not just for release engineering).</p> <p>Do <em>not</em> automatically switch over code on your production servers; somebody might accidentally hit the wrong button. Production updates should always be done with care. Scripts for adding new tags is, imho, unnecessary due to the simplicity of it, but your mileage may vary.</p> <p>One last thing, don't allow anyone to have changes on your production server. It might cause conflicts, and those tend to take time to resolve. Not to mention, it destroys your ability to reproduce a given release on different workstations (works fine here! why not on the server? hmm).</p>
Weird IE & Javascript issue <p>So I'm creating some HTML using javascript based on where the user clicks on the page. On page load the script replaces an empty div with a ul and some data. The user clicks on that data to receive more and so on. Now when the user navigates off the page and then hits the back button to go back to the page, IE displays a blank page with the replaced divs, in all other browsers, FF, Opera, Safari, the page either reloads to the initial ul or goes back to the last state with the dynamic data in it.</p> <p>Anyone have an idea as to what might be happening here? Any help is appreciated.</p>
<p>It sounds like you need to manage the history and state of your page. Check our Brad Neuberg's <a href="http://code.google.com/p/reallysimplehistory/" rel="nofollow">Really Simple History</a>.</p>
How do you bind the TextWrapping property of a TextBox to the IsChecked value of a MenuItem? <p>The TextWrapping property of the TextBox has three possible values:</p> <ul> <li>Wrap</li> <li>NoWrap</li> <li>WrapWithOverflow</li> </ul> <p>I would like to bind to the IsChecked property of a MenuItem. If the MenuItem is checked, I want to set the TextWrapping property of a TextBox to Wrap. If the MenuItem is not checked, I want to set the TextWrapping property of the TextBox to NoWrap.</p> <p>To sum up, I am trying to bind a control that has two states to two values of an enumeration that has more than two values.</p> <p><strong>[edit]</strong> I would like to accomplish this in XAML, if possible.</p> <p><strong>[edit]</strong> I figured out how to do this using an IValueConverter. Perhaps there is a better way to do this? Here is what I did:</p> <p><hr /></p> <p>In Window.Resources, I declared a reference to my ValueConverter.</p> <pre><code>&lt;local:Boolean2TextWrapping x:Key="Boolean2TextWrapping" /&gt; </code></pre> <p>In my TextBox, I created the binding to a MenuItem and included the Converter in the binding statement.</p> <pre><code>TextWrapping="{Binding ElementName=MenuItemWordWrap, Path=IsChecked, Converter={StaticResource Boolean2TextWrapping}}" </code></pre> <p>and the ValueConverter looks like this:</p> <pre><code>public class Boolean2TextWrapping : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo) { if (((bool)value) == false) { return TextWrapping.NoWrap; } return TextWrapping.Wrap; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } </code></pre>
<p>If you want to do this all in xaml you need to use a <a href="http://msdn.microsoft.com/en-us/library/system.windows.style.aspx">Style</a> and a <a href="http://msdn.microsoft.com/en-us/library/system.windows.datatrigger.aspx">DataTrigger</a>.</p> <pre><code>&lt;StackPanel&gt; &lt;CheckBox x:Name="WordWrap"&gt;Word Wrap&lt;/CheckBox&gt; &lt;TextBlock Width="50"&gt; Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin lacinia nibh non augue. Pellentesque pretium neque et neque auctor adipiscing. &lt;TextBlock.Style&gt; &lt;Style TargetType="{x:Type TextBlock}"&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding IsChecked, ElementName=WordWrap}" Value="True"&gt; &lt;Setter Property="TextWrapping" Value="Wrap" /&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/TextBlock.Style&gt; &lt;/TextBlock&gt; &lt;/StackPanel&gt; </code></pre>
right approach to handling bad xml data <p>I've got a little c# windows service that periodically pulls xml from a web service and stores the data in a database table.</p> <p>Unfortunately it's failing because the web service has occasional bad data in it - strings instead of decimals. I don't have any control over the web service (unvalidated user input from software we can't change) but I would like to log the bad data so that it can be re-input.</p> <p>It's simple data that looks something like this:</p> <pre><code>&lt;ROWS&gt; &lt;ROW&gt; &lt;COL1&gt;5405&lt;/COL1&gt; &lt;COL2&gt;102.24&lt;/COL1&gt; &lt;/ROW&gt; &lt;ROW&gt; &lt;COL1&gt;5406&lt;/COL1&gt; &lt;COL2&gt;2.25&lt;/COL1&gt; &lt;/ROW&gt; &lt;/ROWS&gt; </code></pre> <p>The table just has two columns, COL1 (NUMBER, 10), COL2 (NUMBER, 10,2).</p> <p>I was using a validating XmlReader and this XSD: </p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;xs:schema id="ROWS" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"&gt; &lt;xs:element name="ROWS" msdata:IsDataSet="true" msdata:Locale="en-US"&gt; &lt;xs:complexType&gt; &lt;xs:choice minOccurs="0" maxOccurs="unbounded"&gt; &lt;xs:element name="ROW"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="COL1" type="xs:decimal" minOccurs="0" /&gt; &lt;xs:element name="COL2" type="xs:decimal" minOccurs="0" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:choice&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre> <p>then a dataset.ReadXml() and Update()ing the dataset.</p> <p>Whenever it hits bad data I get the following exception:</p> <blockquote> <p>System.Xml.Schema.XmlSchemaValidationException was unhandled</p> <p>Message="The 'COL1' element is invalid - The value 'A40' is invalid according to its datatype '<a href="http://www.w3.org/2001/XMLSchema:decimal" rel="nofollow">http://www.w3.org/2001/XMLSchema:decimal</a>' - The string 'A40' is not a valid Decimal value."</p> </blockquote> <p>I can think of several ways of ways of getting around the problem but they all feel like a bit of a kludge and I'd like to learn something more elegant, and improve my knowledge. Here's what I've come up with so far:</p> <ul> <li>Pre-process the XML provided by the web service before loading into the validating XML reader, removing any bad nodes entirely.</li> <li>Catch the XmlSchemaValidationExceptions and try to continue from them gracefully (not sure about that one)</li> <li>Don't use a validating XML reader, but instead catch exceptions when loading the unvalidated xml into the dataset. (again not sure about that)</li> <li>have string columns in the dataset, and ignore bad data until I update it, and catch anything the database rejects.</li> <li>go and stand over the users with a large mallet until they learn to get it right first time (too time consuming)</li> <li>something else?</li> </ul> <p><strong>UPDATE:</strong> The data can be bad because it comes from a application that doesn't validate the user input for COL1 - but the numbers in COL2 are calculated correctly, and COL1 should correspond with a different system. Any invalid entries should be recorded so they can be corrected. After the data is written to the database, another system verifies that COL1 is valid, and the users will soon spot if it doesn't show correctly in the other system - they used to load it by hand anyway :) </p>
<blockquote> <p>Pre-process the XML provided by the web service before loading into the validating XML reader, removing any bad nodes entirely.</p> </blockquote> <p>This is the option I would choose, it would allow you to grab the bad input before the exception and store it somewhere so it can be looked at later. Then you can find the offending user and use another of your methods </p> <blockquote> <p>go and stand over the users with a large mallet until they learn to get it right first time</p> </blockquote>
Using QSortFilterProxyModel with a tree model <p>I have a QDirModel whose current directory is set. Then I have a QListView which is supposed to show the files in that directory. This works fine. Now I want to limit the files shown, so it only shows png files (the filename ends with .png). The problem is that using a QSortFilterProxyModel and setting the filter regexp will try to match every parent of the files as well. According to the documentation:</p> <blockquote> <p>For hierarchical models, the filter is applied recursively to all children. If a parent item doesn't match the filter, none of its children will be shown.</p> </blockquote> <p>So, how do I get the QSortFilterProxyModel to only filter the files in the directory, and not the directories it resides in?</p>
<p>We ran into something similar where I work, and ended up making our own proxy model to do our filtering. However, looking through the documentation for what you want (which seems like it would be a more common case), I came across two possibilities.</p> <ol> <li>You might be able to set a name filter on the QDirModel and filter things that way. I have no idea if this will work like you want, or if the name filters apply to directories also. The documentation is kind of sparse on these.</li> <li>Subclass the QSortFilterProxyModel and override the <code>filterAcceptsRow</code> function. From the documentation:</li> </ol> <blockquote> <p>Custom filtering behavior can be achieved by reimplementing the filterAcceptsRow() and filterAcceptsColumn() functions.</p> </blockquote> <p>Then you could presumably use the model index to check if the index item is a directory (automatically accept) or a file (filter on filename).</p>
How do I find the length (size) of a binary blob in sqlite <p>I have an sqlite table that contains a BLOB file, but need to do a size/length check on the blob, how do I do that?</p> <p>According to some documentation I did find, using length(blob) won't work, because length() only works on texts and will stop counting after the first NULL. My empirical tests have shown this to be true.</p> <p>I'm using SQLite 3.4.2</p> <hr> <p>Updates:</p> <p>So as of SQLite 3.7.6 it appears as though the length() function returns the correct value of blobs - I checked various change-logs of sqlite, but did not see in what version this was corrected.</p> <p>From Sqlite 3.7.6:</p> <pre> payload_id|length(payload)|length(hex(payload))/2 1807913|194|194 1807914|171|171 </pre> <p>The <a href="http://www.sqlite.org/lang_corefunc.html">documentation</a> was changed to reflect this.</p> <pre> length(X) The length(X) function returns the length of X in characters if X is a string, or in bytes if X is a blob. If X is NULL then length(X) is NULL. If X is numeric then length(X) returns the length of a string representation of X. </pre>
<p>haven't had this problem, but you could try <code>length(hex(glob))/2</code></p> <p><strong>Update (Aug-2012):</strong> For SQLite 3.7.6 (released April 12, 2011) and later, <code>length(blob_column)</code> works as expected both both text and binary data.</p>
Detect a “Error: Object doesn't support this property or method” <p>The object I’m working on is instantiated in JavaScript, but used in VBScript. In one code path, the variable <code>M.DOM.IPt</code> is defined and has a value, in the other however it is not. I need to detect if it has been defined or not. I checked that <code>M.DOM</code> is defined and accessable in both code paths. Every test I have tried simply results in this error:</p> <blockquote> <p>Error: Object doesn't support this property or method</p> </blockquote> <p>I have tried:</p> <ul> <li><code>IsEmpty(M.DOM.IPt)</code></li> <li><code>M.DOM.IPt is Nothing</code></li> <li><code>isNull(M.DOM.IPt)</code></li> </ul> <p>Is there any way to detect the variable isn’t defined and avoid the error?</p> <p>Note: I can put <code>On Error Resume Next</code> in and it will simply ignore the error, but I actually need to detect it and conditionally do something about it.</p>
<pre><code>On Error Resume Next Err.Clear MyVariable=M.DOM.Ipt If Err.Number&lt;&gt; 0 Then 'error occured - Ipt not defined 'do your processing here Else 'no error - Ipt is defined 'do your processing here End If </code></pre>
How can one open a PNG (image) file with VB6 into an RGB array, or R, G, B arrays <p>How can one open a PNG formatted image file with VB6? Ideally, I (that is my customer) would like to have the PNG file open and placed into seperate R(ed), G(reen) and B(lue) arrays.</p> <p>VB6 is not my tool of choice (for lack of knowledge) and I be thrilled if some one could point me in the right direction for a VB6 solution.</p>
<p>Thanks for the link, although not being a fluent VB guy (more C &amp; ASM flavours), the code appears to be very BMP centric; not PNG. </p> <p>If that's the case, I have to believe you suggested the link because it would be a simple matter to make the code PNG'able, but I wouldn't know how to approach that.</p>
Share Styling Between CSS Classes <p>In <a href="http://stackoverflow.com/questions/226206/alternating-item-style">this question</a>, I was given a really cool answer to alternating an image and its description between left and right, respectively. Now I want to apply styling to both, e.g. padding-top, padding-bottom etc. How do I apply a style to both the RowStyle and AlternatingRowStyle in this scenario.</p> <pre><code>&lt;AlternatingRowStyle CssClass="ProductAltItemStyle" /&gt; &lt;RowStyle CssClass="ProductItemStyle" /&gt; &lt;Columns&gt; &lt;asp:TemplateField&gt; &lt;ItemTemplate&gt; &lt;div class="Image"&gt;&lt;asp:Image runat="server" ID="productImage" ImageUrl='&lt;%# Eval("imageUrl") %&gt;' /&gt;&lt;/div&gt; &lt;div class="Description"&gt;&lt;asp:Label runat="server" ID="lblProductDesc" Width="100%" Text='&lt;%# Eval("productDesc") %&gt;'&gt;&lt;/asp:Label&gt;&lt;/div&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre>
<p>Here's how you do it:</p> <pre><code>.ProductAltItemStyle, .ProductItemStyle { // CSS Rules that apply to both go here }</code></pre>
Is it possible to execute SQL commands and send MSMQ messages in a TransactionScope? <p>I'm investigating using MSMQ for my team's new project but I need to know if I can send MSMQ messages and execute SQL commands within a System.Transactions.TransactionScope and have them commit or rollback together. I can't find a reliable source online that says "yes" with code examples. </p> <p>I need to send some messages to a single queue and insert some records in a single database, but I need to to succeed or fail together.</p> <p>EDIT: I was not able to actually verify whether this works or not in my testing (I was pulled off this task quickly) but all the documentation states that TransactionScope does capture MSMQ messages and SQL commands in the same instance.</p>
<p>From personal experience I know the TransactionScope works great with SQL. I'm not too familiar with MSMQ but a quick <a href="http://www.google.com/search?q=msmq+transactionscope" rel="nofollow">Google search</a> shows some examples (normally forum discussions) where it looks like it's working successfully. The System.Messaging.MessageQueue object also has a .Transactional property and the .Send() method has a MessageQueueTransaction parameter so I'd say it should all work together.</p> <p>Here's the code example from one of the forums in the search (not my code):</p> <pre><code>using (TransactionScope scope = new TransactionScope()) { using (MessageQueue myQueue = new MessageQueue(QUEUE_NAME)) { if (myQueue.Transactional) { myQueue.Send(TicketTextBox.Text, "Message", MessageQueueTransactionType.Automatic); } } scope.Complete(); } </code></pre> <p>Just throw your SQL code inside the using() block for the TransactionScope (before the .Complete()) and you should be good to go?</p>
An example for using DBMS_AQ.POST and explanation of its utility <p>The DBMS_AQ package has a method called POST. </p> <p>The documentation says,</p> <blockquote> <p>This procedure posts to a list of anonymous subscriptions, allowing all clients who are registered for the subscriptions to get notifications of persistent messages. This feature is not supported with buffered messages.</p> </blockquote> <p>and</p> <blockquote> <p>This call provides a best-effort guarantee. A notification goes to registered clients at most once. This call is primarily used for lightweight notification. If an application needs more rigid guarantees, then it can enqueue to a queue.</p> </blockquote> <p>I understand all of the words but I do not see a purpose for non-guaranteed messaging. I queue something because I need it to get somewhere. Maybe it's just that my business doesn't have a use-case for this. I'd to know what use-cases you have for such a technology.</p>
<p>The first that springs to mind is that you may have a large number of client applications interested in the DB information. Some system triggers an event that updates the database with useful, but not so important information (e.g. total count of rows in a table that is shown to the user).</p> <p>It then wants to broadcast this to the clients, but if a client is really busy (or offline briefly - e.g. network disconnect), this approach can be used to drop the unimportant message. This may be the best approach to take in some situations as if they are offline the client may when reconnecting actively look up all the information again.</p> <p>While there are use cases, I would guess they're much less common than guaranteed delivery - just like TCP seems to be used significantly more than UDP.</p>
VIM visual mode: highlight last 2 chars in each line? <p>I like Vim's visual mode. <kbd>v</kbd> for highlight/select chars or lines, <kbd>Ctrl</kbd><kbd>v</kbd> for rectangle highlighting, as far as I know (I am a beginner). Is there any way to use visual mode to highlight last two chars, for example, on each line for some selected lines? The selected lines are in different length. Basically, I would like to find a quick way to remove the last two chars for some selected lines. Not sure I can use visual mode to highlight irregular area.</p>
<p>My approach to this sort of problem is to use line selection (shift-V, cursor movement) to select the lines-of-interest, then type:</p> <pre><code> :s/..$// </code></pre> <p>That's a substitution, using the regex <code>..$</code> which will match the last two characters at the end of the line. Then substitute 'nothing' i.e. delete.</p> <p>In vim, once you hit the <code>:</code> with a line selection active, the command prompt will actually show:</p> <pre><code>:'&lt;,'&gt; </code></pre> <p>Which is the start and end of selection addresses for the next command (s in this case)</p>