input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
What is the CS definition of a Php Array? <p>From a strictly implementation and computer science point of view how would you classify the Php array datastructure? Is it an associative array? a hash? a dictionary? ... ?</p>
| <p>From the <a href="http://uk3.php.net/manual/en/language.types.array.php" rel="nofollow">PHP manual</a>:</p>
<blockquote>
<p>An array in PHP is actually an ordered
map. A map is a type that associates
values to keys. This type is optimized
for several different uses; it can be
treated as an array, list (vector),
hash table (an implementation of a
map), dictionary, collection, stack,
queue, and probably more.</p>
</blockquote>
|
How to write a code generator given a custom IDL? <p>If you have a simple enough schema with basic boolean string fields, how to go about writing a code generator in C++.
If you ever wrote , how did you start. Articles/recommendation welcome.</p>
<p>EDIT: Note that this is not the standard CORBA idl.</p>
| <p>In summary:</p>
<ol>
<li>Convert something by hand, </li>
<li>copy that output into a string literal and then </li>
<li>generalise with loops and variables instead of fixed names.</li>
</ol>
<p>This is a particularly good problem to tackle with TDD - start by setting up a framework such as CPPUnit (or <a href="http://stackoverflow.com/questions/387272/unit-testing-in-c">one of many alternatives</a>) with <em>stupidly simple</em> tests that just ensure you can load a file and iterate its contents by writing them out.</p>
<p>Approach the solution very incrementally - get something simple and general output, with a test to confirm it works, then add a more sophisticated variation. eg: handle single parameter functions first.</p>
<p>For code up to a moderate range of complexity, just have a long set of output statements using the standard C++ ostream classes which will allow you to write lots of code mixing literals with any variables. </p>
|
Can you tell on runtime if you're running java from within a jar? <p>I have an application that some of my users run from Eclipse, and others run it by using a jar file.</p>
<p>I want some actions to be done when running from within the jar, but I don't want them to be done when running from Eclipse.</p>
<p>Is there a way to know on runtime whether the current application is running from within a jar?</p>
<p>Thanks!</p>
<p>Dikla</p>
| <p>Well, you can tell whether or not a class has been loaded from a jar - use <code>Foo.class.getResource("Foo.class")</code> and see whether the returned URL begins with "jar:"</p>
<p>For example, take this program:</p>
<p>package com.whatever;</p>
<pre><code>public class Foo
{
public static void main(String[] args)
{
System.out.println(Foo.class.getResource("Foo.class"));
}
}
</code></pre>
<p>Running it loading the file from the file system:</p>
<pre><code>file:/C:/Users/Jon/Test/com/whatever/Foo.class
</code></pre>
<p>Running it from a jar file:</p>
<pre><code>jar:file:/C:/Users/Jon/Test/foo.jar!/com/whatever/Foo.class
</code></pre>
|
What's the best way to pass configuration to application agnostic modules? <p>I am working on an application that consists of several modules which in turn will be used in other applications as well. Each of these modules needs some configuration options, but should not be aware of the options of other modules, and also should not require other modules to exist. Some settings are shared between modules.</p>
<p>Lets say Module A requires settings x and y, Module B requires settings y and z.</p>
<p>Settings are stored either in the registry or in one or more .ini files.</p>
<p>So far I have considered the following approaches:</p>
<ol>
<li>Have a global unit ("global.pas")
that is included in all modules and
contains global variables with the
settings. I don't like this approach
very much because it would require
all applications to have such a unit
and it is bound to collect lots of
additional code that has nothing to
do with the original purpose. So
eventually each application will
have its own incompatible global
unit.</li>
<li>Have configuration classes for each module that contain all the settings required for that module. These are passed into the module from some central point in the application which also handles reading and writing them to some permanent form (e.g. use JvAppStorage). This requires some synchronisation between the modules because some options will be shared between them, so if the option is changed in one module, this change must somehow be reflected in the configuration of another module (not necessarily in real time but the next time the module is initialized).</li>
<li>Have a generic configuration class that is passed to each module and that contains the settings for all modules as properties. Each module accesses only those settings it knows about. The problem here might be that name clashes can occur whithout being noticed. Also I don't like the idea of passing configuration options around that are not necessary for a module. In addition, every application will contain a different subset of modules but would end up containing the same configuration class with the options for all possible modules. (This isn't very different from the global unit approach above.)</li>
<li>Have a generic configuration class that is passed to each module, like above. But instead of having properties, the modules access their settings by name (in the easiest case this could be a TCustomIniFile). This avoids having settings for all modules available in all applications, but introduces possible type compatibility problems and again, name clashes may become an issue (unless each module prefixes its options with its name, but then they can no longer share options).</li>
</ol>
<p>I guess everybody who wrote a modularized system has faced this issue and found some solutions they later on were stuck with, whether they still liked them or not. I have been there too, several times and am still looking for the golden bullet.</p>
<p>Maybe somebody else has already found the ideal solution?</p>
<p>(This is Delphi 2007 in case it matters. I am already using the JCL / JVCL.)</p>
| <p>I would probably create a generic configuration class, and have each module depend on one or several concrete configuration classes that are singletons. A module depends on a configuration class instance with settings that are significant for that module only, and optionally on one or more other configuration class instances with settings that pertain to more than one module. Due to the fact that the configuration objects are singletons the modules that share configuration objects automatically get the same settings.</p>
<p>You would create the configuration classes according to functionality, not according to module usage. The functionalities a module uses implicate which configuration objects it will need.</p>
<p>Every module that gets added to an application adds all the needed configuration classes as dependencies, other configuration classes are not added. The singleton configuration objects add themselves to a list (or registry if you will) of such objects on application startup. The application itself does not need to know about details, just loading and saving the settings from and to persistent storage is enough. It can OTOH make use of the same infrastructure if it needs to.</p>
<p>Generally I would implement everything in terms of interfaces, and leave the persistence mechanism outside. Thus you would be free later on to have configurations in INI files, the registry, or even a database (which would give you a simple way of implementing a history of configuration changes). I have found that I have not locked myself that much into a way of doing things since I started programming against interfaces instead of hierarchies of classes.</p>
|
How to hilight a section of a TableView cell as part of the filtering process? <p>The backstory: I am applying a filter to a TableView. It's a simple 'find the rows with this string' filter.</p>
<p>The requirement: I wish to hilight instances of the search term where they occur. </p>
<p>Thus far I can see no means of doing this. ITableColorProvider let's me apply colours to entire cells, but not to a fraction of it.</p>
<p>Clues most welcome.</p>
| <p>Looks like the <code>highlighting</code> method is for you</p>
<p>Since <a href="http://update.eclipse.org/downloads/drops/S-3.5M4-200812111908/eclipse-news-M4.html" rel="nofollow">3.5M4</a>, the existing owner draw support for JFace TableViewer and TreeViewer has been extended to allow multiple fonts within cells. For example, this can be used to highlight matching text in search results using a bold font. </p>
<p><img src="http://update.eclipse.org/downloads/drops/S-3.5M4-200812111908/images/multi-font-labels.png" alt="alt text" /></p>
|
Video shooting in iPhone <p>Is there a way to capture video from iPhone?</p>
| <p>Officially, no. Its not currently available via Apple, nor do they provide an API.</p>
<p>However if you Jailbreak the phone you can install unofficial applications that will let you do this. Or write your own of course!</p>
|
C# - Calling methods from inside class <p>How do you call a client codes methods from inside a class defined in the client code?</p>
<p>For example, I have a memory reading class, that can read values from the memory of a process at a certain address. I also have classes for managing the type of data that is read from memory (I am reading about an in-game 'object'. In the 'client code' I am calculating the 'base address' of that object in memory, then initializing my 'object class' using a constructor that takes the 'base address' as a parameter. This base class should then be able to tell me things about that object through methods because the objects know how far away from the base address a certain value is, such as 'health')</p>
<p>I tried using code such as this, and it gave me an error. 'ObjectManager' is the class which can read values from memory.</p>
<pre><code>class ObjectManager : Memory
{
LocalCharacter LocalPlayer = new LocalCharacter(this);
// other things omitted
}
// Error: Keyword 'this' is not available in the current context
</code></pre>
<p>and this, out of desperation:</p>
<pre><code>class ObjectManager : Memory
{
LocalCharacter LocalPlayer = new LocalCharacter(ObjectManager);
// other things omitted
}
// Error: Keyword 'this' is not available in the current context
</code></pre>
<p>But to no avail. What is the best way to do this?</p>
| <p>How about referencing 'this' in the constructor:-</p>
<pre><code>class ObjectManager : Memory
{
ObjectManager()
{
LocalPlayer = new LocalCharacter(this);
}
LocalCharacter LocalPlayer;
// other things omitted
}
</code></pre>
|
Group Box in WinForms <p>I have a question about design winforms.</p>
<p>Should I use, or not, group boxes in my forms? Is it good to the user? Give me some advantages, or disadvantages?</p>
<p>Some people think thar it's not goog enough to use.</p>
<p>What do you think about it?</p>
| <p>One reason is to group RadioButtons. </p>
<p>For every element you add to your UI you should ask yourself a few questions:</p>
<ul>
<li>Why do I add the element?</li>
<li>Why is it located in this position?</li>
<li>Why is it this color?</li>
<li>Why am I not using a standard control/color/font/...</li>
<li>etc.</li>
</ul>
<p>If you can find good answers for this questions, you can include it. But you should be able to explain why you used it.</p>
<p>So for a group box you might say:</p>
<ul>
<li>It saves space on my form because I can prevent a label from repeating.</li>
<li>It gives a clear seperation of other controls</li>
<li>Users know it is used to group controls</li>
</ul>
|
Canon Remote SDK Alternative? <p>Is there any Solution from another vendor? (With another Camera?)
Canon does not want to support the SDK anylonger.</p>
<p>The Solution shoul contain live preview, zooming and configurable Flash. A c# interface would be fine. </p>
<p>I know, the WIA interface but it isnt powerful enough.</p>
| <p>Have you looked into <a href="http://www.gphoto.org/" rel="nofollow">gphoto2</a>? This only runs under Unix-like systems (Linux, BSD, and probably MacOS), so it may not help under Windows.</p>
|
How can I tell when another process has stopped writing to a file in Perl? <p>I have a system which is writing files to a folder using FTP. I need to copy those files, but only when they FTP system has finished. How do I tell when the first process has finished writing.</p>
| <p>Another possibility is to have the process which uploads the files upload them under a temporary name and then rename them.</p>
<p>Renames happen atomically so there would be no case where the file was incomplete under its final name.</p>
<p>The copying process could ignore the temporary named files.</p>
|
Implementing and using the ICommand interface, MVVM <p>Although I deeply fell in love with the MVVM pattern there seem to be a lot of problems I cannot (yet) figure out for myself.</p>
<p>I wonder what the parameters of the methods of the IComamnd interface are good for</p>
<p>e.g. <code>void Execute(object parameter);</code></p>
<p>I tie my view to the view model like this</p>
<pre><code><Button Command="{Binding SomeCommand}" ... />
</code></pre>
<p>and so "<code>parameter</code>" will always be null.</p>
<p>Any hints are welcome.</p>
<p>Thanks!</p>
<p><strong>Update:</strong>
Darn, one minute after I posted this question I found the answer on <a href="http://stackoverflow.com/questions/335849/wpf-commandparameter-is-null-first-time-canexecute-is-called">Stackoverflow</a>. Obviously controls do have a CommandParameter property.</p>
| <p>You can add CommandParameter="" to pass a parameter. Usually you'll pass in the binding, or an id that's part of the binding, so the command knows what record to work with.</p>
|
Why is this query returning unwanted results? <p>Good morning,</p>
<p>I have a problem with this query:</p>
<pre><code>SELECT
P.txt_nome AS Pergunta,
IP.nome AS Resposta,
COUNT(*) AS Qtd
FROM
tb_resposta_formulario RF
INNER JOIN formularios F ON
F.id_formulario = RF.id_formulario
INNER JOIN tb_pergunta P ON
P.id_pergunta = RF.id_pergunta
INNER JOIN tb_resposta_formulario_combo RFC ON
RFC.id_resposta_formulario = RF.id_resposta_formulario
INNER JOIN itens_perguntas IP ON
IP.id_item_pergunta = RFC.id_item_pergunta
WHERE
RF.id_formulario = 2
GROUP BY
P.txt_nome,
IP.nome
</code></pre>
<p>This is the actual result of this query:</p>
<p>|Pergunta| Resposta |Qtd|<br />
|Produto |Combo 1MB | 3 |<br />
|Produto |Combo 2MB | 5 |<br />
|Produto |Combo 4MB | 1 |<br />
|Produto |Combo 6MB | 1 |<br />
|Produto |Combo 8MB | 4 |<br />
|Região |MG | 3 |<br />
|Região |PR | 2 |<br />
|Região |RJ | 3 |<br />
|Região |SC | 1 |<br />
|Região |SP | 5 | </p>
<p>These are the results I was expecting:</p>
<p>|Produto | Região |Qtd|<br />
|Combo 1MB | MG | 3 |<br />
|Combo 2MB | SP | 5 |<br />
|Combo 4MB | SC | 1 |<br />
|Combo 6MB | RJ | 1 |<br />
|Combo 8MB | PR | 2 | </p>
<p>I am using the PIVOT and UNPIVOT operators but the result is not satisfactory.</p>
<p>Has anyone already faced this situation before? Do you have any insight you can offer?</p>
<p>I already analyzed these links:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/213702/sql-server-2005-pivot-on-unknown-number-of-columns">http://stackoverflow.com/questions/213702/sql-server-2005-pivot-on-unknown-number-of-columns</a></li>
<li><a href="http://stackoverflow.com/questions/152770/transpose-a-set-of-rows-as-columns-in-sql-server-2000">http://stackoverflow.com/questions/152770/transpose-a-set-of-rows-as-columns-in-sql-server-2000</a></li>
<li><a href="http://stackoverflow.com/questions/428041/sql-server-2005-turn-columns-into-rows">http://stackoverflow.com/questions/428041/sql-server-2005-turn-columns-into-rows</a></li>
<li><a href="http://stackoverflow.com/questions/159456/pivot-table-and-concatenate-columns-sql-problem#159803">http://stackoverflow.com/questions/159456/pivot-table-and-concatenate-columns-sql-problem#159803</a> </li>
<li><a href="http://stackoverflow.com/questions/198716/pivot-in-sql-2005#199763">http://stackoverflow.com/questions/198716/pivot-in-sql-2005#199763</a></li>
</ul>
<p>Att,
Pelegrini</p>
| <p>The "obvious" answer is: because the query is incorrect. We really know nothing about the table structure and what you're trying to achieve. </p>
<p>Concerning at least one very basic problem in your query: you're expecting the columns <code>|Produto | Região |Qtd|</code> in your response, yet the query unambiguously selects the columns <code>Pergunta</code>, <code>Reposta</code> and <code>Qtd</code>, which coincides with the result you're getting. </p>
<p>How well are you acquainted with SQL at all? It may be worth it to read an introductory text. I'd suggest <a href="http://philip.greenspun.com/sql/" rel="nofollow">this</a> as a good introduction. (Uses Oracle, but the principles are the same)</p>
|
Easiest way to derive subset array of highest 10 values? <p>In javascript I have an array as follows: </p>
<pre><code>var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128, 1, 2, 2, 1, 18, 12, 60, 2, 28, 1, 17, 2, 3, 4, 2, 2, 2, 1, 27, 2, 17, 7, 2, 2, 2, 5, 1, 2, 4, 7, 1, 2, 1, 1, 1, 2, 1, 5, 7, 2, 7, 6, 1, 7, 1, 5, 8, 4];
</code></pre>
<p>And I am interested in finding a way (within one loop, not multiple) to derive a subset array of the highest 10 values, where the previous position of the value is the 'key' (so simulating a Map object): </p>
<p>eg:</p>
<pre><code>var fooTopTen = [[4, 128], [18, 128], [25, 60], [27, 28], [10, 27], [37, 27], [15, 21], [9, 18], [14, 18], [23, 18]];
</code></pre>
| <p>My previous answer used a reverse index table, but contained some bugs - which are now fixed - and was harder to understand than the following code.</p>
<p>This is actually the slowest of all solutions given in the answers - for maximum performance, check my other answer.</p>
<pre><code>var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128, 1, 2, 2, 1, 18, 12, 60, 2, 28, 1, 17, 2, 3, 4, 2, 2, 2, 1, 27, 2, 17, 7, 2, 2, 2, 5, 1, 2, 4, 7, 1, 2, 1, 1, 1, 2, 1, 5, 7, 2, 7, 6, 1, 7, 1, 5, 8, 4];
var fooTopTen = [];
// add index to values
for(var i = 0, len = foo.length; i < len; ++i)
fooTopTen.push([i, foo[i]]);
// sort first by value (descending order), then by index (ascending order)
fooTopTen.sort(function(t1, t2) {
return t2[1] - t1[1] || t1[0] - t2[0];
});
// shorten array to correct size
fooTopTen.length = 10;
// output top ten to check result
document.writeln('[[' + fooTopTen.join('], [') + ']]');
</code></pre>
<p>The second part of the comparison function (the one comparing the indices) is not needed, as <code>sort()</code> is stable in most implementations (this isn't required by ECMA <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array/Sort" rel="nofollow">according to MDC</a>). I'll leave it in as an example to how sorting with multiple requirements can be done...</p>
|
How to mount from command line like the Nautilus does? <p>On my Ubuntu linux box I can easily mount USB connected drives or CDROM clicking on devices icons that I can found on the Desktop.</p>
<p>For example if I click on a USB connected drive icon the following things happen:</p>
<ul>
<li>a /media/LABEL directory is automatically created (where LABEL is the label of the disk and may vary from disk to disk)</li>
<li>the filesystem on the device is mounted on /media/LABEL</li>
</ul>
<p>This process is significantly different from mounting using the <code>mount</code> command. In particular: </p>
<ul>
<li>you don't need to be root (or you don't need to modify /etc/fstab to allow ordinary user to mount the device)</li>
<li>the /media/LABEL directory is automatically created</li>
<li>the name of the directory changes according the volume label.</li>
</ul>
<p>There is a command line command that behaves like the Gnome GUI mounting facilities does?</p>
| <p>i guess what you are looking for is "gfvs-mount" (it recently replaced the "gnome-mount" most people talk about; both gnome-mount and pmount rely on HAL which is being phased out).</p>
<p>there's no man page so just type "gvfs-mount --help" for the details, or read here: <a href="http://omegamormegil.wordpress.com/2010/10/23/how-to-mount-filesystems-from-the-command-line-in-ubuntu-10-04-and-10-10/">How to mount filesystems from the command line in Ubuntu 10.04 and 10.10</a>;
basic usage is as simple as it may get: </p>
<p>"gvfs-mount --list" to get a list of mounted/mountable volumes; </p>
<p>"gvfs-mount [-u] " to [un]mount it, e.g. "gvfs-mount smb://server/share" or "gvfs-mount WINDOWS".</p>
<p>sadly, there seems to be a bug that results in a "Error mounting location: volume doesn't implement mount" message trying to mount by volume name, but "gvfs-mount -d /dev/" should work.</p>
<p>on my ubuntu 10.04 i can mount smb shares like that but not the windows partitions -- but it might be me doing it wrong, my need was mounting smb shares and didn't bother to research the issue with the ntfs partitions.</p>
|
YUV/PCM Visualizer to measure Lip Sync <p>I have a two dump files of raw video and raw audio from an encoder and I want to be able to measure the "Lip-sync". Imagine a video of a hammer striking an anvil. I want to go frame by frame and see that when the hammer finally hits the anvil, there is a spike in amplitude on the audio track.</p>
<p>Because of the speed that everything happens at, I cannot merely listen to the audio, i need to see the waveform in time domain.</p>
<p>Are there any tools out there that will let me see both the video and audio?</p>
| <p>If you are concerned about validating a decoder then generally from a validation perspective the goal is to check Audio and Video PTS values against a common real time clock.</p>
<p>Raw YUV and PCM files do not include timestamps. <strong>If</strong> you know the frame-rate and sample-rate you can use a raw yuv file viewer (I wrote my own) to figure out the time (from start of file) of a given frame in the video, and a tool like Audacity to figure out the time form start of file to a start of tone in the audio file. this still may not tell you the whole story since tools usually embed a delay between the audio and video in the ts/ps file. Or you can hook up ab OScope and go old school.</p>
|
When should I opt for IsolatedStorage versus AppData file storage? <p>I've recently discovered the <code>IsolatedStorage</code> facilities in .net, and I'm wondering when I should use them for my application data versus when I should use (e.g.) <code>Application.LocalUserAppDataPath</code>.</p>
<p>One thing that I've noticed is that <code>Application</code> doesn't exist outside of a winforms app, so it seems that <code>IsolatedStorage</code> might make sense for a class library that needs some specific storage, especially if that library might be used by both a web app and a winforms app. Is that the only distinguishing point, or is there more to it?</p>
<p>(As a rule, up 'til now, I've made the app provide a file stream to the library when the library might need some sort of external storage--- in general, I don't like the idea of a library having some sort of state external to the caller's context.)</p>
| <p>IsolatedStorage has a couple interesting features that might make you opt for it: </p>
<ul>
<li><p>Even very low trusted applications (such as click-once) can access isolated storage. Not all applications can have access to AppData. Depending on the security policy imposed on the application, IsolatedStorage can also be limited, but it usually is more accessible than AppData/file system.</p></li>
<li><p>IsolatedStorage storage requirements can be controlled by administrator policy.</p></li>
<li><p>You don't have to know where or how isolated storage data is stored. It has a uniform API for accessing it on all systems you can completely ignore the underlying path that it is stored in. As you noted, this is very useful for a library which may have no idea how the hosting application stores data.</p></li>
<li><p>You can also have data stored data in isolated storage with vary levels of isolation very easily. See <a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragescope.aspx" rel="nofollow">the IsolatedStorageScope values</a> for more information. This is its namesake, so I guess I should have listed this point first :) </p></li>
</ul>
<p>On the downside:</p>
<ul>
<li>IsolatedStorage has some notable limits in the amount of data you can store there. For example, application preferences will be fine, but it is not appropriate for documents. </li>
</ul>
<p>Some useful links: </p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx" rel="nofollow">Introduction to Isolated Storage</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/8dzkff1s(VS.80).aspx" rel="nofollow">Performing Isolated Storage Tasks</a> </li>
</ul>
|
How to calculate permutations in linear time, with a twist <p>I have a resource scheduling issue in Java where things need to be sequenced, but there are restrictions on what resources can be next to each other. A good analogy is a string of "digits", where only certain digits can be next to each other. My solution was recursive, and works fine for small strings, but run time is O(X^N), where X is the number of possible digits (the base), and N is the length of the string. It quickly becomes unmanageable.</p>
<p>Using the compatibility matrix below, here are a few examples of allowed strings<br>
Length of 1: 0, 1, 2, 3, 4<br>
Length of 2: 02, 03, 14, 20, 30, 41<br>
Length of 3: 020, 030, 141, 202, 203, 302, 303, 414<br></p>
<pre>
0 1 2 3 4
---------------------
0| 0 0 1 1 0
1| 0 0 0 0 1
2| 1 0 0 0 0
3| 1 0 0 0 0
4| 0 1 0 0 0
</pre>
<p>My solution for counting all strings of length N was start with an empty string, permute the first digit, and make a recursive call for all strings of length N-1. The recursive calls check the last digit that was added and try all permutations that can be next to that digit. There are some optimizations made so that I don't try and permute 00, 01, 04 every time, for example - only 02, 03, but performance is still poor as it scales from base 5 (the example) to base 4000.</p>
<p>Any thoughts on a better way to count the permutations other than trying to enumerate all of them?</p>
| <p>If you just want the number of strings of a certain length, you could just multiply the compatibility matrix with itself a few times, and sum it's values.</p>
<blockquote>
<p><em>n</em> = <em>length of string</em><br>
<em>A</em> = <em>compatibility matrix</em><br>
<em>number of possible strings</em> = sum of <em>A</em><sup><em>n</em>-1</sup></p>
</blockquote>
<p>A few examples:</p>
<pre><code>n = 1
| 1 0 0 0 0 |
| 0 1 0 0 0 |
| 0 0 1 0 0 |
| 0 0 0 1 0 |
| 0 0 0 0 1 |
sum: 5
n = 3
| 2 0 0 0 0 |
| 0 1 0 0 0 |
| 0 0 1 1 0 |
| 0 0 1 1 0 |
| 0 0 0 0 1 |
sum: 8
n = 8
| 0 0 8 8 0 |
| 0 0 0 0 1 |
| 8 0 0 0 0 |
| 8 0 0 0 0 |
| 0 1 0 0 0 |
sum: 34
</code></pre>
<p>The original matrix (row <em>i</em>, column <em>j</em>) could be thought of as the number of strings that start with symbol <em>i</em>, and whose next symbol is symbol <em>j</em>. Alternatively, you could see it as number of strings of length <strong>2</strong>, which start with symbol <em>i</em> and ends with symbol <em>j</em>.</p>
<p>Matrix multiplication preserves this invariant, so after exponentiation, <em>A</em><sup><em>n</em>-1</sup> would contain the number of strings that start with symbol <em>i</em>, has length <em>n</em>, and ends in symbol <em>j</em>.</p>
<p>See <a href="http://en.wikipedia.org/wiki/Exponentiation_by_squaring" rel="nofollow">Wikipedia: Exponentiation by squaring</a> for an algorithm for faster calculation of matrix powers.</p>
<p>(Thanks stefan.ciobaca)</p>
<p>This specific case reduces to the formula:</p>
<blockquote>
<p><em>number of possible strings</em> = <em>f</em>(<i>n</i>) = 4 + Σ<sub><em>k</em>=1..<em>n</em></sub> 2<sup>⌊<sup><em>k</em>-1</sup>⁄<sub>2</sub>⌋</sup> = <em>f</em>(<i>n</i>-1) + 2<sup>⌊<sup><em>n</em>-1</sup>⁄<sub>2</sub>⌋</sup></p>
</blockquote>
<pre><code>n f(n)
---- ----
1 5
2 6
3 8
4 10
5 14
6 18
7 26
8 34
9 50
10 66
</code></pre>
|
Examples of using F# to query Entity Framework <p>I'm looking all over Google to find an example or tutorial about using F# to query an Entity data source.</p>
<p>Honestly I haven't found much. Have any of you had any luck ? </p>
| <p>The following is an example I was able to pieces together from what i found on this <a href="http://bloggemdano.blogspot.com/2008/11/linq-to-sql-in-f.html">blog</a></p>
<pre><code>open Microsoft.FSharp.Linq.QuotationEvaluation
open Microsoft.FSharp.Linq
let IsPermited (serviceName:string) =
//Instantiate the Entity
let data = new BusModelContainer()
//Build your query
let services = Query.query <@ seq{ for service in data.ServiceSet do
service.Name.Equals(serviceName) && service.IsEnabled then
yield service } @>
if Seq.is_empty services then
false
else
true
</code></pre>
<p>Here is the code from the blog that showed me how to go about selecting from an Entity</p>
<pre><code> let db = new FSharpSampleDB(connString)
Query.query <@ seq { for c in db.Customers do
if id = c.CustomerId then
yield (new Customer(c.CustomerId, c.Name, c.Balance))}
|> Seq.hd @> :> ICustomer
</code></pre>
|
Oracle9i: Filter Expression Fails to Exclude Data at Runtime <p>I have a relatively simple select statement in a VB6 program that I have to maintain. (Suppress your natural tendency to shudder; I inherited the thing, I didn't write it.)</p>
<p>The statement is straightforward (reformatted for clarity):</p>
<pre><code>select distinct
b.ip_address
from
code_table a,
location b
where
a.code_item = b.which_id and
a.location_type_code = '15' and
a.code_status = 'R'
</code></pre>
<p>The table in question returns a list of IP addresses from the database. The key column in question is <code>code_status</code>. Some time ago, we realized that one of the IP addresses was no longer valid, so we changed its status to <code>I</code> (invalid) to exclude it from appearing in the query's results.</p>
<p>When you execute the query above in SQL Plus, or in SQL Developer, everything is fine. But when you execute it from VB6, the check against <code>code_status</code> is ignored, and the invalid IP address appears in the result set.</p>
<p>My first guess was that the results were cached somewhere. But, not being an Oracle expert, I have no idea where to look. </p>
<p>This is <em>ancient</em> VB6 code. The SQL is embedded in the application. At the moment, I don't have time to rewrite it as a stored procedure. (I will some day, given the chance.) But, I need to know what would cause this disparity in behavior and how to eliminate it. If it's happening here, it's likely happening somewhere else.</p>
<p>If anyone can suggest a good place to look, I'd be very appreciative.</p>
| <p>Some random ideas:</p>
<ul>
<li><p>Are you sure you committed the changes that invalidate the ip-address? Can someone else (using another db connection / user) see the changed code_status?</p></li>
<li><p>Are you sure that the results are not modified after they are returned from the database?</p></li>
<li><p>Are you sure that you are using the "same" database connection in SQLPlus as in the code (database, user etc.)?</p></li>
<li><p>Are you sure that that is indeed the SQL sent to the database? (You may check by tracing on the Oracle server or by debugging the VB code). Reformatting may have changed "something".</p></li>
</ul>
<p>Off the top of my head I can't think of any "caching" that might "re-insert" the unwanted ip. Hope something from the above gives you some ideas on where to look at.</p>
|
getting a property of a java bean of unknown class <p>I'd like to be able to call "getProgram" on objects which have that method, without knowing which class they belong to. I know I should use an interface here, but I'm working with someone else's code and can't redesign the classes I'm working with. I thought BeanUtils.getProperty might help me, but it seems it only returns strings. Is there something like Beanutils.getProperty that will return a cast-able object? Or another, smarter way to work with two similar classes that don't share an interface?
thanks,
-Morgan</p>
| <p>Use PropertyUtils (from apache commons-beanutils) instead of BeanUtils.</p>
<p>It has a getProperty(Object bean, String name) method that returns an Object instead of a String.</p>
<p>See the <a href="http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/PropertyUtils.html">JavaDoc</a> for more information.</p>
|
Swapping two rows in MS SQLServer retaining the original primary key and without manual update <p>I have the following problem : I have rows like </p>
<pre><code>ID CODE NAME .........
1 h1100h1 Cool example1 .........
2 h654441 Another cool1 .........
</code></pre>
<p>I would like to swap them retaining all old primary keys and constraints. Of course, I can easily solve this manually by updating the rows. I am kind of wondering whether anybody has any excellent solution for this kind of problem instead of just executing update command manually. I really really appreciate any suggestions or recommendations.</p>
| <p>I haven't tested this, but I think it will work. I'm assuming that id is a single-column Primary Key. If that's not the case then you will need to adjust this code slightly to handle the PK.</p>
<pre><code>UPDATE
T1
SET
column_1 = T2.column_1,
column_2 = T2.column_2,
...
FROM
dbo.My_Table T1
INNER JOIN dbo.My_Table T2 ON
T2.id =
CASE
WHEN T1.id = @id_1 THEN @id_2
WHEN T1.id = @id_2 THEN @id_1
ELSE NULL
END
WHERE
T1.id IN (@id_1, @id_2)
</code></pre>
|
Why is System.Object not abstract in .NET? <p>I know it is commonly used as a lock object, but is that really sufficient reason?
What is the meaning of</p>
<pre><code>object o = new object();
</code></pre>
<p>An non-abstract class is something that represents actual objects. "asdasdf" is a string. What actual instance can there be of "object" class? It doesn't make sense, OOP-wise. My question is if there is some practical reason for its existence (besides being used as a lock object).</p>
| <p>The easiest way to answer that question is to ask another one: is there any reason for the Object class to be abstract? Since there is no reason for it to be abstract, it's not.</p>
|
Is it possible to achieve the "Aero Glass" look on XP? <p>Does anyone know any kind of framework that enables (not exactly the same, but) Vista's Aero Glass on XP?</p>
<p>I need to develop a little desktop application with WPF, which has a Vista-like UI on XP. I don't need exactly the Aero Glass, some UI like "Windows Live Messenger" will do the thing.
Is there any way to make it a reality?</p>
| <p>If you really mean Aero <strong>Glass</strong> then I think you're out of luck. The hardware acceleration required to create this effect is only supported via Vista's new DWM (Desktop Window Manager), which works by compositing multiple windows together into one rendered layer. </p>
<p>If you just want transparency and non-rectangular windows then this can definitely be achieved in XP, as evidenced by the fact that Windows Live Messenger can do it. Have a look at <a href="http://msdn.microsoft.com/en-us/library/ms997507.aspx" rel="nofollow">Layered Windows</a> in MSDN.</p>
|
getting the list of all functions executed like call stack in asp.net <p>I am having trouble with debugging one of the problems that I am having in our website. This is the problem. I have a webpage that contains the photo of an employee and information related to the employee. When the user logins to our website, we are storing the details of the employee in session. I am setting the image url for the photo of an employee as follows.</p>
<pre><code>imgEEPhoto.ImageUrl = imgPhoto.aspx?Company=XXXX&Empno=YYYY.
</code></pre>
<p>Inside the page imgPhoto.aspx, I am checking if the session is alive for that user. when I login to the page that has the employee photo sometimes the photo is not displayed. It is because I am checking whether the session is alive inside the imgPhoto.aspx page. sometimes the session is alive and sometimes the session is not alive. It looks like there is some function that is setting the session to null asynchronously. I am not knowing how to track that function. so I am thinking that inside the imgPhoto.aspx page, if I can get the list of all functions that have been executed so far, I could track the function that is resetting the session. Is there a way to find this? </p>
<p>If there is no another way to debug this problem, please let me know.</p>
<p><strong>EDIT:</strong></p>
<p>The page imgPhoto.aspx gets company and empno as query string parameters. Then the page gets the binary data based on company and empno and uses Response.BinaryWrite() to display photo. The session check is at the beginning of this function. so somewhere before this function is called and after the end of all the functions in mainpage the session is getting timedout. Actually I am not sure if it is getting timedout because I can print the sessionid. But I cannot access variables stored in session.</p>
<p>If I print the callstack inside the function, it is giving the list of functions that are executed inside that page. It is not giving all the functions that are executed before that function.</p>
| <p>There's no built-in facility in .NET to list all functions called, although you can print the call-stack at a specific point (like exceptions do).</p>
<p>I'd suggest looking for a code-coverage profiler if this is the route you want to take. </p>
|
calling methods on an instance with getattr [ python ] <p>I was trying to write some code that would check if an item has some attributes , and to call them . I tried to do that with getattr , but the modifications wouldn't be permanent . I made a "dummy" class to check upon this .
Here is the code I used for the class :</p>
<pre><code>
class X:
def __init__(self):
self.value = 90
def __get(self):
return self.value
def __set(self,value):
self.value = value
value = property(__get,__set)
x = X()
print x.value # this would output 90
getattr(x,"value=",99) # when called from an interactive python interpreter this would output 99
print x.value # this is still 90 ( how could I make this be 99 ? )
</code></pre>
<p>Thanks !</p>
| <p>You need to do something like</p>
<pre><code>class X:
def __init__(self):
self._value = 90
def _get(self):
return self._value
def _set(self, value):
self._value = value
value = property(_get, _set)
</code></pre>
<p>Note that the "internal" variable has to have a different name than the property (I used <code>_value</code>).</p>
<p>Then,</p>
<pre><code>setattr(x, 'value', 99)
</code></pre>
<p>should work.</p>
|
how to select only the background in jQuery <p>I would like to add two events to my items.</p>
<p>One for the "background" of the document: <code>$(document).click(function() {do()});</code></p>
<p>One for the divs in the document: <code>$("div").click(function() {do2()});</code></p>
<p>The problem is that when I click on a <code>div</code>, both functions, <code>do</code> and <code>do2</code> are called.</p>
<p>How can I thus tell to call <code>do()</code> only when I click on no element?</p>
<p>Thanks for your help,</p>
<p>J.</p>
<hr>
| <p>The terms you're looking for here are Event Propagation or Event Bubbling.</p>
<p>The event handling in "modern" browsers (which is the model most libraries hook into) works by bubbling up the document tree. What that means is if you have html document structure like this</p>
<pre><code><body>
<div>
<ul>
<li>Foo</li>
<li>Bar</li>
<li>Baz</li>
</ul>
</div>
</body>
</code></pre>
<p>and someone clicks on Foo, the following event stuff happens</p>
<ol>
<li>The <li> receives a click event</li>
<li>The <ul> receives a click event</li>
<li>The <div> receives a click event</li>
<li>The <body> receives a click event</li>
</ol>
<p>That's what's happening to you. There's two things you can do to prevent this.</p>
<p>The first, as many have suggested is, if your event handler returns false, then event propagation will stop at the element that has been clicked. (this is how jQuery handles it, each library has a different approach)</p>
<pre><code>$(document).ready(function() {
//hookup events for entire body of document
$('body').bind('click', function(e){
//do clicked body stuff
});
//hookup our divs, returning false to prevent bubbling
$('div').bind('click', function(e){
//do clicked div stuff
return false; //stop event propagation
});
});
</code></pre>
<p>A second, some would argue better, approach is to use event delegation. Event delegation, in the context of Javascript and the DOM, is where you attach a single event handler to an outer element (in this case the body), and then based on what element was originally clicked, take a particular action.</p>
<p>Something like this.</p>
<pre><code>$(document).ready(function() {
//event delegate
$('body').bind('click', function(e){
var originalElement = e.srcElement;
if(!originalElement){originalElement=e.originalTarget;}
if ($(originalElement).is('div')) {
console.log("A div!");
}
else if ($(originalElement).is('div#inside')) {
console.log("A Specific Div!");
}
else{
console.log("Something else!");
}
});
});
</code></pre>
<p>The benifits of this are two-fold. First, you can centralize all your event handling code into a single place in your code. The second (more important in my mind) is attaching a single event handler consumes much less browser memory and sets you up for better performance moving forward.</p>
|
Linux Socket Buffer Imbalance <p>I have a simple scenario, where two servers are connected through a gigabit link.
I run iperf on both sides to measure the throughput.</p>
<p>What surprises me, whenever I run the traffic bidirectionally, it always favor one side only (eg. ~900Mbps vs. ~100Mbps). If I run the traffic unidirectional, each side got ~900Mbps.</p>
<p>If I connect one of the server (the lower memory) to another server, the bidirectional traffic was balanced out. So definitely not the iperf problem.</p>
<p>Other facts:</p>
<ul>
<li>One server has pretty big memory (~12GB), while the other only has ~4GB.</li>
<li>Both server have the same TCP memory configurations, in this case, the same TCP w/r mem, core w/r mem, TX queue length.</li>
<li>Both are using the same ethernet card (E1000 driver).</li>
<li>Same Linux version, RedHat 2.6.9. The big server runs 64-bit version, due to the 12GB memory.</li>
<li>Both have no other traffic, beside small SSH, and occasional ping every second.</li>
<li>Both have "tcp_moderate_rcvbuf" on.</li>
</ul>
<p>Questions:</p>
<ol>
<li>Why the imbalanced?</li>
<li>Which area should I look to see if the socket buffer is heavily utilized on one side, and how?</li>
<li>Beside iperf, what are other good software (not hardware/tester) to measure the performance?</li>
<li>What's the best way to get an insight on how Linux allocating the buffer, from the Ethernet ring buffer, TCP buffer, socket buffer, and other buffers?</li>
<li>What could be the other entity that might impact the throughput that I haven't covered above?</li>
<li>Is there any documentation that explains how Linux distributes the memory allocation between user, kernel, device drivers, and network stack?</li>
</ol>
<p>Any advise is deeply appreciated.</p>
| <p>Suggestions:</p>
<ul>
<li>Take a look at the actual settings on your Ethernet interfaces. "ethtool" is one way to get a thorough look. "ifconfig" tells you something, though less. (Both probably in /usr/sbin/.) Finding kernel messages with "dmesg" might tell you something. Looking at link error rates might reveal something too.</li>
<li>Querying your switch for its idea of port state might also reveal what's really going on. (Not relevant if you're just using a CAT5 cable between interfaces, without a switch.)</li>
<li>Since one pair of machines works as you expect, while another pair of machines doesn't, I'm thinking about some anomaly with duplex autonegotiation. Half-duplex is unusual for GigE but perhaps your switch or NIC is causing it. Discovering a half-duplex setting anywhere, or especially a disagreement between a host and its switch about port state, could be possible cause.</li>
</ul>
|
UpdatePanelAnimationExtender: No animation when certain button clicked <p>I have a GridView inside an UpdatePanel that is populated when a search is performed on the page. When it is populated or the page changed, it performs a fade animation. There are other operations that I want to perform that update the UpdatePanel, but I don't want these to perform these fade animations. The closest I have found on the ASP forums is: <a href="http://forums.asp.net/p/1037038/1487096.aspx" rel="nofollow">http://forums.asp.net/p/1037038/1487096.aspx</a></p>
<p>The problem with the solution proposed in that thread is that there is no way to catch the Updated and Updating events to animate. Any ideas?</p>
<p>Thanks,</p>
<p>Nick</p>
| <p>Nick,</p>
<p>Is it possbile to consider using JQuery to do the animations? May give you more control on the elements than just the use of the UpdatePanelAnimationExtender.</p>
<p><a href="http://jquery.com/" rel="nofollow">http://jquery.com/</a></p>
<p><a href="http://docs.jquery.com/UI/Effects" rel="nofollow">http://docs.jquery.com/UI/Effects</a></p>
|
Facebook authorization problem <p>I'm working on a facebook app and there's something I'm just not understanding about how their authorization system works.</p>
<p>Our basic setup is this</p>
<p>canvas URL = domain.com/facebook</p>
<p>This is a simple page with an FBML Iframe element that points to domain.com/facebook/app which is an HTML page that serves up a Flash Application. </p>
<p>The Flash Application requests additional data from our application server - some of those requests ask for facebook data (such as a list of friend IDs).</p>
<p>So Flash then makes a request to domain.com/resources/facebook/friends - this is a PHP page which creates a Facebook instance (their PHP library) and performs the necessary call to their API and returns the data.</p>
<p>However, the request to this URL (by flash) doesn't validate, so it is then redirected to their login when then itself redirects back my canvas URL with two parameters - <strong>auth_token</strong> and <strong>next</strong>. So the request is valid, but the redirect breaks the flash call.</p>
<p>So, I'm trying to figure out how to make these other API calls (when themselves mace facebook API calls) be facebook-vaildated from the get-go.</p>
| <p>Ok, I figured it out.</p>
<p>As it turns out, Flash already follows the redirects - all I needed to do was detect (at the canvas URL) when there was an authorization request (noted by the presence of <strong>auth_token</strong> and <strong>next</strong>) and <em>include</em> the auth_token as a GET parameter when I redirected to the next URL (basically, forward the auth_token on to the original request).</p>
<p>So, contrary to what I said above, the redirect did NOT break the flash call - it just didn't have enough data to be a valid request.</p>
|
Editing shortcut (.lnk) properties with Powershell <p>I've found a nasty VBS way to do this, but I'm looking for a native PoSh procedure to edit the properties of a .LNK file. The goal is to reach out to remote machines, duplicate an existing shortcut with most of the correct properties, and edit a couple of them.</p>
<p>If it would just be easier to write a new shortcut file, that would work too.</p>
| <pre><code>Copy-Item $sourcepath $destination ## Get the lnk we want to use as a template
$shell = New-Object -COM WScript.Shell
$shortcut = $shell.CreateShortcut($destination) ## Open the lnk
$shortcut.TargetPath = "C:\path\to\new\exe.exe" ## Make changes
$shortcut.Description = "Our new link" ## This is the "Comment" field
$shortcut.Save() ## Save
</code></pre>
<p>Found the VB version of the code here:
<a href="http://www.tutorialized.com/view/tutorial/Extract-the-target-file-from-a-shortcut-file-.lnk/18349">http://www.tutorialized.com/view/tutorial/Extract-the-target-file-from-a-shortcut-file-.lnk/18349</a></p>
|
Discrimanant taskkill.exe for excel.exe <p>I have to run Excel on a server and to kill the excel.exe process I am using taskkill.exe:</p>
<p>System.Diagnostics.Process.Start("taskkill.exe", "-im excel.exe /f");</p>
<p>My only problem is that if there is someone who is also using the server who is working on excel (It could happen) then their processes will be killed also. Is there anyway around this to only kill the excel files created by my code? Any help would be great. Thanks!</p>
| <p>Keep track of the PID of the processes you launch and kill them with taskkill.exe /pid NUMBER</p>
|
OpenGL performance difference on Linux and WindowsXP <p>I've noticed that a OpenGL app I've been working on has significant performance difference when run on Linux vs WindowsXP. </p>
<p>Granted, there are a lot of textures and shadow buffers but I would estimate that the app runs about 10x <strong>slower</strong> on Windows XP. </p>
<p>Any ideas? </p>
<p>Any suggestions for porting the code to DirectX? Can that be done easily or would a re-write be needed? </p>
<p>Running of different hardware. I don't have the specs of the Linux box, but my xp box is Intel Duo Core 2 with Nvidia Quadro FX 1500. The linux box video card was some sort of Nvidia Geforece (It was a University computer).</p>
<p>Some initiation code:</p>
<pre><code>FlyWindow::FlyWindow() :
GlowWindow("fly", 300, 100, // GlowWindow::autoPosition, GlowWindow::autoPosition,
700, 500,
Glow::rgbBuffer | Glow::doubleBuffer |
Glow::depthBuffer | Glow::multisampleBuffer,
Glow::keyboardEvents | Glow::mouseEvents | Glow::dragEvents |
/*Glow::menuEvents | */ Glow::motionEvents | Glow::visibilityEvents |
Glow::focusEvents /* set ::glutEntryFunc */ ),
W(700), H(500),
flock(10),
lastSeconds(myclock.getSecondsSinceStart())
{
myfps = FPScounter();
GLdraw<float>::initGL(W,H);
// Add a bouncing checkerboard
MovingCB = Point3d<double>(50, 2, 50);
Glow::RegisterIdle(this);
bDebug = false;
m_bLookAtCentroid = true;
m_bLookAtGoal = false;
}
</code></pre>
<p>Thanks</p>
| <p>Comparing the Quadro to a GeForce is a big mistake. They may both be "graphics" cards but that is where the similarity ends.</p>
<p>The Quadro is designed for high end rendering and not games. From the wikipedia article on the Quadro:</p>
<blockquote>
<p>Their designers aimed to accelerate CAD (Computer-Aided Design) and DCC (digital content creation), and the cards are usually featured in workstations. (Compared to the NVIDIA GeForce product-line, which specifically targets computer-gaming).</p>
</blockquote>
<p>Quadro is going to preform very differently then the GeForce, regardless of operating system.</p>
|
What language has the easiest and most robust date parsing? <p>I know java has the SimpleDateFormat which seems fairly powerful, but you need to know the format ahead of time to use it correctly.<br />
TCL's clock scan function seems to be the easiest and most powerful I've seen.</p>
<p>e.g. clock scan "1/08/2009 12:33:01 AM" will work just as well as<br />
clock scan "8-Jan-2009 12:33:01"</p>
<p><strong>EDIT:</strong> Okay, removing the idea that it has to be a built-in feature. Are Perl and Python the best available?</p>
| <p>Perl's Date::Parse module (I don't know that it can be considered builtin to the language, but it's a CPAN module so that's good enough for me) has saved me countless hours on data conversion projects. From the documentation (<a href="http://metacpan.org/pod/Date::Parse" rel="nofollow">http://metacpan.org/pod/Date::Parse</a>):</p>
<pre><code>Below is a sample list of dates that are known to be parsable with Date::Parse:
1995:01:24T09:08:17.1823213 ISO-8601
1995-01-24T09:08:17.1823213
Wed, 16 Jun 94 07:29:35 CST Comma and day name are optional
Thu, 13 Oct 94 10:13:13 -0700
Wed, 9 Nov 1994 09:50:32 -0500 (EST) Text in ()'s will be ignored.
21 dec 17:05 Will be parsed in the current time zone
21-dec 17:05
21/dec 17:05
21/dec/93 17:05
1999 10:02:18 "GMT"
16 Nov 94 22:28:20 PST
</code></pre>
|
Converting serial port data to TCP/IP in a linux environment <p>I need to get data from the serial port of a Linux system and convert it to TCP/IP to send to a server. Is this difficult to do? I have some basic programming experience but not much experience with Linux. Are there any open source applications that do this?</p>
| <p>You don't need to write a program to do this in Linux. Just <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-4.html">pipe</a> the serial port through <a href="http://netcat.sourceforge.net/">netcat</a>.</p>
<pre><code>netcat www.example.com port < /dev/ttyS0
</code></pre>
<p>Just replace the address and port information. Also, you may be using a different serial port (i.e. change the <code>/dev/ttyS0</code> part). You can use the <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?stty">stty</a> or <a href="http://setserial.sourceforge.net/setserial-man.html">setserial</a> commands to change the parameters of the serial port (baud rate, parity, stop bits, etc.).</p>
|
Restoring MySQL database from physical files <p>Is it possible to restore a MySQL database from the physical database files. I have a directory that has the following file types:</p>
<p>client.frm<br />
client.MYD<br />
client.MYI </p>
<p>but for about 20 more tables.</p>
<p>I usually use mysqldump or a similar tool to get everything in 1 SQL file so what is the way to deal with these types of files?</p>
| <p>A MySQL MyISAM table is the combination of three files:</p>
<ul>
<li>The FRM file is the table definition.</li>
<li>The MYD file is where the actual data is stored.</li>
<li>The MYI file is where the indexes created on the table are stored.</li>
</ul>
<p>You should be able to restore by copying them in your database folder (In linux, the default location is <code>/var/lib/mysql/</code>)</p>
<p>You should do it while the server is not running.</p>
|
Visual Studio: How to figure out where this type is defined? <p>i have an interface - one of whose members returns a variable of type**Object**.</p>
<p>In my attempts to try to use this returned variable, i discovered that it isn't just an "<strong>Object</strong>", but is actually a "<strong>mshtml.HTMLDocumentClass</strong>", as you can see in the following screenshot:</p>
<p><img src="http://i43.tinypic.com/svmfbn.jpg" alt="alt text" /></p>
<p>In my case, this is perfect, since it appears (through code-insight), that the object then supports many of the methods and properties i'm actually trying to use (that i was about to use through late binding).</p>
<p><strong>The question is:</strong> </p>
<ul>
<li>Where is this type coming from? </li>
<li>Where is it defined</li>
</ul>
<p>so i may convert my code from:</p>
<pre><code>object webDocument = ie.Document;
</code></pre>
<p>to</p>
<pre><code>mshtml.HTMLDocumentClass webDocument = (mshtml.HTMLDocumentClass)ie.Document;
</code></pre>
<p><hr /></p>
<p>If you're wondering, <strong>ie</strong> is declared as:</p>
<pre><code>IWebBrowser2 ie;
</code></pre>
<p>and IWebBrowser2's declaration of ie.Document is:</p>
<pre><code>[ComImport, DefaultMember("Name"),
Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
SuppressUnmanagedCodeSecurity]
public interface IWebBrowser2
{
...
object Document { [return: MarshalAs(UnmanagedType.IDispatch)] [DispId(0xcb)] get; }
...
}
</code></pre>
<p>So it's an <strong>Object</strong>, that also supports <strong>IDispatch</strong>. Nowhere in any of my code is mentioned a type called "mshtml.HTMLDocumentClass".</p>
<p><strong>Note:</strong> If you think it can be cast to </p>
<pre><code>System.Windows.Forms.HtmlDocument
</code></pre>
<p>you would be mistaken.</p>
<p><hr /></p>
<p>If you're wondering why i'm doing this, then change all variable names and class types into random strings to obfuscate the example.</p>
<p><hr /></p>
<p><a href="http://stackoverflow.com/questions/484770/visual-studio-how-to-figure-out-where-this-type-is-defined#484830">chakrit</a> suggested using "*Go to Definition** of the <strong>ie.Document</strong> member, which unfortunatly goes to the declaration of ie.Document:</p>
<p><img src="http://i41.tinypic.com/96dwmd.jpg" alt="alt text" /></p>
<p>And also the declaration of <strong>Object</strong> brings me to the declaration of <strong>Object</strong>:</p>
<p><img src="http://i41.tinypic.com/28qta9z.jpg" alt="alt text" /></p>
<p><hr /></p>
<p><a href="http://stackoverflow.com/questions/484770/visual-studio-how-to-figure-out-where-this-type-is-defined#484830">chakrit</a> had a really good suggestion:</p>
<pre><code>public static string TellMeAboutThisObject(object obj)
{
Type t = obj.GetType();
Assembly asm = t.Assembly;
return
"Type Name: "+t.FullName+Environment.NewLine+
"Namspace: " + t.Namespace+Environment.NewLine+
"From assembly: "+ asm.FullName+Environment.NewLine+
"Located at: "+asm.Location;
}
</code></pre>
<p>Which in my case returns:</p>
<blockquote>
<p><strong>Type Name:</strong> mshtml.HTMLDocumentClass</p>
<p><strong>Namspace:</strong> mshtml </p>
<p><strong>From assembly:</strong> Microsoft.mshtml, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</p>
<p><strong>Located at:</strong> C:\Windows\assembly\GAC\Microsoft.mshtml\7.0.3300.0__b03f5f7f11d50a3a\Microsoft.mshtml.dll</p>
</blockquote>
<p>So, in my case it's the damnest thing that someone is automagically adding a reference to a managed assembly - when i was trying to interop with COM directly.</p>
| <p>A quick search on MSDN gets me to this page which describes how to get the document interface:
<a href="http://msdn.microsoft.com/en-us/library/bb508515(VS.85).aspx" rel="nofollow">About MSHTML</a><br/>
Note: I cannot try any of this as I am stuck with VS.80</p>
|
MSTest.exe not finding app.config <p>I'm currently trying to run MSTest.exe from NCover, but I believe the question could apply generally to running MSTest.exe from the command line.</p>
<p>If I have the "/noisolation" argument, then MSTest.exe appears to find and use the app.config as expected. Without it, NCover doesn't capture any coverage information. From my research so far, it seems NCover needs /noisolation. So the question is how to get my *.config files to work when that argument is passed.</p>
<p>My NCover settings are:</p>
<p><strong>Application to Profile</strong><br />
C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe</p>
<p><strong>Working Folder</strong><br />
C:\Documents and Settings\MyProfile\My Documents\Visual Studio 2008\Projects\XYZ\XYZ.CoreTest\bin\Debug</p>
<p><strong>Application arguments</strong><br />
/noisolation /testcontainer:"C:\Documents and Settings\MyProfile\My Documents\Visual Studio 2008\Projects\XYZ\XYZ.CoreTest\bin\Debug\XYZ.CoreTest.dll"</p>
<p><br /><br />
Update: I added a trace showing that my config is (not surprisingly) trying to read from "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe.Config".</p>
<p>Update 2: If at all possible, I don't want to edit MSTest.exe.Config. That just isn't terribly portable.</p>
| <p>From Craig Stuntz in a comment at <a href="http://devlicio.us/blogs/derik_whittaker/archive/2008/07/23/mstest-why-i-hate-you-you-cause-me-too-much-friction.aspx">link text</a></p>
<p>How to do this with MSTest.</p>
<ol>
<li><p>In Solution Explorer, right-click the Solution (not the Project).</p></li>
<li><p>Click Add, New Item</p></li>
<li><p>In Categories, select Test Run Configuration</p></li>
<li><p>Now choose the Test Run Configuration item and add it to your project</p></li>
<li><p>In Solution Explorer, double-click the Test Run Configuration you just created</p></li>
<li><p>Click the Deployment item</p></li>
<li><p>Add your config file as a deployed file (or deploy the entire folder which contains it, if appropriate)</p></li>
</ol>
<p>This took me a little while to figure out, but I'm in a similar situation and it does work for me.</p>
|
Are There Any Good Ruby, Rails or .Net Libraries for Working with Barcodes? <p>Does anyone know any good Ruby, Rails or .Net specific libraries for working with barcodes?</p>
| <p>for ruby there's the barby gem and redux for rails</p>
|
How would you determine where each property and method of a Python class is defined? <p>Given an instance of some class in Python, it would be useful to be able to determine which line of source code <em>defined</em> each method and property (e.g. to implement [1]). For example, given a module ab.py</p>
<pre><code>class A(object):
z = 1
q = 2
def y(self): pass
def x(self): pass
class B(A):
q = 4
def x(self): pass
def w(self): pass
</code></pre>
<p>define a function whither(class_, attribute) returning a tuple containing the filename, class, and line in the source code that defined or subclassed <code>attribute</code>. This means the definition in the class body, not the latest assignment due to overeager dynamism. It's fine if it returns 'unknown' for some attributes.</p>
<pre><code>>>> a = A()
>>> b = B()
>>> b.spigot = 'brass'
>>> whither(a, 'z')
("ab.py", <class 'a.A'>, [line] 2)
>>> whither(b, 'q')
("ab.py", <class 'a.B'>, 8)
>>> whither(b, 'x')
("ab.py", <class 'a.B'>, 9)
>>> whither(b, 'spigot')
("Attribute 'spigot' is a data attribute")
</code></pre>
<p>I want to use this while introspecting Plone, where every object has hundreds of methods and it would be really useful to sort through them organized by class and not just alphabetically.</p>
<p>Of course, in Python you can't always reasonably know, but it would be nice to get good answers in the common case of mostly-static code.</p>
| <p>This is more-or-less impossible without static analysis, and even then, it won't always work. You can get the line where a function was defined and in which file by examining its code object, but beyond that, there's not much you can do. The <code>inspect</code> module can help with this. So:</p>
<pre><code>import ab
a = ab.A()
meth = a.x
# So, now we have the method.
func = meth.im_func
# And the function from the method.
code = func.func_code
# And the code from the function!
print code.co_firstlineno, code.co_filename
# Or:
import inspect
print inspect.getsource(meth), inspect.getfile(meth)
</code></pre>
<p>But consider:</p>
<pre><code>def some_method(self):
pass
ab.A.some_method = some_method
ab.A.some_class_attribute = None
</code></pre>
<p>Or worse:</p>
<pre><code>some_cls = ab.A
some_string_var = 'another_instance_attribute'
setattr(some_cls, some_string_var, None)
</code></pre>
<p>Especially in the latter case, what do you want or expect to get?</p>
|
Achieving emailing between website users without "Mailing Server" configuring? <p>I have requirement like, each user of the site
will be mailing any other user and I have rules for that communication
(let them aside for now). So user1 will be picking an email id like:
mypickeduser1n...@sitedomain.com and will be sending an email to
user2, whose email id will be like:
mypickeduser2n...@sitedomain.com. Like that any number of users will
be sending emails to any numbers of users. And any outsider should be
able to send an email to mypickeduser2n...@sitedomain.com. My question
is,So in this context, do I need to build my own smtp(setup mailing)
servers. I am totally a newbie in the smtp arena. Can I achieve the
email communication between the users without "mailing server"
configurations?
Can this be achievable? </p>
| <p>You need a mail server. Even if local email is just directly deposited into a mail directory or database somewhere, something has to be responsible for accepting email from the outside world. I recommend postfix - it's powerful but easy to set up, and the config files don't look like Klingon.</p>
|
Calling a remote COM+ ServicedComponent from a C# client <p>I have a serviced component installed in a COM+ server application. I want to create an instance from a remote client. The client needs to be able to specify the server machine's name dynamically. How do I do this?</p>
<p>I tried using Activator:</p>
<pre><code> (XSLTransComponent.XSLTransformer)Activator.GetObject(
typeof(XSLTransComponent.XSLTransformer),
serverName
);
</code></pre>
<p>But I get this:</p>
<p>System.Runtime.Remoting.RemotingException: Cannot create channel sink to connect to URL 'server'. An appropriate channel has probably not been registered.
at System.Runtime.Remoting.RemotingServices.Unmarshal(Type classToProxy, String url, Object data)</p>
<p>Do I need to register a channel? If so, how?</p>
<p>Another idea is to use Marshall.BindToMoniker, but how do I specify a moniker for a remote object hosted on COM+ on server x?</p>
| <p>Eureka! This works:</p>
<pre><code>string serverName = serverTextBox.Text;
Type remote = Type.GetTypeFromProgID("XSLTransComponent.XSLTransformer", serverName);
return (XSLTransComponent.XSLTransformer)Activator.CreateInstance(remote);
</code></pre>
<p>Thanks to <a href="http://social.msdn.microsoft.com/forums/en-US/netfxremoting/thread/6bf76216-f46d-4f04-89c5-6db450a529ac/" rel="nofollow">this question</a></p>
|
Entity Framework AddTo function inconsistency? <p>Let me describe the behavior I get:</p>
<ul>
<li>Load a user from the database: this means the user is attached to the context</li>
<li>Create a new Object C:
<ul>
<li>C tempC = new C();</li>
<li>tempC.User = previously loaded user;</li>
<li>Context.AddToCSet( tempC );</li>
<li>The last line throws an exception because the object was added to the context when the property user was set.</li>
</ul></li>
</ul>
<p>but if I do the following:</p>
<ul>
<li>Load a user from the database: this means the user is attached to the context</li>
<li>Create a new Object C:
<ul>
<li>C tempC = new C();</li>
<li>tempC.User = previously loaded user;</li>
<li>Context.SaveChange();</li>
</ul></li>
<li>Create a new Object E which has a relationship with Object C.
<ul>
<li>E tempE = new E();</li>
<li>tempE.C = previously created C;</li>
<li>Context.AddToESet( tempE );</li>
</ul></li>
</ul>
<p>it <em>doesn't</em> throw an exception. I was expecting an exception because by then C is attached to the context, which should be the same case as the first example. But it isn't. Why, and what can I do to have some consistency?</p>
<p>I am planning on checking the state of the object (EntityState == Detached) before adding it to the set, but I figured I must be doing something wrong to begin with.</p>
| <p>Assuming that there is a 1 to Many relationship between <code>User</code> and <code>C</code>, you may want to use a different syntax to add a <code>C</code> to the parent <code>User</code>. Instead of <code>tempC.User = previously loaded user;</code> you probably want to add the <code>tempC</code> as a child of <code>User</code>. Here is what I mean:</p>
<pre><code>C tempC = new C();
(previously created user).C.Add(tempC);
Context.AddToCSet(tempC);
</code></pre>
|
How can I parse Serv-U FTP logs with SSIS? <p>A while back I needed to parse a bunch of Serve-U FTP log files and store them in a database so people could report on them. I ended up developing a small C# app to do the following:</p>
<ol>
<li><p>Look for all files in a dir that have not been loaded into the db (there is a table of previously loaded files). </p></li>
<li><p>Open a file and load all the lines into a list. </p></li>
<li><p>Loop through that list and use RegEx to identify the kind of row (CONNECT, LOGIN, DISCONNECT, UPLOAD, DOWNLOAD, etc), parse it into a specific kind of object corresponding to the kind of row and add that obj to another List.</p></li>
<li><p>Loop through each of the different object lists and write each one to the associated database table. </p></li>
<li><p>Record that the file was successfully imported.</p></li>
<li><p>Wash, rinse, repeat.</p></li>
</ol>
<p>It's ugly but it got the job done for the deadline we had.</p>
<p>The problem is that I'm in a DBA role and I'm not happy with running a compiled app as the solution to this problem. I'd prefer something more open and more DBA-oriented.</p>
<p>I could rewrite this in PowerShell but I'd prefer to develop an SSIS package. I couldn't find a good way to split input based on RegEx within SSIS the first time around and I wasn't familiar enough with SSIS. I'm digging into SSIS more now but still not finding what I need. </p>
<p>Does anybody have any suggestions about how I might approach a rewrite in SSIS?</p>
| <p>I have to do something similar with Exchange logs. I have yet to find an easier solution utilizing an all SSIS solution. Having said that, here is what I do:</p>
<p>First I use logparser from Microsoft and the bulk copy functionality of sql2005</p>
<p>I copy the log files to a directory that I can work with them in.</p>
<p>I created a sql file that will parse the logs. It looks similar to this:</p>
<pre><code>SELECT TO_Timestamp(REPLACE_STR(STRCAT(STRCAT(date,' '), time),' GMT',''),'yyyy-M-d h:m:s') as DateTime, [client-ip], [Client-hostname], [Partner-name], [Server-hostname], [server-IP], [Recipient-Address], [Event-ID], [MSGID], [Priority], [Recipient-Report-Status], [total-bytes], [Number-Recipients], TO_Timestamp(REPLACE_STR([Origination-time], ' GMT',''),'yyyy-M-d h:m:s') as [Origination Time], Encryption, [service-Version], [Linked-MSGID], [Message-Subject], [Sender-Address] INTO '%outfile%' FROM '%infile%' WHERE [Event-ID] IN (1027;1028)
</code></pre>
<p>I then run the previous sql with logparser:</p>
<pre><code>logparser.exe file:c:\exchange\info\name_of_file_goes_here.sql?infile=c:\exchange\info\logs\*.log+outfile=c:\exchange\info\logs\name_of_file_goes_here.bcp -i:W3C -o:TSV
</code></pre>
<p>Which outputs a bcp file.</p>
<p>Then I bulk copy that bcp file into a premade database table in SQL server with this command:</p>
<pre><code>bcp databasename.dbo.table in c:\exchange\info\logs\name_of_file_goes_here.bcp -c -t"\t" -T -F 2 -S server\instance -U userid -P password
</code></pre>
<p>Then I run queries against the table. If you can figure out how to automate this with SSIS, I'd be glad to hear what you did.</p>
|
Will Emacs make me a better programmer? <p>Steve Yegge wrote <a href="http://steve.yegge.googlepages.com/tour-de-babel">a comment on his blog</a>:</p>
<blockquote>
<p>All of the greatest engineers in the
world use Emacs. The world-changer
types. Not the great gal in the cube
next to you. Not Fred, the amazing guy
down the hall. I'm talking about the
greatest software developers of our
profession, the ones who changed the
face of the industry. The James
Goslings, the Donald Knuths, the Paul
Grahams, the Jamie Zawinskis, the
Eric Bensons. Real engineers use
Emacs. You have to be way smart to use
it well, and it makes you incredibly
powerful if you can master it. Go look
over Paul Nordstrom's shoulder while
he works sometime, if you don't
believe me. It's a real eye-opener for
someone who's used Visual Blub
.NET-like IDEs their whole career. </p>
<p>Emacs is the 100-year editor.</p>
</blockquote>
<p>The last time I used a text editor for writing code was back when I was still writing HTML in Notepad about 1000 years ago. Since then, I've been more or less IDE dependent, having used Visual Studio, NetBeans, IntelliJ, Borland/Codegear Studio, and Eclipse for my entire career.</p>
<p>For what it's worth, I <em>have</em> tried Emacs, and my experience was a frustrating one because of its complete lack of out-of-the-box discoverable features. (Apparently there's an Emacs command for discovering other Emacs commands, which I couldn't find by the way -- it's like living your own cruel Zen-like joke.) I tried to make myself like the program for a good month, but eventually decided that I'd rather have drag-and-drop GUI designers, IntelliSense, and interactive debugging instead.</p>
<p>It's hard to separate fact from fanboyism, so I'm not willing to take Yegge's comments at face value just yet.</p>
<p><strong>Is there a measurable difference in skill, productivity, or programming enjoyment between people who depend on IDEs and those who don't, or is it all just fanboyism?</strong></p>
| <p>First let me say, I am a self professed true believer in the cult of Emacs. </p>
<p>That said, the blogger is nuts. You write in what you find useful. I find that Emacs helps me, mainly because I spent my college years pre-paying the start-up cost of learning how to modify it to suit my needs, and modifying myself to its needs.</p>
<p>But other people do things differently, and as they say "That's OK".</p>
|
WinDbg -- TraceListener and Saturated ThreadPool <p>I have a multithreaded .NET Windows Service that hangs intermittently -- maybe once every two weeks of 24/7 operation. When the hangs occurs the threadpool is completely saturated because calls to our custom tracelistener start blocking for some reason. There aren't any locks in the offending code nor anything blocking according to windbg, but they're definitely blocking somewhere. There aren't any exceptions on the stack either. There is a Thread.Sleep(1) that will occasionally be hit in the BufferedStream.Write code, but my question is what is the ReOpenMetaDataWithMemory, CreateApplicationContext, and DllCanUnloadNow mean?</p>
<p>Nearly all of the 2000 hung up worker threads (not normal operation!) on the ThreadPool have a stack similar to the following:</p>
<pre><code>0:027> !dumpstack
OS Thread Id: 0x1638 (27)
Child-SP RetAddr Call Site
000000001d34df58 0000000077d705d6 ntdll!ZwDelayExecution+0xa
000000001d34df60 000006427f88901d kernel32!SleepEx+0x96
000000001d34e000 000006427f454379 mscorwks!DllCanUnloadNowInternal+0xf53d
000000001d34e080 000006427fa34749 mscorwks!CreateApplicationContext+0x41d
000000001d34e0e0 0000064280184902 mscorwks!ReOpenMetaDataWithMemory+0x1ff59
000000001d34e290 0000064280184532 Company_Common_Diagnostics!Company.Common.Diagnostics.BufferedStream.Write(Byte[], Int32, Int32)+0x1b2
000000001d34e300 00000642801831fd Company_Common_Diagnostics!Company.Common.Diagnostics.XmlRollingTraceListener+TraceWriter.Write(System.String)+0x52
000000001d34e350 00000642801b3304 Company_Common_Diagnostics!Company.Common.Diagnostics.XmlRollingTraceListener.InternalWrite(System.Text.StringBuilder)+0x3d
000000001d34e390 0000064274e9d7ec Company_Common_Diagnostics!Company.Common.Diagnostics.XmlRollingTraceListener.TraceTransfer(System.Diagnostics.TraceEventCache, System.String, Int32, System.String, System.Guid)+0xc4
000000001d34e410 00000642801b2f59 System_ni!System.Diagnostics.TraceSource.TraceTransfer(Int32, System.String, System.Guid)+0x2ec
</code></pre>
| <p>Hey, <p>
Not really an answer, but something to check... <p>
Make sure that you do not still have the DefaultTraceListener registered in your trace source.
If you don't explicitly <strong>clear</strong> or <strong>remove</strong> the <strong>DefaultTraceListener</strong> it still may be there. The <strong>DefaultTraceListener</strong> 's <strong>IsThreadSafe</strong> property returns <strong>false</strong>, in which case the System.Diagnostics.Trace classes create a <strong>lock()</strong> around the <strong>TraceEvent()</strong> calls.. <p> Just something to watch out for.
<p>
More Information:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.tracelistener.isthreadsafe.aspx" rel="nofollow">TraceListener.IsThreadSafe Property </a></p>
<blockquote>
<p>The value of IsThreadSafe is used to determine whether to use a global lock when writing to the listener. If the value of IsThreadSafe is false, the global lock is used regardless of the value of UseGlobalLock. The global lock is not used only if the value of IsThreadSafe is true and the value of UseGlobalLock is false. The default behavior is to use the global lock whenever writing to the listener. </p>
</blockquote>
<p><p>
Thanks,
Aaron </p>
|
ASP.NET - temporarily impersonate the app pool service ID when default it to impersonate the user? <p>I have to call some code in a SharePoint site that runs under the same service ID that the web application is running under. By default, SharePoint impersonates the user viewing the web page, and the users don't have the necessary permissions.</p>
<p>What is the best way to run some code using the web application's service ID, then revert back to using the default impersonation?</p>
| <p><a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx" rel="nofollow">SPSecurity.RunWithElevatedPrivileges</a></p>
|
Accessing Word documents in a Rails app <p>I have a number of documents (mainly Word and Excel) that I'd like to make available to users of my Rails app. However, I've never tried something like this before and was wondering what the best way to do this was? Seeing as there will only be a small number of Word documents, and all will be uploaded by me, do I just store them somewhere in my Rails app (i.e. public/docs or similar) or should I set up a separate FTP and link to that? Perhaps there's an even better way of doing this?</p>
| <p>I would do as you suggested and put them in public/docs. If you are planning on making an overview/index page for the files and link directly to them it would be easier if they were stored locally instead of a remote FTP server. However, since you are the one who will be uploading and maintaining these files, I think you should go with the option that's easiest for you.</p>
|
C++ Tokenizing using iterators in an eof() cycle <p>I'm trying to adapt this answer </p>
<p><a href="http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c#53921">http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c#53921</a></p>
<p>to my current string problem which involves reading from a file till eof. </p>
<p>from this source file:</p>
<pre><code>Fix grammatical or spelling errors
Clarify meaning without changing it
Correct minor mistakes
</code></pre>
<p>I want to create a vector with all the tokenized words. Example: v<code>ector<string> allTheText[0] should be "Fix"</code></p>
<p>I don't understad the purpose of <code>istream_iterator<std::string> end;</code> but I included cause it was on the original poster's answer. </p>
<p>So far, I've got this non-working code:</p>
<pre><code>vector<string> allTheText;
stringstream strstr;
istream_iterator<std::string> end;
istream_iterator<std::string> it(strstr);
while (!streamOfText.eof()){
getline (streamOfText, readTextLine);
cout<<readTextLine<<endl;
stringstream strstr(readTextLine);
// how should I initialize the iterators it and end here?
}
</code></pre>
<p>Edit:</p>
<p>I changed the code to </p>
<pre><code> vector<string> allTheText;
stringstream strstr;
istream_iterator<std::string> end;
istream_iterator<std::string> it(strstr);
while (getline(streamOfText, readTextLine)) {
cout << readTextLine << endl;
vector<string> vec((istream_iterator<string>(streamOfText)), istream_iterator<string>()); // generates RuntimeError
}
</code></pre>
<p>And got a RuntimeError, why?</p>
| <p>Using a <code>while (!â¦.eof())</code> loop in C++ is broken because the loop will never be exited when the stream goes into an error state!</p>
<p>Rather, you should test the stream's state directly. Adapted to your code, this could look like this:</p>
<pre><code>while (getline(streamOfText, readTextLine)) {
cout << readTextLine << endl;
}
</code></pre>
<p>However, you already <em>have</em> a stream. Why put it into a string stream as well? Or do you need to do this line by line for any reason?</p>
<p>You can <strong>directly</strong> initialize your vector with the input iterators. No need to build a string stream, and no need to use the <code>copy</code> algorithm either because there's an appropriate constructor overload.</p>
<pre><code>vector<string> vec((istream_iterator<string>(cin)), istream_iterator<string>());
</code></pre>
<p>Notice the extra parentheses around the first argument which are necessary to disambiguate this from a function declaration.</p>
<p><strong>EDIT</strong> A small explanation what this code does:</p>
<p>C++ offers a unified way of specifying <em>ranges</em>. A range is just a collection of typed values, without going into details about how these values are stored. In C++, these ranges are denoted as half-open intervals [<code>a</code>, <code>b</code>[. That means that a range is delimited by two <em>iterators</em> (which are kind of like pointers but more general; pointers are a special kind of iterator). The first iterator, <code>a</code>, points to the first element of the range. The second, <code>b</code>, points <em>behind</em> the last element. Why behind? Because this allows to iterate over the elements very easily:</p>
<pre><code>for (Iterator i = a; i != b; ++i)
cout << *i;
</code></pre>
<p>Like pointers, iterators are <em>dereferenced</em> by applying <code>*</code> to them. This returns their value.</p>
<p>Container classes in C++ (e.g. <code>vector</code>, <code>list</code>) have a special constructor which allows easy copying of values from another range into the new container. Consequently, this constructor expects two iterators. For example, the following copies the C-style array into the vector:</p>
<pre><code>int values[3] = { 1, 2, 3 };
vector<int> v(values, values + 3);
</code></pre>
<p>Here, <code>values</code> is synonymous with <code>&values[0]</code> which means that it points to the array's first element. <code>values + 3</code>, thanks to pointer arithmetic, is <em>nearly</em> equivalent to <code>&values[3]</code> (but this is <strong>invalid</strong> C++!) and points to the virtual element <em>behind</em> the array.</p>
<p>Now, my code above does the exact same as in this last example. The only difference is the type of iterator I use. Instead of using a plain pointer, I use a special iterator class that C++ provides. This iterator class <em>wraps</em> an input stream in such a way that <code>++</code> <em>advances</em> the input stream and <code>*</code> reads the next element from the stream. The kind of element is specified by the type argument (hence <code>string</code> in this case).</p>
<p>To make this work as a range, we need to specify a beginning and an end. Alas, we don't know the end of the input (this is logical, since the end of the stream may actually move over time as the user enters more input into a console!). Therefore, to create a virtual <em>end</em> iterator, we pass no argument to the constructor of <code>istream_iterator</code>. Conversely, to create a begin iterator, we pass an input stream. This then creates an iterator that points to the current position in the stream (here, <code>cin</code>).</p>
<p>My above code is functionally equivalent to the following:</p>
<pre><code>istream_iterator<string> front(cin);
istream_iterator<string> back;
vector<string> vec;
for (istream_iterator<string> i = front; i != back; ++i)
vec.push_back(*i);
</code></pre>
<p>and this, in turn, is equivalent to using the following loop:</p>
<pre><code>string word;
while (cin >> word)
vec.push_back(word);
</code></pre>
|
Different performance between Java and c# code when testing URL <p>When running the following Java code, I get very accurate and consistent results in determining if the web page I'm testing is up.</p>
<pre><code>protected synchronized boolean checkUrl(HttpURLConnection connection){
boolean error = false;
//HttpURLConnection connection = null;
GregorianCalendar calendar = new GregorianCalendar();
try{
if(connection != null){
connection.connect();
//200 is the expected HTTP_OK response
error = processResponseCode(connection.getResponseCode());
connection.disconnect();
} else{
error = false;
}
}catch(java.net.UnknownHostException uhe){
... }
catch(Exception e){
... }
return error;
}
</code></pre>
<p>The closest match to the Java pattern in c# has much higher results of false positives (mostly due to timeouts - which has a default period of 100000ms).</p>
<pre><code>protected bool connectedToUrl = false;
response = null;
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(this.getUri());
webreq.Credentials = CredentialCache.DefaultCredentials;
WebResponse res = null;// webreq.GetResponse();
try
{
WebRequest request = WebRequest.Create(this.getUri()) as WebRequest;
request.Credentials = CredentialCache.DefaultCredentials;
if (request != null)
{
// Get response
res = webreq.GetResponse();
connectedToUrl = processResponseCode(res);
}
else
{
logger.Fatal(getFatalMessage());
string error = string.Empty;
}
}
catch (Exception e)
{
throw e;
}
return connectedToUrl;
}
</code></pre>
<p>I have tried various patterns in c# to match the effectiveness of the quoted Java code, to no avail. </p>
<p>Any ideas?</p>
| <p>I believe this is because you're not closing any of the request objects.</p>
|
Highest Performance Database Storage Mechanism <p>I need ideas to implement a (really) high performance in-memory Database/Storage Mechanism. In the range of storing 20,000+ objects, with each object updated every 5 or so seconds. <strong>I would like a FOSS solution</strong>.</p>
<p>What is my best option? What are your experiences?</p>
<p>I am working primarily in Java, but I need the datastore to have good performance so the datastore solution need not be java centric.</p>
<p>I also need like to be able to Query these objects and I need to be able to restore all of the objects on program startup.</p>
| <p><a href="http://sqlite.org/" rel="nofollow">SQLite</a> is an open-source self-contained database that supports in-memory databases (just connect to <code>:memory:</code>). It has bindings for many popular programming languages. It's a traditional SQL-based relational database, but you don't run a separate server â just use it as a library in your program. It's pretty quick. Whether it's quick enough, I don't know, but it may be worth an experiment.</p>
<p><a href="http://www.zentus.com/sqlitejdbc/" rel="nofollow">Java driver</a>.</p>
|
Why isn't the SelectedIndexChanged event firing from a dropdownlist in a GridView? <p>I cannot get my SelectedIndexChanged of my dropdownlist to fire. I have the following:</p>
<pre><code><form id="form1" runat="server">
<div>
<asp:GridView id="grdPoll" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="Review" Value="Review" Selected="True">Review</asp:ListItem>
<asp:ListItem Text="Level1" Value="lvl1">Send Back to Level1</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblCity" runat="server" Text="Label"></asp:Label>
</div>
</form>
</code></pre>
<p>In my code behind I have this:</p>
<pre><code>protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
this.lblCity.Text = ((DropDownList)sender).SelectedValue;
}
</code></pre>
<p>If I put this same ddl outside of the gridview, it fires.</p>
<p>The postback is occurring and the autopostback is set to true. The event just never fires. Why can't I get my event to fire from within the gridview?</p>
<p>Thank you.</p>
| <p>Well, this question was asked more than a month ago and may be irrelevant now, but @LFSR was kind enough to edit it recently, it's in the "Active questions" list. </p>
<p>Since it remains unanswered (224 views!), I thought I should give it a go:</p>
<p><hr /></p>
<p>The problem is that in the context of a GridView, the DropDownList(referred to hereafter as DDL) is a dynamic control and therefore its events need to be reattached upon Postback.</p>
<p>When this concept is understood, the solution becomes relatively simple :</p>
<p><strong>ASPX:</strong></p>
<pre><code><asp:DropDownList ID="DDL1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DDL1_SelectedIndexChanged">
<asp:ListItem Text="Review" Value="Review" Selected="True">Review</asp:ListItem>
<asp:ListItem Text="Level1" Value="lvl1">Send Back to Level1</asp:ListItem>
</asp:DropDownList>
</code></pre>
<p>CS Code:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// Bind the GridView to something.
DataBindGrid();
}
}
protected void DDL1_SelectedIndexChanged(object sender, EventArgs e)
{
this.lblCity.Text = ((DropDownList)sender).SelectedValue;
}
protected void grdPoll_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(Page.IsPostBack)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("DDL1") as DropDownList;
if(ddl != null)
{
ddl.SelectedIndexChanged += new EventHandler(DDL1_SelectedIndexChanged);
}
}
}
}
</code></pre>
|
Castle Windsor: So what DOES ActAs do? <p>I noticed that the castle windsor fluent component registration interface has the rather confusing ActAs() method.</p>
<p>Googling around for it the only reference I found was at their wiki <a href="http://using.castleproject.org/display/IoC/Fluent+Registration+API" rel="nofollow">here</a>.</p>
<blockquote>
<p>TODO (Stuff that could be documented)</p>
<ul>
<li>what does ActAs() do?</li>
</ul>
</blockquote>
<p>Not too helpful.</p>
<p>The source doesn't seem to have any unit tests for the method that would give a clue to its usage and I'm too unfamiliar with their source to be able to tell for myself what is going on.</p>
<p>Does anyone know any more about this?</p>
| <p>It <a href="http://fisheye2.atlassian.com/changelog/castleproject?cs=4961" rel="nofollow">adds custom dependencies (tags)</a> to the component being registered. The <a href="http://www.castleproject.org/container/facilities/trunk/wcf/index.html" rel="nofollow">WcfFacility</a>, for example, <a href="http://fisheye2.atlassian.com/browse/castleproject/trunk/Facilities/Wcf/Castle.Facilities.WcfIntegration/Service/WindsorServiceHostFactory.cs?r=5525#l93" rel="nofollow">uses these attached dependencies</a> to <a href="http://fisheye2.atlassian.com/browse/castleproject/trunk/Facilities/Wcf/Castle.Facilities.WcfIntegration.Tests/Rest/RestServiceFixture.cs?r=5525#l36" rel="nofollow">set up endpoints and other stuff</a>.</p>
|
Controllers in Grails <p>I'm writing a small webapp in Grails and I have the following question regarding best practices for controller design and using GORM:</p>
<p>I'm storing the user object in session.user. Currently all my action methods start with the following code to make sure a valid user is logged in and that the user object is fresh:</p>
<pre><code>class FooController {
def actionMethodThatRequiresAValidUser = {
if (!session?.user) {
redirect(controller: "authentication", action: "login")
}
session.user.refresh()
...
/* do stuff */
...
}
}
</code></pre>
<p>Is that best practice? Can it be done in a better and/or more concise way?</p>
| <p>Use a <a href="http://grails.org/doc/1.0.x/guide/6.%20The%20Web%20Layer.html#6.6%20Filters">filter</a>, that way you can put that same repeated code in the filter and keep your controllers focussed on the real action.</p>
|
How could I implement autocompletion using Swing? <p>I'm interested in providing an autocompletion box in a JFrame. The triggering mechanism will be based on mnemonics (I think), but I'm not really sure what to use for the "autocompletion box" (I would like results to be filtered as the user presses keys).</p>
<p>How would you implement this? Some sort of JFrame, or a JPopupMenu? </p>
<p>I would like to know how this is implemented, so please don't post links to available [J]Components.</p>
| <p>You might want to try the free AutoComplete component over at SwingLabs.</p>
<p><a href="http://swinglabs.org" rel="nofollow">http://swinglabs.org</a></p>
<p>Edit: This site seems to have moved <a href="http://java.net/projects/swinglabs" rel="nofollow">http://java.net/projects/swinglabs</a></p>
<p>There is an example how to implement this code at:</p>
<p><a href="http://download.java.net/javadesktop/swinglabs/releases/0.8/docs/api/org/jdesktop/swingx/autocomplete/package-summary.html" rel="nofollow">http://download.java.net/javadesktop/swinglabs/releases/0.8/docs/api/org/jdesktop/swingx/autocomplete/package-summary.html</a></p>
|
Portable / Interoperable WCF Contracts <p>I was wondering if anybody out there had some good tips/dos and don'ts for designing WCF contracts with a mind for web-service interoperability, both in terms of older Microsoft web service technologies (e.g. WSE) and non-Microsoft technologies such as Java calling WCF web services. </p>
<p>For example: are there any special rules that need to be taken into account when exposing DateTime as a type in your contract? How about Dictionaries and Hashtables? What are the issues you might run into with the various bindings available? </p>
| <h2>WCF DateTime woes</h2>
<p>Regarding your DateTime question, you are right to be concerned about passing around DateTime via WCF. This is just one link of many that gripe about the difficulties...
<a href="http://daveonsoftware.blogspot.com/2008/07/wcf-datetime-field-adjusted.html">http://daveonsoftware.blogspot.com/2008/07/wcf-datetime-field-adjusted.html</a></p>
<h2>Regarding Type Equivalence</h2>
<p>According to section 3.1.3 of Juval Lowy's book entitled Programming WCF Services, 2nd Edition...</p>
<blockquote>
<p>WCF offers implicit data contracts for
the primitive types because there is
an industry standard for the schemas
of those types.</p>
</blockquote>
<p>He also points that out in regards to the use of custom types as parameters on Operation Contract methods. I presume this also applies to method return types.</p>
<blockquote>
<p>To be able to use a custom type as an
operation parameter, there are two
requirements: first, the type must be
serializable, and second, both the
client and the service need to have a
local definition of that type that
results in the same data schema.</p>
</blockquote>
<p>You may also want to check out section F.4. Data Contracts, which is part of his WCF Coding Standard. Bullet #9 applies to your question...</p>
<blockquote>
<p>Do not pass .NET-specific types, such
as Type, as operation parameters.</p>
</blockquote>
<h2>Bindings Establish Expectations</h2>
<p>Bindings that are based on WSHttpBindingBase (search in Reflector.NET for its four derivations) are going to be the most interoperable, since they are designed for interoperability.</p>
<h2>Book Recommendation</h2>
<p>I highly recommend Juval's book: <a href="http://www.bookpool.com/sm/0596521308">http://www.bookpool.com/sm/0596521308</a></p>
|
OleDbPermission in .NET Framework 3.5 <p>I have a windows program in .net framework 3.5 to update an access database, I need to set the permission to full trust level. the client don't have the framework configuration tools installed on their server, so is there any other place that I can make this change?</p>
| <p>You can configure the trust levels with the notepad:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ff648344.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ff648344.aspx</a></p>
|
Keys / Values Functionality to Iterators in C++ <p>I know this questions has come up in various guises before, but this is slightly different.</p>
<p>I have a class which contains a std::map. Although I wish to use the map for other purposes inside the class, externally I want to expose an iterator adapter to just the values inside the map (ie the second item in the std::pair).</p>
<p>For example in python I might do something like this:</p>
<pre><code>def __iter__(self):
return self._dict.itervalues()
</code></pre>
<p>How do I go about doing this in c++, hiding the implementation inside the class?</p>
<p>Thanks,</p>
<p>Dan</p>
| <p>Have a look at Boost's <a href="http://www.boost.org/doc/libs/1_37_0/libs/iterator/doc/transform_iterator.html"><code>transform_iterator</code></a> which provides exactly this kind of functionality:</p>
<pre><code>template <typename K, typename V>
struct get_value {
const V& operator ()(std::pair<K, V> const& p) { return p.second; }
};
class your_class {
typedef map<int, float> TMap;
TMap mymap;
public:
typedef get_value<TMap::key_type, TMap::data_type> F;
typedef
boost::transform_iterator<F, TMap::iterator>
value_iterator;
value_iterator begin() { return make_transform_iterator(mymap.begin(), F()); }
value_iterator end() { return make_transform_iterator(mymap.end(), F()); }
// TODO Same for const versions.
// Rest of the interface â¦
};
</code></pre>
<p>Now you can iterate over the values, e.g. like this:</p>
<pre><code>your_class c;
// Fill c with some values â¦
copy(c.begin(), c.end(), ostream_iterator<float>(cout, " "));
</code></pre>
|
Algorithm for drawing an anti-aliased circle? <p>What's a good algorithm for drawing anti-aliased circles? (Filled and not filled.)</p>
| <p>Bresenham (of the line algorithm fame) also had a circle algorithm.</p>
<p>Xiaolin Wu adapted the line algorithm for anti-aliasing, and likewise did the same to the circle algorithm.</p>
<p><a href="http://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm">http://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm</a></p>
<p>You can find the circle algorithm with this search:</p>
<p><a href="http://www.google.com/search?q=Xiaolin%20Wu%20circle">http://www.google.com/search?q=Xiaolin%20Wu%20circle</a></p>
|
Why would my java program send multicast packets with a TTL of 1? <p>I have a java client program that uses mdns with service discovery to find its associated server. After much testing on a single network with Windows, Fedora 10, and Ubuntu 8.10, we delivered a test build to a customer. They report that the client and server never connect. They sent us a wireshark capture that shows the mdns packets have a TTL of 1 even though our code sets it to 32. When we test locally, the TTL is 32 just like we set it. The customer is using Redhat Enterprise 5. </p>
<p>I saw <a href="http://stackoverflow.com/questions/139909/java-multicast-time-to-live-is-always-0">Java Multicast Time To Live is always 0</a> but it leaves me curious as to why that question asker has a TTL of 0, but mine is 1.</p>
| <p>Did you check out the answer to <a href="http://stackoverflow.com/questions/139909/java-multicast-time-to-live-is-always-0">Java Multicast Time To Live is always 0</a>? This may fix your problem as well. The answer there references the answerer's <a href="http://www.peterfranza.com/2008/09/25/setting-multicast-time-to-live-in-java/" rel="nofollow">blog entry</a>.</p>
|
ASP.NET MVC RC1 - Custom View Engine for Areas - FindView override not firing <p>I have a custom view engine in ASP.NET MVC and since upgrading to RC1 my custom view engine that implements Areas <a href="http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx" rel="nofollow">as in this post by Phil Haack</a> does not enter the override method FindView, thus breaking any controllers that sit within an area as the application is unable to find them. As I'm aware that a good number of people are using areas in their MVC applications, is anyone aware of a solution to this problem or why it happens?</p>
<p>Below is my findview method for reference.</p>
<pre><code> public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName)
{
ViewEngineResult areaResult = null;
if (controllerContext.RouteData.Values.ContainsKey("area"))
{
string areaViewName = FormatViewName(controllerContext, viewName);
areaResult = base.FindView(controllerContext, areaViewName, masterName);
if (areaResult != null && areaResult.View != null)
{
return areaResult;
}
string sharedAreaViewName = FormatSharedViewName(controllerContext, viewName);
areaResult = base.FindView(controllerContext, sharedAreaViewName, masterName);
if (areaResult != null && areaResult.View != null)
{
return areaResult;
}
}
return base.FindView(controllerContext, viewName, masterName);
}
</code></pre>
| <p>They have added a parameter to the FindView Method. You can now specify to usecache on both FindView and FindPartialView.</p>
|
K&R exercise: Multidimensional array into pointer array <p>Exercise (5-9):
Rewrite the routines <code>day_of_year</code> with pointers instead of indexing.</p>
<pre><code>static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
/* day_of_year: set day of year from month and day */
int day_of_year(int year, int month, int day)
{
int i, leap;
leap = (year%4 == 0) && (year%100 != 0) || (year%400 == 0);
for (i = 1; i < month; i++)
{
day += daytab[leap][i];
}
return day;
}
</code></pre>
<p>I may just be tired and not thinking, but how does one actually create a multidimensional array with pointers?</p>
<p>I could probably figure out the rest of the function, but I can't get the syntax right.</p>
| <p>There are two ways of handling this:</p>
<p>The first is to emulate the way that C actually handles multidimensional arrays, which is to say not at all. char[4][4] is really just syntactical sugar around char[16]. You can create a pointer to an array of 16 bytes (in this case) and you've got the same thing.</p>
<p>The other is to create a pointer to a pointer. Following the previous example:</p>
<pre><code>char **foo = malloc(sizeof(char *) * 4);
for(int i = 0; i < 4; ++i)
foo[i] = malloc(sizeof(char) * 4);
foo[0][0] = bar;
</code></pre>
|
Logic first, WCF security later? <p>I'm working on a WCF service that will be communicating over net.tcp to n instances of a client app (that is being developed by another programmer in my office). </p>
<p>At the moment I am using net.tcp without any security as I felt setting this up at this stage wasn't necessary, at least not until we are closer to rolling out.</p>
<p>During the development of a WCF application, is there any harm in using a standard binding (net.tcp in my case) without security, then once the business logic has been completed, implement all the security requirements? Are there any things I need to be aware of that may not function after the implementation of security?</p>
| <p>While your overall design should consider security from the very beginning, I don't think it's a good idea to couple your components to any particular security strategy. You may very well want to use some of your components in a non-secure manner or across a different protocol which offers different security options.</p>
<p>So my answer is yes and no. Yes you need to think about it from the beginning, but no you should not couple your components to your security needs.</p>
<p>That said, since you know that you'll be using net.tcp you should be aware that transport security is turned on by default for this binding. </p>
<p>For tons more information, see Juval Lowy's fantastic <a href="http://rads.stackoverflow.com/amzn/click/0596521308" rel="nofollow">Programming WCF Services</a>, chapter 10. Lowy, in his ServiceModelEx library (discussed at length in the book) provides a really nice framework that you can plug in after you've created your components. Even if it's not exactly what you're looking for you can customize it to suit your needs.</p>
|
Is there still a place for MDI? <p>Even though MDI is <a href="http://pixelcentric.net/article-art=docs.html" rel="nofollow">considered harmful</a>, several applications (even MS Office, Adobe apps) still use it either in its pure form or some as a hybrid with a tabbed/IDE-like interface.</p>
<p><strong>Is an MDI interface still appropriate for some applications?</strong> </p>
<p>I'm thinking of an application where one typically works with several documents at one time, and often wants to have multiple documents side to view or copy/paste between them. </p>
<p>An example would be <a href="http://www.originlab.com/" rel="nofollow">Origin</a>, where one has multiple worksheet and graph windows in a project; a tabbed or IDE-like interface would be much more inconvenient with a lot of switching back and forth.</p>
<p>On the mac, it's natural and convenient for an application to have multiple top-level windows to solve this, what is the preferred way in Windows if one doesn't use MDI? </p>
| <p>The disadvantages of MDI are the following:</p>
<ul>
<li><p>It generally requires the user to learn and understand a more complicate set of window relations.</p></li>
<li><p>Many simple actions can require a two-step process. For example, bringing a desired window to the foreground can require that the user first brings the container window forward then bring the right primary window in the container window forward. Resizing or maximizing a window can mean first adjusting the container window then the primary window within. </p></li>
<li><p>If multiple container windows are open, the user can forget which one has the desired primary window, requiring a tedious search.</p></li>
<li><p>Users are easily confused by the dual ways to maximize, iconify, layer, and close a window. For example they may close the entire app rather than a window within the container window. Or they may âloseâ a window because they iconified it within the container window without realizing it.</p></li>
<li><p>The user is limited in the sizes and positions his or her windows can assume. Suppose I want to look simultaneously at 3 windows of one app and 1 from another app. With SDI, I can have each window take a quadrant of the screen, but I canât do that with MDI. What if I want one window in the MDI to be large and the other small? I have to make the container window large to accommodate the large window (where it occludes the windows of other apps), but that wastes space when looking at the child.</p></li>
</ul>
<p>Note that all of these disadvantages apply to tabbed document interfaces (TDI) too, with tabbed interfaces having the additional disadvantage that the user canât look at two documents in the same container window side by side. Tabs also add clutter and consume real estate in your windows. However, overall TDI tend to be less problematic than MDI, so they might be preferred for special cases (read on)</p>
<p>In summary, it hard to think of any situation to use MDI. Itâs no better than an SDI while adding more complexity and navigation overhead, and working poorly with the windows of other apps.</p>
<p>Thereâs no reason an app canât have multiple top-level SDI windows. Even with an app like Origin, I donât see a problem with a project being spread across multiple SDI windows as long as the project is well identified in each window. SDI also allows different kinds of windows (e.g., graph vs worksheet) to have different menus and toolbars, rather than hiding or disabling items depending on the active window (the former is confusing, and the latter wastes space).</p>
<p>SDI gives your users the more flexibility over either MDI or TDI. Users can overlap or maximize the windows, and use the taskbar/dock as a de facto tab interface. Users can alternatively resize and reposition the windows so they can look at multiple at once. Each window can be sized independently to optimize screen space. Whatever advantages an MDI or TDI may have, you may be able augment SDI to have those advantages too (e.g., provide a thumbnailed menu that makes switching among windows faster than using the taskbar and comparable to selecting tabs, or provide a control that iconifies all windows of an app with one click).</p>
<p>Unless you have compelling reasons to use a TDI, go SDI to allow this flexibility. Compelling reasons include some subset of the following:</p>
<ul>
<li><p>Each tab is used for unrelated high-order tasks and user will not be switching among tabs frequently or comparing information across tabs.</p></li>
<li><p>Youâre working with very low-end users who are ignorant of or confused by the taskbar/dock and multiple windows, and donât know how to resize windows (it seems compelling tab imagery works better than the taskbar for such users).</p></li>
<li><p>You anticipate thereâre typically be a large set of tabs (e.g., 4 or more) and you can control their display in a manner more effectively for the task than the OS can if they were SDI windows on the taskbar/dock (e.g., with regard to order and labeling).</p></li>
<li><p>With SDI, youâre having problems with users confusing the toolbars or palettes of inactive windows with active windows. </p></li>
<li><p>Tabs are fixed in number and permanently open (e.g., when each tab is a different component of the same data object). The user is not saddled with trying to distinguish between closing a tab and closing the entire window; figuring out the window to navigate to is not an issue because all windows have the same tabs. </p></li>
<li><p>There is really only one way to properly arrange the data for task, with no variation among users or what they actually use the app for. You might as well set it up for the user with a combination of tabs and master-detail panes and rather than relying on the user to arrange and size SDI windows right.</p></li>
</ul>
<p>In summary, given your usersâ abilities, app complexity, and task structure, if your app can manage the content display better than the user/OS, use TDI, otherwise use SDI. </p>
|
What is the proper way to update Delphi 2009's default installation of Indy 10? <p>Since Indy is now built-into the install process of Delphi 2009... is there a proper way to 'remove' it so it can be upgraded to the latest from the SVN repo? There isn't an automated option to remove it as far as I'm aware.</p>
| <p>The <em>dcu</em> files for Indy are stored separately from the other Delphi units. To stop using them, simply remove that directory from the search path, library path, etc., and remove the source files from the browse path.</p>
<p>You can remove the design-time packages the same as any other design-time packages. Remove them from the IDE configuration, and then delete the <em>bpl</em> and <em>dcp</em> files. (If you just delete the files, you may get errors when you next start the IDE since it won't find the expected files.)</p>
<p>Once the Indy components no longer appear on the Tool Palette, the packages no longer appear on the package list, and compiling a project that references Indy units fails with a "can't find used unit" error, you're ready to start installing the latest version.</p>
|
Delphi 2009 and Synapse - tested and ready for Unicode support? <p>Is Synapse ready for a Delphi 2009 production applications? Their website doesn't look like it's been updated in a while: <a href="http://www.ararat.cz/synapse/doku.php" rel="nofollow">http://www.ararat.cz/synapse/doku.php</a> Is the project dead?</p>
| <p>I have been using the latest version from the SVN repository without any problems in a commercial application compiled with Delphi 2009.</p>
|
What's the most efficient way to check the presence of a row in a table? <p>Say I want to check if a record in a MySQL table exists. I'd run a query, check the number of rows returned. If 0 rows do this, otherwise do that.</p>
<pre><code>SELECT * FROM table WHERE id=5
SELECT id FROM table WHERE id=5
</code></pre>
<p>Is there any difference at all between these two queries? Is effort spent in returning every column, or is effort spent in filtering out the columns we don't care about?</p>
<pre><code>SELECT COUNT(*) FROM table WHERE id=5
</code></pre>
<p>Is a whole new question. Would the server grab all the values and then count the values (harder than usual), or would it not bother grabbing anything and just increment a variable each time it finds a match (easier than usual)?</p>
<p>I think I'm making a lot of false assumptions about how MySQL works, but that's the meat of the question! Where am I wrong? Educate me, Stack Overflow!</p>
| <p>Optimizers are pretty smart (generally). They typically only grab what they need so I'd go with:</p>
<pre><code>SELECT COUNT(1) FROM mytable WHERE id = 5
</code></pre>
|
hiding grids using ESC key <p>I'm new to WPF.
I have like 15 grids on my Window and I have a small menu on which I can click and choose which grid to show up or hide. One grid at a time only. I would like that grid to hode (fade out) when I hit <kbd>Esc</kbd>. I have all the animations already, I just need to know what grid is visible (active) at the moment.</p>
<p>I don't know how to get current topmost control of my Window.</p>
<p>My solution is when <code>KeyDown</code> event is triggered on my Window to:</p>
<pre><code>private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Escape)
{
//check all grids for IsVisible and on the one that is true make
BeginStoryboard((Storyboard)this.FindResource("theVisibleOne_Hide"));
}
}
</code></pre>
| <p>By active, I assume that means the one that has keyboard focus. If so, the following will return the control that currently has keyboard input focus:</p>
<pre><code>System.Windows.Input.Keyboard.FocusedElement
</code></pre>
<p>You could use it like this:</p>
<pre><code>if (e.Key == System.Windows.Input.Key.Escape)
{
//check all grids for IsVisible and on the one that is true make
var selected = Keyboard.FocusedElement as Grid;
if (selected == null) return;
selected.BeginStoryboard((Storyboard)this.FindResource("HideGrid"));
}
</code></pre>
<p>An approach that would be more decoupled would be to create a static attached dependency property. It could be used like this (untested):</p>
<pre><code><Grid local:Extensions.HideOnEscape="True" .... />
</code></pre>
<p>A very rough implementation would look like:</p>
<pre><code>public class Extensions
{
public static readonly DependencyProperty HideOnEscapeProperty =
DependencyProperty.RegisterAttached(
"HideOnEscape",
typeof(bool),
typeof(Extensions),
new UIPropertyMetadata(false, HideOnExtensions_Set));
public static void SetHideOnEscape(DependencyObject obj, bool value)
{
obj.SetValue(HideOnEscapeProperty, value);
}
public static bool GetHideOnEscape(DependencyObject obj)
{
return (bool)obj.GetValue(HideOnEscapeProperty);
}
private static void HideOnExtensions_Set(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var grid = d as Grid;
if (grid != null)
{
grid.KeyUp += Grid_KeyUp;
}
}
private static void Grid_KeyUp(object sender, KeyEventArgs e)
{
// Check for escape key...
var grid = sender as Grid;
// Build animation in code, or assume a resource exists (grid.FindResource())
// Apply animation to grid
}
}
</code></pre>
<p>This would remove the need to have code in codebehind. </p>
|
Caching with multiple server <p>I'm building an application with multiple server involved. (4 servers where each one has a database and a webserver. 1 master database and 3 slaves + one load balancer)</p>
<p>There is several approach to enable caching. Right now it's fairly simple and not efficient at all.
All the caching is done on an NFS partition share between all servers. NFS is the bottleneck in the architecture.</p>
<ol>
<li>I have several ideas implement
caching. It can be done on a server
level (local file system) but the
problem is to invalidate a cache
file when the content has been
update on all server : It can be
done by having a small cache
lifetime (not efficient because the
cache will be refresh sooner that it
should be most of the time)</li>
<li>It can also be done by a messaging
sytem (XMPP for example) where each
server communicate with each other.
The server responsible for the
invalidation of the cache send a
request to all the other to let them
know that the cache has been
invalidated. Latency is probably
bigger (take more time for everybody
to know that the cache has been
invalidated) but my application
doesn't require atomic cache
invalidation.</li>
<li>Third approach is to use a cloud
system to store the cache (like
CouchDB) but I have no idea of the
performance for this one. Is it
faster than using a SQL database?</li>
</ol>
<p>I planned to use Zend Framework but I don't think it's really relevant (except that some package probably exists in other Framework to deal with XMPP, CouchDB)</p>
<p>Requirements: Persistent cache (if a server restart, the cache shouldn't be lost to avoid bringing down the server while re-creating the cache)</p>
| <p><a href="http://www.danga.com/memcached/" rel="nofollow">http://www.danga.com/memcached/</a></p>
<p>Memcached covers most of the requirements you lay out - message-based read, commit and invalidation. High availability and high speed, but very little atomic reliability (sacrificed for performance).</p>
<p>(Also, memcached powers things like YouTube, Wikipedia, Facebook, so I think it can be fairly well-established that organizations with the time, money and talent to seriously evaluate many distributed caching options settle with memcached!)</p>
<p><em>Edit (in response to comment)</em>
The idea of a cache is for it to be relatively transitory compared to your backing store. If you need to persist the cache data long-term, I recommend looking at either (a) denormalizing your data tier to get more performance, or (b) adding a middle-tier database server that stores high-volume data in straight key-value-pair tables, or something closely approximating that.</p>
|
Uses for both static strong typed languages like Haskell and dynamic (strong) languages like Common LIsp <p>I was working with a Lisp dialect but also learning some Haskell as well. They share some similarities but the main difference in Common Lisp seems to be that you don't have to define a type for each function, argument, etc. whereas in Haskell you do. Also, Haskell is mostly a compiled language. Run the compiler to generate the executable.</p>
<p>My question is this, are there different applications or uses where a language like Haskell may make more sense than a more dynamic language like Common Lisp. For example, it seems that Lisp could be used for more bottom programming, like in building websites or GUIs, where Haskell could be used where compile time checks are more needed like in building TCP/IP servers or code parsers.</p>
<p>Popular Lisp applications:
Emacs</p>
<p>Popular Haskell applications:
PUGS
Darcs</p>
<p>Do you agree, and are there any studies on this?</p>
| <p>Programming languages are tools for thinking with. You can express any program in any language, if you're willing to work hard enough. The chief value provided by one programming language over another is how much support it gives you for thinking about problems in different ways. </p>
<p>For example, Haskell is a language that emphasizes thinking about your problem in terms of types. If there's a convenient way to express your problem in terms of Haskell's data types, you'll probably find that it's a convenient language to write your program in. </p>
<p>Common Lisp's strengths (which are numerous) lie in its dynamic nature and its homoiconicity (that is, Lisp programs are very easy to represent and manipulate as Lisp data) -- Lisp is a "programmable programming language". If your program is most easily expressed in a new domain-specific language, for example, Lisp makes it very easy to do that. Lisp (and other dynamic languages) are a good fit if your problem description deals with data whose type is poorly specified or might change as development progresses.</p>
<p>Language choice is often as much an aesthetic decision as anything. If your project requirements don't limit you to specific languages for compatibility, dependency, or performance reasons, you might as well pick the one you feel the best about.</p>
|
Problem with windows Batch file on windows 7 <p>I have a batch file to compile and link all of my code. It contains the following:</p>
<pre><code>@echo off
nasm -f aout -o start.o start.asm
gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions -nostdinc -fno-builtin -I./include -c -o main.o main.c
gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions -nostdinc -fno-builtin -I./include -c -o scrn.o scrn.c
ld -T link.ld -o kernel.bin start.o main.o scrn.o
pause
</code></pre>
<p>Problem is, when i run it it just prints all this out as text.
It's definitely a batch file. it has the .bat file ending, and in notepad++, the syntax for @echo off and pause are being highlighted without being set manually.
Is this a windows 7 bug? or am i doing something wrong?</p>
| <p>Are you running from a command line or by double-clicking in Explorer?</p>
<p>Maybe you have the <i>Edit</i> action set as the default?</p>
<p>Try right-clicking and selecting <i>Open</i>.</p>
<p>EDIT: Maybe your line terminators are messed up. Windows expects CRLF.</p>
<p>In Notepad++:</p>
<ul>
<li>Click View->Show End Of Line.</li>
<li>If they are not CRLF, click Format->Convert to Windows Format.</li>
</ul>
|
Different Log File For Specific Controller <p>I currently have a controller were I would like to keep track of logging in a separate log file, like: tracker.log. I currently get about 100,000 hits a day with this, and I would like to separate the log from all the other controllers so I can easily debug those as well as the tracker.<br /><br />
I couldn't find anything for the Rails::Initializer, that would extend specifically for a controller.<br /><br />
I know it will be something along the lines of:</p>
<pre>
config.log_path = 'log/tracker.log'
</pre>
<p>Although you can't re-run the Rails initializer mid load, right?</p>
| <p>AFAIK rails can't maintain two separate log file simultaneously. I'd recommend doing your own logging in the controller in question. </p>
<p>In similar situations I've used <a href="http://log4r.sourceforge.net/" rel="nofollow">log4r</a>. It's very <a href="http://log4r.sourceforge.net/manual.html#outofbox" rel="nofollow">easy</a> to get started.</p>
|
Convert existing snippet of code to use Array.ForEach <p>We know that if you have:</p>
<pre><code>var aa = new [] { 1, 2, 3, 4, 5 };
for (int i = 0; i < aa.length; ++i)
{
aa[i] = aa[i] + 1;
}
</code></pre>
<p>it's really</p>
<pre><code>var aa = new [] { 1, 2, 3, 4, 5 };
Arrary.ForEach(aa, a => a + 1);
</code></pre>
<p>However, what if I had this:</p>
<pre><code>var aa = new [] { 1, 2, 3, 4, 5 };
var ab = new [] { 1, 2, 3, 4, 5 };
for (int i = 0; i < aa.length; ++i)
{
aa[i] = ab[i] + 1;
}
</code></pre>
<p>Can I convert this to use just one Array.ForEach? Or, how would you do it, if you wanna go all functional programming crazy? Clunky for loops just looks ugly.</p>
| <p>How about:</p>
<pre><code>aa = ab.ConvertAll(x => x+1);
</code></pre>
|
How to serialize an Exception object in C#? <p>I am trying to serialize an Exception object in C#. However, it appears that it is impossible since the Exception class is not marked as <a href="https://msdn.microsoft.com/en-us/library/system.serializableattribute"><code>[Serializable]</code></a>. Is there a way to work around that?</p>
<p>If something goes wrong during the execution of the application, I want to be informed with the exception that occurred. </p>
<p>My first reflex is to serialize it.</p>
| <p>Create a custom Exception class with the <strong>[Serializable()]</strong> attribute. Here's an example taken from the <a href="http://msdn.microsoft.com/en-us/library/ms173163.aspx">MSDN</a>:</p>
<pre><code>[Serializable()]
public class InvalidDepartmentException : System.Exception
{
public InvalidDepartmentException() { }
public InvalidDepartmentException(string message) : base(message) { }
public InvalidDepartmentException(string message, System.Exception inner) : base(message, inner) { }
// Constructor needed for serialization
// when exception propagates from a remoting server to the client.
protected InvalidDepartmentException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
</code></pre>
|
Python shelve module question <p>Does the Python shelve module have any protection built in to make sure two processes aren't writing to a file at the same time?</p>
| <p>The shelve module uses an underlying database package (such as dbm, <a href="http://docs.python.org/library/gdbm.html#module-gdbm" rel="nofollow">gdbm</a> or bsddb) .</p>
<p>The <a href="http://docs.python.org/library/shelve.html#restrictions" rel="nofollow"><em>restrictions</em> pragraph</a> says (my emphasis):</p>
<blockquote>
<p>The shelve module <strong>does not support concurrent read/write access to shelved objects</strong>. (Multiple simultaneous read accesses are safe.) When a program has a shelf open for writing, no other program should have it open for reading or writing. Unix file locking can be used to solve this, but this differs across Unix versions and requires knowledge about the database implementation used.</p>
</blockquote>
<p>Conclusion: it depends on OS and the underlying DB. To keep things portable, do not build on concurrency.</p>
|
Display different header depending on page selected <p>I have an asp.net website with 5 items (home, products, news, about, contact) on the main horizontal navigation.</p>
<p>The site uses a master page which splits the page into a header, body and footer using </p>
<p>I want to be able to display a different header (which will include different colors and images) depending on which of the 5 navigation items is selected.</p>
<p>Can anyone tell me the best way to achieve this without bloating the page download?</p>
<p>I know my way around asp.net, html, css, javascript and vb but I am no expert.</p>
| <p>I'd probably create a base CSS class that they'd all use, and then create 5 different themes in the app_themes directory (create one if you don't have one), one for each nav option; in there, you can override the base CSS with more specific options to change the background images / colors. If you're using Asp:Images (instead of background images with CSS), you can also change the source using a .theme file in each theme. This way, you'd only download the relevant files. You'll have to change the Page.Theme on Page_Init.</p>
|
Why does C# designer-generated code (like Form1.designer.cs) play havoc with Subversion? <p>My workshop has recently switched to Subversion from SourceSafe, freeing us from automatic locks. This led to concurrent editing of the Forms, which is wonderful. But when multiple developers commit their changes, the code files created by the designer (all the files named <code>TheFormName.designer.cs</code>) cause conflicts which are very difficult to resolve.</p>
<p>As far as I can tell, this is because the code generated by the designer is heavily re-arranged whenever the user modifies it, no matter how little the actual change really did.</p>
<ul>
<li>How do I make these conflicts easier to resolve? </li>
<li>Is there some way to tell the designer to modify the code less?</li>
<li>How do you, the experienced C# teams, deal with concurrent modification of a Form?</li>
</ul>
| <p>Here are some things to try:</p>
<ul>
<li>Make things more modular. Use components like User Controls etc. to split forms into multiple, smaller physical files.</li>
<li>Use presentation layer design patterns like MVP to move code out of views and into standard POCO classes.</li>
<li>Recent versions of SVN allow you to take hard locks - use this to avoid complex merge scenarios.</li>
</ul>
<p>Hope that helps.</p>
|
Regarding how best to expose programming to a foreign audience <p>I'm writing a novel at the moment and, while programming will not be receiving a great deal of focus, I do want to at least get it into the reader's head that a character's coding background could cause them to be the way there are about various things.</p>
<p>So, my question is this: what d'you reckon is the best way to talk about the art in such a manner that the reader gains a bit of comprehension without being scared away? Should I drop "smart-sounding" keywords here and there? Include a bit of actual code? All suggestions are welcome...</p>
| <p>Talk about emotions, about what the programmer feels when working at its craft. Talk about his moments of doubt, his moments of pride.</p>
<p>Talk about his relations with his manager, his colleages, his friends and family.</p>
<p>If you want the reader get empathy with your character, talk about what is universal in programmer's way of living, not about what is specific.</p>
<p>Not novel-related, but an excellent base for storytelling: take a look at <a href="http://rads.stackoverflow.com/amzn/click/0060391685" rel="nofollow">Story</a>, by Robert McKee.</p>
|
Help with Regex patterns <p>I need some help with regex.</p>
<ol>
<li><p>I have a pattern AB.* , this pattern should match for strings
like AB.CD AB.CDX (AB.whatever).and
so on..But it should NOT match
strings like AB,AB.CD.CD ,AB.CD.
AB.CD.CD that is ,if it encounters a
second dot in the string. whats the
regex for this?</p></li>
<li><p>I have a pattern AB.** , this pattern should match strings like
AB,AB.CD.CD, AB.CD. AB.CD.CD but NOT
strings like AB.CD ,AB.CDX,
AB.whatever Whats the regex for
this?</p></li>
</ol>
<p>Thanks a lot.</p>
| <p>Looks like you've got globs not regular expressions. Dot matches any char, and * makes the previous element match any 0+ times.</p>
<p>1) <code>AB\.[^.]*</code>
Escape the first dot so it matches a literal dot, and then match any character other than a dot, any number of times. </p>
<p>2) <code>"^(AB)|(AB\.[^.]*\.[^.]*$"</code>
This matches <code>AB</code> or <code>AB</code> followed by <code>.<stuff>.<stuff></code></p>
|
LR1 Parser and Epsilon <p>I'm trying to understand how LR1 Parsers work but I came up with a strange problem: What if the grammar contains Epsilons? For instance: if I have the grammar:</p>
<pre><code>S -> A
A -> a A | B
B -> a
</code></pre>
<p>It's clear how to start:</p>
<pre><code>S -> .A
A -> .a A
A -> .B
</code></pre>
<p>... and so on</p>
<p>but I don't know how to do it for such a grammar:</p>
<pre><code>S -> A
A -> a A a | \epsilon
</code></pre>
<p>Is it correct to do:</p>
<pre><code>S -> .A
A -> .a A a
( A -> .\epsilon )
</code></pre>
<p>And then make this State in the DFA accepting? </p>
<p>Any help would really be appreciated!</p>
| <p>Yes, exactly (think of the epsilon as empty space, where there aren't two places for the dot at the sides).</p>
<p>In an LR(0) automaton, you would make the state accepting and reduce to A. However, due to the <code>A->a A a</code> production, there'd be a shift/reduce conflict.</p>
<p>In a LR(1) automaton, you would determine whether to shift or reduce using lookahead (<code>a</code> -> shift, anything in <code>FOLLOW(A)</code> -> reduce)</p>
<p>See the <a href="http://en.wikipedia.org/wiki/LR_parser" rel="nofollow">Wikipedia article</a></p>
|
reporting services virtual directory <p>i have iis7 i had build the report using business intelligence studio but i cant able to deploy the reports.it has given the error that "you are not attached to the server" but i install the reporting services in my admin account only </p>
| <p>Can you log into the management website using your browser: <a href="http://localhost/reports" rel="nofollow">http://localhost/reports</a> ???</p>
|
Why is my Access database not up-to-date when I read it from another process? <p>In my application I do the follwing things:</p>
<ol>
<li>Open a Access database (.mdb) using Jet/ADO and VB6</li>
<li>Clear and re-fill a table with new data </li>
<li>Close the database</li>
<li>Start another process which does something with the new data.</li>
</ol>
<p>The problem is that <em>sometimes</em> the second process cannot find the new data. Sometimes the table is just empty, sometimes RecordCount > 0, but EOF is true and I cannot do a MoveFirst or MoveNext. In a nutshell: All kinds of weird things.</p>
<p>My current workaround is adding a delay between closing the database and starting the second process.</p>
<ul>
<li>What is happening here?</li>
<li>Can I do something about it? (Besides using a different database)</li>
</ul>
| <p>Just a guess but I might be due to the fact that the Jet engine features a read cache and lazy writes:</p>
<p><a href="http://support.microsoft.com/kb/240317/en-us" rel="nofollow">How To Implement Multiuser Custom Counters in Jet 4.0 and ADO 2.1</a></p>
<p>"Microsoft Jet has a read-cache that is updated every PageTimeout milliseconds (default is 5000ms = 5 seconds). It also has a lazy-write mechanism that operates on a separate thread to main processing and thus writes changes to disk asynchronously. These two mechanisms help boost performance, but in certain situations that require high concurrency, they may create problems."</p>
<p>The article suggests using Jet's RefreshCache method and to set the Jet OLEDB:Transaction Commit Mode to 1 millisecond (one advantage for ADO over DAO for Jet is that you can alter this setting without changing the value in the registry).</p>
<p>P.S. you should consider editing Access database (.mdb) to mention 'Jet' instead and using the 'Jet' tag too, otherwise you'll get a comment from a certain SO user who is pernickety about these things :)</p>
|
UML state of the art <p>I'm a fan of UML and use Fowlers <a href="http://rads.stackoverflow.com/amzn/click/0321193687" rel="nofollow" title="UML Distilled">UML distilled</a> book as a reference.</p>
<p>My question is : have things moved on in UML, what is the current 'state of the art'.
Is there a better reference book for modern UML or is the above still a good reference.</p>
<p>I'd be less interested in 'proposed extensions' and things committees are considering; really I'm looking for what practitioners are actually using, similarly to the content of the Fowler book.</p>
| <p>Tool support for version 2.0 is good and practice is to use them, so if you've got the third edition then you've got a good introduction.</p>
<p>The 'state of the art' depends what arena your working in.</p>
<p>For companies which have been using DOORS for ever, UML tools (Sparx Systems Enterprise Architect) include requirements support and integrate with the DOORS database. Such support is used extensively in large projects. The requirements concept came from the SysML extension, but you don't need to know SysML to use them.</p>
<p>Embedded systems also use UML tools with full code generation from action semantics - actions define what the methods do. Such tools generate the full code rather than just method outlines which tools at the EA price-point generate. If you want to look at such tools, Artisan now have a free single user version for download. </p>
|
SVN for Delphi Developers <p>I have posted a question before, <a href="http://stackoverflow.com/questions/225115/delphi-moving-away-from-vss">Moving away from VSS</a>, in which I asked about the best VCS control for Delphi developers who were using VSS. Most developers seem to use svn with TortoiseSVN. I tried this for few days and I think it's the best route to go with.</p>
<p>However, I still have some confusion about the way that svn works so here are a few questions that I'd like answered:</p>
<ol>
<li><p>Can I work with old lock way(checkout-modify-checkin) that vss uses?</p></li>
<li><p>Delphi forms have two files (MyForm.pas, MyForm.dfm). When I add any control to the form, both files will be modified so I want to commit "myform.pas" and have "myform.dfm" commit with it too. Am I missing anything here?</p></li>
<li><p>The same applies for the Delphi Project file. Because this links with other files, all of them should be committed when I change the project file.</p></li>
<li><p>What files do you have marked to be ignored in TSVN, so TSVN will not look for these files like (<em>.dcu,</em>.exe, ...), and can I export it from one Pc to other?</p></li>
</ol>
<p>I now have to change the way I'm thinking in vss style, and need to change it for SVN style, but with vss, all things were managed within the IDE, which was fantastic ;-).</p>
<p><strong>UPDATE:</strong></p>
<p>5.If I commit the Delphi form(.pas & dfm) and found some one already updated the version before, how do you resolve the conflict if there some new controls and events added to that form and unit(this require Delphi developer with svn).</p>
| <ol>
<li>Yes, you could still lock files, but it's not recommended. You have to set the svn:needs-lock property on all the files you might want to lock so they get the readonly flag set when you check out. But again, that's not the recommended work flow for text files. Just give the modify-merge work flow a try!</li>
<li>Since you're using TortoiseSVN: right-click on your parent folder, choose "Commit". In the commit dialog, you will see all files that need committing. Just check both the myform.pas and the myform.dfm file for the commit. All checked files will get committed together, no need (and definitely not recommended!) to commit each file individually!</li>
<li>See 2. - But you should read the wonderful <a href="http://svnbook.red-bean.com/">Subversion book</a> first to get familiar with the concept. You should always commit all files that belong to a logical change. For example, if you add new controls to your form and implement the code to handle it, you may have more than just the form files modified but several files more. Always commit all those files together since a commit is a logical entity.</li>
<li>You don't have to 'export' ignore settings. Just add the svn:ignored property. That's very easy to do with TortoiseSVN as explained in the <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-ignore.html">docs</a>.</li>
</ol>
|
What's the right way, for testability, to add functionality to a ComboBox? <p>The desired functionality of the 'enhanced' combo box is a quick find method. Each item in the combobox has a ToString() method, such that they can be displayed in the drop down list. On clicking an item in the drop down list, the combobox's observers are notified of the selection.</p>
<p>Also, every time the typed text in the combobox changes, a list of "Candidates" is generated, made of all those items in the drop down list which contain the text typed in so far. Hitting enter takes you to the first candidate in that list, repeatedly hitting enter cycles you through the list.</p>
<p>I've implemented this functionality by deriving from ComboBox - I figured this made sense as I'm still functionally left with a combobox, it just has this "QuickFind" feature added. However, the logic to create the candidate list and cycle through it, whilst simple, isn't totally trivial, and would enjoy some testing.</p>
<p>However, as seen <a href="http://stackoverflow.com/questions/479587/testing-custom-control-derived-from-combobox">here</a> it doesn't seem to be all that easy to test a ComboBox just by constructing it and prodding the extra routines I've added - it needs to exist on a form for it to behave the same way as it does in the application. This seems altogether too much effort to test a simple addition to a simple combo box!</p>
<p>Nothing in the code to cycle through the candidates is specific to my application however - I have created a general control that may be used in any number of contexts, the only requirement being that the objects in the combobox have a ToString() methiod, which is the same restriction placed on objects going into normal comboboxes anyway, and is guaranteed by C# .NET.</p>
<p>So, with testability in mind, where would you put the enhanced functionality?</p>
| <p>As with the post you references: seperating the logic from the gui elements is also the solution here.</p>
<p>You should consider using a controller-like class which exposes a list of items which you can databind to your ComboBox' DataSource. The controller itself is responsible for maintaining this list.</p>
<p>So whenever you type a letter in the ComboBox you call a function on the controller, let's say UpdateList(string typedString). In this way you have seperated the logic of filling the list with 'candidates'.</p>
<p>Now you can easily write a number of tests which each call UpdateList() with different arguments and inspect the list of items afterwards. No GUI stuff needed to do the testing, you're only testing the algorithm itself.</p>
|
UIView Clipped By Statusbar until Autorotate <p>Ive created a multiview application that uses multiple controllers to display and control views. The problem Im having is, when the simulator initially loads the view the header is partially covered by the bar at top of screen and the tool bar at the base is not touching the base of the screen. I used the Interface builder size attributes to control the view when the iphone rotates and it works perfectly. All smaps into place perfectly both in landscape and portrait mode AFTER a rotation but the problem is with the initial load before a rotation occurs.
Your thoughts a much appreciated.
Tony</p>
| <p>I grappled with this issue for days and days--no amount of fiddling in IB worked.</p>
<p>Ultimately I got it to work by adding this line: </p>
<pre><code>mainViewController.view.frame = window.screen.applicationFrame;
</code></pre>
<p>to the application:didFinishLaunchingWithOptions: method. (Where mainViewController is the primary UIViewController).</p>
|
Serving favicon.ico in ASP.NET MVC <p>What is the final/best recommendation for how to serve favicon.ico in ASP.NET MVC?</p>
<p>I am currently doing the following :</p>
<ul>
<li><p>Adding an entry to the <strong>very beginning</strong> of my RegisterRoutes method :</p>
<pre><code>routes.IgnoreRoute("favicon.ico");
</code></pre></li>
<li><p>Placing favicon.ico in the root of my application (which is also going to be the root of my domain).</p></li>
</ul>
<p>I have two questions :</p>
<ul>
<li>Is there no way to put favicon.ico somewhere other than the root of my application. Its pretty icky being right there at the same level as <code>Content</code> and <code>Controllers</code>.</li>
<li><p>Is this <code>IgnoreRoute("favicon.ico")</code> statement sufficient - or should I also do the following as discussed in <a href="http://haacked.com/archive/2008/07/14/make-routing-ignore-requests-for-a-file-extension.aspx">a blog post from Phil Haack</a>. I'm not aware of ever having seen a request to favicon.ico in any directory other than the root - which would make this unnecessary (but its nice to know how to do it).</p>
<pre><code>routes.IgnoreRoute("{*favicon}", new {favicon=@"(.*/)?favicon.ico(/.*)?"});
</code></pre></li>
</ul>
| <p>Placing favicon.ico in the root of your domain only really affects IE5, IIRC. For more modern browsers you should be able to include a link tag to point to another directory:</p>
<pre><code><link rel="SHORTCUT ICON" href="http://www.mydomain.com/content/favicon.ico"/>
</code></pre>
<p>You can also use non-ico files for browsers other than IE, for which I'd maybe use the following conditional statement to serve a PNG to FF,etc, and an ICO to IE:</p>
<pre><code><link rel="icon" type="image/png" href="http://www.mydomain.com/content/favicon.png" />
<!--[if IE]>
<link rel="shortcut icon" href="http://www.mydomain.com/content/favicon.ico" type="image/vnd.microsoft.icon" />
<![endif]-->
</code></pre>
|
Delphi PDF generation <p>We're using Fast Reports to create reports but we're not very happy with the quality of the PDFs it creates. I know we can plug in other PDF components instead of the one that comes with FastReports so my question is</p>
<p>What good PDF components are there out there (Free or Commercial) for Delphi? Ideally it should not require any dlls.</p>
<p><strong>Edit:</strong> I bought <a href="http://www.gnostice.com/">Gnostice</a> in the end as it had the FastReports integration, source available and a fairly good reputation. I did however find an issue (after I had bought it) with exporting multipage reports from FastReports to PDF where the component leaks memory and corrupts the output. I've reported it to Gnostice so I guess we'll see how good their support is in the next few days...</p>
<p><strong>Edit 2:</strong> Gnostice came back with a fix that rectifies the memory leak and the corrupted output.</p>
| <p>We are using Gnostice and are very pleased with it. It allows us to print our ReportBuilder reports to PDF, HTML, XML, Excel, Gif, ...</p>
<p><hr /></p>
<p>Some minor issues we have come accross working with the component</p>
<ol>
<li>Somewhere deep in the bowels of the component, Application.Processmessages get's called. You have to make sure your code handles reëntrance.</li>
<li>We had to set Preferences.UseImagesAsResources of the TgtDocSettings component to True to resolve AV's when printing to anything else but PDF.</li>
<li>Probably due to the way we use the component but the first printed page was always Portrait. We had to add a call to gtRBExportInterface.Engine.Settings.Page.Orientation to set the orientation to landscape if needed.</li>
</ol>
|
Shut down a ATL application cleanly <p>I have developed a console ATL application and want to trap the close?, exit?, terminate? event so that I can close log files and perform a general clean-up on exit.</p>
<p>How can I trap the 'terminate' event that would result from someone ending the .exe in the task manager?</p>
<p><strong>EDIT:</strong></p>
<p>It's a console application, I've attached the main class. Could you possibly point to where and how I should use <code>SetConsoleCtrlHandler</code>?</p>
<pre><code>// Override CAtlExeModuleT members
int WinMain(int nShowCmd) throw()
{
if (CAtlBaseModule::m_bInitFailed) //ctor failed somewhere
{
ATLASSERT(0);
return -1;
}
HRESULT hr = S_OK;
LPTSTR lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT
if( ParseCommandLine( lpCmdLine, &hr ) )
{
if( SUCCEEDED( RegisterClassObjects( CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE ) ) )
{
CComPtr<IRORCAdapterMain> pAdapter;
if( SUCCEEDED( pAdapter.CoCreateInstance( L"RORCAdapter.RORCAdapterMain" ) ) )
{
if( SUCCEEDED( pAdapter->StartAdapter() ) )
{
MSG msg;
while( GetMessage( &msg, 0, 0, 0 ) )
DispatchMessage( &msg );
}
}
RevokeClassObjects();
}
}
</code></pre>
| <p>You can't trap "End Process" from the Processes tab in Task Manager. If a program could trap it, how would you kill it?</p>
<p>To respond to "End Process" on the Applications tab in Task Manager, handle the WM_CLOSE message in your main window.</p>
<p>This assumes that your ATL app is a Windows GUI application. If it's a console application, you need to look at SetConsoleCtrlHandler.</p>
|
Log analyzer for non-web-applications <p>I have been searching for some kind of tool to analyse log files that are in custom format (my own format for my own program for example). There are many tools that are designed for web-traffic log analysing, but I haven't found suitable tools for custom log files. I'd be happy to find one where I can collect for example all the timestamps and draw conclusions or graphs based on that. For example show TPS (transactions per second).</p>
<p>I'd preferably use free programs. Basically it can be any kind of data analyser as long as it's capable of parsing log files. I would write a program of my own if I only needed to analyse only one kind of files, but I have need to analyse wide variety of files. </p>
<p>I did try to google for suitable tool for a long time but every analyser seems to be designed for web traffic.</p>
| <p>With <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&displaylang=en" rel="nofollow">Log Parser</a> you get info by simple sql query.</p>
<p>At cmd line for text file use like that:</p>
<pre><code>LogParser -i:textline "select * from 'c:\path\*.txt' where text like '%TEXT TO FIND%'"
</code></pre>
<p>or try with <a href="http://www.codeplex.com/visuallogparser" rel="nofollow">GUI</a>.</p>
|
Validate inputs that are not inside a form with jQuery Validation plugin <p>How can I validate some inputs that are not inside a form tag?</p>
<p>All the samples I found have a form tag, but I want to validate some inputs that are not inside a form.</p>
| <p><a href="http://stackoverflow.com/a/487690/594235">The previously accepted answer (since deleted)</a> was linking to <a href="http://code.google.com/p/jquery-validator/" rel="nofollow">a plugin</a> that was last updated in January 2009. This obsolete plugin is very different than <a href="http://jqueryvalidation.org" rel="nofollow">the plugin the OP was asking about</a>:</p>
<p><strong>Title</strong>: "Validate inputs that are not inside a form <strong>with jQuery Validation plugin</strong>"</p>
<p><strong>Tag</strong>: <a href="/questions/tagged/jquery-validate" class="post-tag" title="show questions tagged 'jquery-validate'" rel="tag">jquery-validate</a></p>
<p>Using <a href="http://jqueryvalidation.org" rel="nofollow">the jQuery Validate plugin</a>, you <strong>cannot</strong> validate input elements that are contained outside of a <code><form></form></code> container. <strong>There is no workaround for this limitation.</strong></p>
<p><strong>DEMO 1</strong>: Shows the proper usage with a <code>form</code> container.</p>
<pre><code><form id="myform">
<input type="text" name="myinput" />
<input type="submit" />
</form>
</code></pre>
<p><a href="http://jsfiddle.net/nswnomn6/" rel="nofollow">http://jsfiddle.net/nswnomn6/</a></p>
<hr>
<p><strong>DEMO 2</strong>: Shows the <code>form</code> container changed into a <code>div</code> and the same code is now totally broken. The plugin does nothing without a <code>form</code> container.</p>
<pre><code><div id="myform">
<input type="text" name="myinput" />
<input type="submit" />
</div>
</code></pre>
<p><a href="http://jsfiddle.net/nswnomn6/1/" rel="nofollow">http://jsfiddle.net/nswnomn6/1/</a></p>
<hr>
<p>Your only alternative would be to use a different jQuery plugin for form validation. Unfortunately, I know of no jQuery form validation plugin that would allow you to validate input elements outside of a <code><form></code> container.</p>
|
Best Practice for Using Java System Properties <p>Our code uses a lot of system properties eg, 'java.io.tmpdir', 'user.home', 'user.name' etc. We do not have any constants defined for these anywhere (and neither does java I think) or any other clever thing for dealing with them so they are in plain text littered throughout the code.</p>
<pre><code>String tempFolderPath = System.getProperty("java.io.tmpdir");
</code></pre>
<p>How is everyone using system properties?</p>
| <p>I would treat this just as any other String constant you have scattered throughout your code and define a constant variable for it. Granted, in this case "java.io.tmpdir" is unlikely to change, but you never know. (I don't mean that Sun might change the meaning of "java.io.tmpdir", or what system property it points to, but that you might change your mind about what system property you need to read.)</p>
<p>If you're only using a particular property within one class, then I'd define the constants right in that class.</p>
<pre><code>private final String TEMPDIR = "java.io.tmpdir";
</code></pre>
<p>If you're using the same properties in different classes, you may want to define an static class of your own to hold the constants you use most often.</p>
<pre><code>public final Class Prop {
public static final String TEMPDIR = "java.io.tmpdir";
...
}
</code></pre>
<p>Then, everywhere you need to use that constant just call it using</p>
<pre><code>System.getProperty(Prop.TEMPDIR);
</code></pre>
|
Automated code sanity check tools for Ruby <p>What tools do you use for automated code sanity checks and adhering to the coding conventions in your Ruby apps? How do you incorporate them into your process? (I mean tools like roodi, reek, heckle, rcov, dcov, etc.)</p>
| <p>I'd suggest taking a look at <a href="https://github.com/bbatsov/rubocop" rel="nofollow">RuboCop</a>. It is a Ruby code style checker based on the <a href="https://github.com/bbatsov/rubocop" rel="nofollow">Ruby Style Guide</a>. It's maintained pretty actively and it's based on standard Ruby tooling (like the <code>ripper</code> library). It works well with Ruby 1.9 and 2.0 and has great Emacs integration.</p>
|
Web usability - datalists and operations on rows of data <p>Where you have a databound list of items and for each item you may want to provide users the ability to (for example):</p>
<ul>
<li>Delete</li>
<li>Download</li>
<li>View Detail</li>
<li>or 'mark' in some way</li>
</ul>
<p>You have a few options:</p>
<ul>
<li>Provide buttons or links within the row itself to complete the operation on the row item</li>
<li>Provide a checkbox select within the row and then a means of performing an operation of a group of selected items</li>
<li>A combination of the above (some operations - 'View Detail' for example - don't work in a grouped selection method)</li>
</ul>
<p>What do people think is the most usable approach to providing this kind of interaction? </p>
<p>Links to examples of 'usable' lists would be good.</p>
| <p>My opinion : It depends on the data displayed in this table.</p>
<p>If I really need to execute one operation on several elements, for example to delete 10 elements, I would expect to have the checkbox with a global button option. It is really user unfriendly to click 10 times on a link to execute this operation.</p>
<p>So, maybe the combination of checkbox and links is a good choice.</p>
|
SQL CASE Statement Versus Conditional Statements In Programming Language <p>I'm going through some old stored procedures at work and constantly come across</p>
<pre><code>CASE MyColumn WHEN 'Y' THEN 'Yes' WHEN 'N' THEN 'No' ELSE 'Unknown' END
</code></pre>
<p>It gets even worse when this is tied not to a word, but instead a colour.</p>
<pre><code>CASE MyColumn WHEN 'Y' THEN 'style="background-color:pink"' ELSE '' END
</code></pre>
<p>The reason this was done was for older ASP 1 pages where everything had to be done inline, but as it's such a large system it's impossible to keep up with updating all the pages.</p>
<p>Can anyone give any valid evidence that using a SQL query for conditional statements surpasses that in other languages such as C# or Java? Is this good practice for speed? Should the plain value be returned and the presentation layer decide what should be done?</p>
| <p>When speed is of the essence, the SQL case statements might even be the fastest (I'll run a test) but for maintainability, returning the plain values to the presentation layer (or some business layer thingy) is the best option. </p>
<p>[update] ran some quick and dirty tests (code below) and found the C# code variant slightly faster than the SQL case variant. Conclusion: returning the 'raw' data and manipulating it in the presentation layer is both quicker and more maintainable.</p>
<p>-Edoode</p>
<p>I retrieved 196288 rows with queries below.</p>
<pre><code>StringBuilder result = new StringBuilder();
using (SqlConnection conn = new SqlConnection(Settings.Default.Conn))
{
conn.Open();
string cmd = "select [state], case [state] when 'ca' then 'california' else [state] end from member";
SqlCommand command = new SqlCommand(cmd, conn);
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
result.AppendLine(reader.GetString(1));
}
}
}
</code></pre>
<p>C# variant:</p>
<pre><code>StringBuilder result = new StringBuilder();
using (SqlConnection conn = new SqlConnection(Settings.Default.Conn))
{
conn.Open();
string cmd = "select [state] from member";
SqlCommand command = new SqlCommand(cmd, conn);
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
result.AppendLine(reader.GetString(0) == "ca" ? "california" : reader.GetString(0));
}
}
</code></pre>
<p>}</p>
|
navigation for limiting sql records <p>I want to write a page that will show all the records from a database, and have it limited using the SQL LIMIT syntax. </p>
<p>My question is how would I use PHP to automatically generate the links? Would I have a variable that would automatically increase somehow, hardcode the links in etc, Is there a convention or best practise for this kind of thing?</p>
| <p>This is <a href="http://php.about.com/od/phpwithmysql/ss/php_pagination.htm" rel="nofollow">standard pagination</a> it sounds like. Basically you will use the <a href="http://php.about.com/od/mysqlcommands/g/Limit_sql.htm" rel="nofollow">LIMIT</a> functionality in MySQL, set amount of records per page, and finally track a page number.</p>
<p>You'll run this off of a $_GET variable called "page". If Page is equal to 2, and # of results per page is 10, then your <a href="http://php.about.com/od/mysqlcommands/g/Limit_sql.htm" rel="nofollow">LIMIT</a> should start on the 21st record. So your <a href="http://php.about.com/od/mysqlcommands/g/Limit_sql.htm" rel="nofollow">LIMIT</a> clause becomes LIMIT 21, 10.</p>
<p>The most work will be done on building the links for Page 1, Page 2, Page 3, etc. You'll need to know how many records you have, divided by the limit of records per page. 100 records and 10 records per page? You'll have Page 1 - Page 10. Each link simply calls the same page, but with a different $_GET["page"] value.</p>
<p>This is a cursory description of <a href="http://php.about.com/od/phpwithmysql/ss/php_pagination.htm" rel="nofollow">pagination</a>. There are <a href="http://www.google.com/search?hl=en&q=tutorial+pagination+php+mysql&btnG=Google+Search&aq=f&oq=" rel="nofollow">tutorials available online</a>.</p>
|
How can I get interactive Python to avoid using readline while allowing utf-8 input? <p>I use a terminal (9term) that does command-line editing itself - programs that use readline just get in its way. It's fully utf-8 aware. How can I make an interactive python session disable readline while retaining utf-8 input and output?</p>
<p>Currently I use:</p>
<pre><code>LANG=en_GB.UTF-8 export LANG
cat | python -i
</code></pre>
<p>however this causes sys.stdin.encoding to be None, which implies Ascii
(the system default encoding, which doesn't seem to be changeable)</p>
<pre><code>TERM=dumb python
</code></pre>
<p>doesn't disable readline (and it mangles utf-8 input also).</p>
<p>I'm new to python, so apologies if this is an obvious question.</p>
| <p>In the past, I've disabled Python readline by rebuilding it from source: <code>configure --disable-readline</code></p>
<p>This might be overkill, though, for your situation.</p>
|
Error with Html.RouteLink in ASP.NET MVC RC <p>I was using Html.RouteLink("LINKTEXT","RouteName",new RouteValueDictionary()) in asp.net MVC beta without problem, today I upgrade to ASP.NET MVC RC and this does no create the link anymore. The route still works because I type in the browser and I go to the Page I want. Any help?</p>
| <p>It's bug in RC. Workaround for now is to put your controller and action names in RouteLink. </p>
<p>For example: </p>
<pre><code><%= Html.RouteLink(cat.Name, "Category", new { id = cat.id, controller = "Home", action = "Category" })%>
</code></pre>
<p>I also found one more issue with publishing web to shared hosting (mine is on iis6): "specific version" property of system.web.mvc reference in project has to be set to "false". Before it was "true" and I had one error in web.config regarding registration of sys.web.mvc assembly. </p>
|
Allow user to sort columns from a LINQ query in a DataGridView <p>I can't quite work out how to allow a DataGridView populated at runtime to sort (when users click on the column headers) where a LINQ from XML query is the DataSource, via a BindingSource.</p>
<pre><code> Dim QueryReOrder = From Q In Query _
Where ((0 - Q.Qualifier) / cmbTSStakeValue.Text) <= 0.1 _
Order By Q.Qualifier Descending _
Select Q
Dim bs As New BindingSource
bs.DataSource = QueryReOrder
DGFindMatch.DataSource = bs
</code></pre>
<p>Some of the DataGridView's properties are: </p>
<pre><code>Sort Nothing String
SortProperty Nothing System.ComponentModel.PropertyDescriptor
SupportsAdvancedSorting False Boolean
SupportsChangeNotification True Boolean
SupportsFiltering False Boolean
SupportsSearching False Boolean
SupportsSorting False Boolean
</code></pre>
<p>Is there a simple solution that will allow a user to be able to sort these values by clicking the column header?</p>
<p>Thanks!</p>
| <p>You need to get the results of the LINQ query into something supports sorting functionality. This is typically done by deriving a class from BindingList and implementing the Sorting Core functionality in the derived class. </p>
<p>There are many examples of implementations out there to choose from and it is a pretty straight forward thing to implement. <a href="http://msdn.microsoft.com/en-us/library/aa480736.aspx">Here is an example</a> of doing it on MSDN. </p>
<p>Once you have this implemented all you have to do is put your results in it and use it as your DataSource and the Grid should allow users to sort using the columns.</p>
<pre><code> //I know that you asked the question in VB.NET but I don't know the syntax that well.
public class SortableBindingList<T> : BindingList<T>
{
//override necessary sort core methods
}
SortableBindingList<string> list = new SortableBindingList<string>(QueryReOrder.ToList());
//use list as your DataSource now
</code></pre>
|
WinForms AcceptButton not working? <p>Ok, this is bugging me, and I just can't figure out what is wrong...</p>
<p>I have made two forms. First form just has a simple button on it, which opens the other as a dialog like so:</p>
<pre><code>using (Form2 f = new Form2())
{
if (f.ShowDialog() != DialogResult.OK)
MessageBox.Show("Not OK");
else
MessageBox.Show("OK");
}
</code></pre>
<p>The second, which is that <code>Form2</code>, has two buttons on it. All I have done is to set the forms AcceptButton to one, and CancelButton to the other. In my head this is all that should be needed to make this work. But when I run it, I click on the button which opens up Form2. I can now click on the one set as CancelButton, and I get the "Not OK" message box. But when I click on the one set as AcceptButton, nothing happens?
The InitializeComponent code of Form2 looks like this:</p>
<pre><code>private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(211, 13);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// button2
//
this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button2.Location = new System.Drawing.Point(130, 13);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 1;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
//
// Form2
//
this.AcceptButton = this.button1;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.button2;
this.ClientSize = new System.Drawing.Size(298, 59);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form2";
this.Text = "Form2";
this.Load += new System.EventHandler(this.Form2_Load);
this.ResumeLayout(false);
}
</code></pre>
<p>I have done nothing else than add those two buttons, and set the AcceptButton and CancelButton. Why doesn't it work?</p>
| <p>Just setting the AcceptButton/CancelButton is not enough. This just tells which button should be invoked on <kbd>Enter</kbd>/<kbd>Esc</kbd>. You have to set the DialogResult in the Button handler.</p>
|
phpMyAdmin - Did the Config files change? <p>I have just installed phpMyAdmin on my new Fedora Core 10 dedicated server.</p>
<p>I downloaded the phpMyAdmin-3.1.2-english.tar.gz. I extracted it and placed it in this folder /opt/phpMyAdmin-3.1.2-english and i created a symbolic link in the /var/www/html directory so that I can access it like this: <a href="http://www.mydomainname.com/webdb" rel="nofollow">http://www.mydomainname.com/webdb</a>.</p>
<p>When I point my browser to that URL it asks me to login and I can only login using localhost as username and a blank password. So I thought I would change it and follow some web tutorials that suggest to change these lines:</p>
<pre><code>$cfg['Servers'][$i]['auth_type'] = âhttpâ;
$cfg['Servers'][$i]['user'] = âUSERNAMEâ;
$cfg['Servers'][$i]['password'] = âPASSWORDâ;
</code></pre>
<p>However, these lines do not even exist in my config.inc.php!!! I have done this install before and I remember these files being there but not with this isntall.</p>
<p>I tried adding those lines and that didn't make a difference.</p>
<p>Has phpMyAdmin changed their config files or have i installed incorrectly??</p>
<p>Thank you for any help!</p>
<h2>EDIT</h2>
<p>I managed to remove that one and use a "yum install phpMyAdmin" and the config file here works fine! :)</p>
<p>However, I am still unable to access phpMyAdmin using the password and username that I suggest in the config.inc.php. Does this mean that the username and password I suggest is config.inc.php is not in line with the MySQL server username and password?</p>
| <p>Would setting </p>
<pre><code>$cfg['Servers'][$i]['auth_type'] = 'config';
</code></pre>
<p>instead of </p>
<pre><code>$cfg['Servers'][$i]['auth_type'] = âhttpâ;
</code></pre>
<p>help?</p>
<p>See <a href="http://www.un4given.nl/phpMyAdmin/Documentation.html#config" rel="nofollow">http://www.un4given.nl/phpMyAdmin/Documentation.html#config</a> for more information.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.