instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Using a configuration file I want to enable myself to turn on and off things like (third party) logging and using a cache in a C# website. The solution should not be restricted to logging and caching in particular but more general, so I can use it for other things as well.</p>
<p>I have a configuration xml file in which I can assert that logging and caching should be turned on or off (it could also be in the Web.Config, that's not the point right now) which will result in for example a <code>bool logging</code> and a <code>bool caching</code> that are <code>true</code> or <code>false</code>.</p>
<p>The question is about this part:
<strong>What I can do is prepend every logging/caching related statement with <code>if (logging)</code> and <code>if (caching)</code>.
What is better way of programming this? Is there also a programming term for this kind of problem? Maybe attributes are also a way to go?</strong></p>
|
<p>Why not just use the web.config and the System.Configuration functionality that already exists?</p>
<p>Your web app is going to parse web.config on every page load anyway, so the overhead involved in having yet another XML config file seems overkill when you can just define your own section on the existing configuration.</p>
|
<p>Consult <a href="http://msdn.microsoft.com/en-us/library/ms178606.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms178606.aspx</a> for specifics regarding configuring cache.</p>
| 11,173
|
<p>Please forgive my long question. I have an idea for a design that I could use some comments on. Is it a good idea to do this? And what are the pit falls I should be aware of? Are there other similar implementations that are better?</p>
<p><strong>My situation is as follows:</strong><br>
I am working on a rewrite of a windows forms application that connects to a SQL 2008 (earlier it was SQL 2005) server. The application is an "expert-system" for an engineering company where we store structured data about constructions. We have control of all installations of the client software, we have no external customers or users, they are all internal to the company, and they are all be trusted not to do anything malicious to the software or database.</p>
<p>The current design doesn't have too many tables (about 10 - 20) but some of them have millions of records that belong to several hundred constructions. The systems performance has been ok so far, but it is starting to degrade as we are pushing the limits of the design. </p>
<p>As part of the rewrite I am considering splitting the database into one master database and several "child" databases where each describes one construction. Each child database should be of identical design. This should eliminate the performance problems we are seeing today since the data stored in each database would be less than one percent of the total data amount. </p>
<p>My concern is that instead of maintaining one database we will now get hundreds of databases that must be kept up to date. The system is constantly evolving as the companys requirements change (you know how it is), and while we try to look forward to reduce the number of changes the changes will come. So we will need a system where we keep track of all database changes done to the system so they can be applied to the child databases. Updating the client application won't be a problem, we have good control of that aspect.</p>
<p>I am thinking of a change tracing system where we store database scripts for all changes in a table in the master database. We can then give each change a version number and we can store a current version number in each child database. When the client program connects to a child database we can then check the version number of the database against the current version number of the master database and if there are patches with version numbers greater than the version number of the child database we run these and update the child database to the latest version. </p>
<p>As I see it this should work well. Any changes to the system will first be tested and validated before committed as a new version of the database. The change will then be applied to the database the first time a user opens it. I suppose we would open the database in exclusive mode while applying the changes, but as long as the changes aren't too frequent this should not be a problem.</p>
<p>So what do you think? Will this work? Have any of you done something similar? Should we scrap the solution and go for the monolithic system instead?</p>
|
<p>I have a similar situation here, though I use MySQL. Every database has a versions table that contains the version (simply an integer) and a short comment of what has changed in this version. I use a script to update the databases. Every database change can be in one function or sometimes one change is made by multiple functions. Functions contain the version number in the function name. The script looks up the highest version number in a database and applies only the functions that have a higher version number in order.</p>
<p>This makes it easy to update databases (just add new change functions) and allows me to quickly upgrade a recovered database if necessary (just run the script again).</p>
<p>Even when testing the changes before this allows for defensive changes. If you make some heavy changes on a table and you want to play it safe:</p>
<pre><code>def change103(...):
"Create new table."
def change104(...):
"""Transfer data from old table to new table and make
complicated changes in the process.
"""
def change105(...):
"Drop old table"
def change106(...):
"Rename new table to old table"
</code></pre>
<p>if in change104() is something going wrong (and throws an exception) you can simply delete the already converted data from the new table, fix your change function and run the script again.</p>
<p>But I don't think that changing a database dynamically when a client connects is a good idea. Sometimes changes can take some time. And the software that accesses a database should match the schema of the database. You have somehow to keep them in sync. Maybe you could distribute a new software version and then you want to upgrade the database when a client is actually starting to use this new software. But I haven't tried that.</p>
|
<p>Better don't create additional databases. At first glance you may think that you'll get some performance gain, but actually you get support nightmare. Remember - what can break, does break sooner or later. </p>
<p>It is way simpler to perform and optimize queries in single database. It is much easier manage user permissions in single database. It is much easier to make consistent backups for single database.</p>
<p>Like KenG said, if you need break your large tables - consider partitioning them. And add some drives :)</p>
<p>But at first run SQL profiler on your database and optimize indexes and queries. Several million rows is usually not a big problem to handle (unless your customer needs <em>live</em> totaling over half of these, in which case no partitioning can help).</p>
| 31,524
|
<p>Google app engine tells me to optimize this code. Anybody any ideas what I could do?</p>
<pre><code>def index(request):
user = users.get_current_user()
return base.views.render('XXX.html',
dict(profiles=Profile.gql("").fetch(limit=100), user=user))
</code></pre>
<p>And later in the template I do:</p>
<pre><code>{% for profile in profiles %}
<a href="/profile/{{profile.user.email}}/"><img src="{{profile.gravatarUrl}}"></a>
<a href="/profile/{{profile.user.email}}/">{{ profile.user.nickname }}</a>
<br/>{{ profile.shortDisplay }}
</code></pre>
<p>Where the methods used are:</p>
<pre><code>def shortDisplay(self):
return "%s/day; %s/week; %s days" % (self.maxPerDay, self.maxPerWeek, self.days)
def gravatarUrl(self):
email = self.user.email().lower()
default = "..."
gravatar_url = "http://www.gravatar.com/avatar.php?"
gravatar_url += urllib.urlencode({'gravatar_id':hashlib.md5(email).hexdigest(),
'default':default, 'size':"64"})
return gravatar_url
</code></pre>
|
<p>The high CPU usage will be due to fetching 100 entities per request. You have several options here:</p>
<ul>
<li>Using Profile.all().fetch(100) will be ever so slightly faster, and easier to read besides.</li>
<li>Remove any extraneous properties from the Profile model. There's significant per-property overhead deserializing entities.</li>
<li>Display fewer users per page.</li>
<li>Store the output of this page in memcache, and render from memcache whenever you can. That way, you don't need to generate the page often, so it doesn't matter so much if it's high CPU.</li>
</ul>
|
<p>It depends where you get the warning of too much CPU.</p>
<p>Is it in the dashboard, it probably is a lot of datastore CPU, no need for optimization.</p>
<p>If the request takes more then 10 sec you need to optimize.</p>
<p>If you get regular Log warnings that a certain request is x.xx over CPU limit it means your application code is taking too long. And needs optimization.</p>
<p>I have found that a lot of Django template stuff does not take a lot of application CPU (50-100 Mcycle). If all the fields for the template are precomputed.</p>
| 38,160
|
<p>I'm writing an image processing program to perform real time processing of video frames. It's in C# using the Emgu.CV library (C#) that wraps the OpenCV library dll (unmanaged C++). Now I have to write my own special algorithm and it needs to be as fast as possible. </p>
<p>Which will be a faster implementation of the algorithm?</p>
<ol>
<li><p>Writing an 'unsafe' function in C#</p></li>
<li><p>Adding the function to the OpenCV library and calling it through Emgu.CV</p></li>
</ol>
<p>I'm guessing C# unsafe is slower because it goes throught the JIT compiler, but would the difference be significant?</p>
<p>Edit:</p>
<p>Compiled for .NET 3.5 under VS2008</p>
|
<p><i>it needs to be as fast as possible</i></p>
<p>Then you're asking the wrong question.</p>
<p>Code it in assembler, with different versions for each significant architecture variant you support.</p>
<p>Use as a guide the output from a good C++ compiler with optimisation, because it probably knows some tricks that you don't. But you'll probably be able to think of some improvements, because C++ doesn't necessarily convey to the compiler all information that might be useful for optimisation. For example, C++ doesn't have the C99 keyword restrict. Although in that particular case many C++ compilers (including MSVC) do now support it, so use it where possible.</p>
<p>Of course if you mean, "I want it to be fast, but not to the extent of going outside C# or C++", then the answer's different ;-)</p>
<p>I would expect C# to at least approach the performance of similar-looking C++ in a lot of cases. I assume of course that the program will be running long enough that the time the JIT itself takes is irrelevant, but if you're processing much video then that seems likely. But I'd also expect there to be certain things which if you do them in unsafe C#, will be far slower than the equivalent thing in C++. I don't know what they are, because all my experience of JITs is in Java rather than CLR. There might also be things which are slower in C++, for instance if your algorithm makes any calls back into C# code.</p>
<p>Unfortunately the only way to be sure how close it is is to write both and test them, which kind of misses the point that writing the C++ version is a bunch of extra effort. However, you might be able to get a rough idea by hacking some quick code which approximates the processing you want to do, without necessarily doing all of it or getting it right. If you algorithm is going to loop over all the pixels and do a few FP ops per pixel, then hacking together a rough benchmark should take all of half an hour.</p>
<p>Usually I would advise against starting out thinking "this needs to be as fast as possible". Requirements should be achievable, and by definition "as X as possible" is only borderline achievable. Requirements should also be testable, and "as X as possible" isn't testable unless you somehow know a theoretical maximum. A more friendly requirement is "this needs to process video frames of such-and-such resolution in real time on such-and-such a speed CPU", or "this needs to be faster than our main competitor's product". If the C# version does that, with a bit to spare to account for unexpected minor issues in the user's setup, then job done.</p>
|
<p>Running on the CPU is always going to be faster than running on a VM on the CPU. I can't believe people are trying to argue otherwise.</p>
<p>For example, we have some fairly heavy image processing work on our web server that's queued up. Initially to get it working, we used PHP's GD functions.</p>
<p>They were slow as hell. We rewrote the functionality we needed in C++.</p>
| 35,489
|
<p>I am encountering very infrequent yet annoying SQL deadlocks on a .NET 2.0 webapp running on top of MS SQL Server 2005. In the past, we have been dealing with the SQL deadlocks in the very empirical way - basically tweaking the queries until it work.</p>
<p>Yet, I found this approach very unsatisfactory: time consuming and unreliable. I would highly prefer to follow deterministic query patterns that would ensure <strong>by design</strong> that no SQL deadlock will be encountered - ever.</p>
<p>For example, in C# multithreaded programming, a simple design rule such as <em>the locks must be taken following their lexicographical order</em> ensures that no deadlock will <em>ever</em> happen.</p>
<p>Are there any SQL coding patterns guaranteed to be deadlock-proof?</p>
|
<p>Writing deadlock-proof code is really hard. Even when you access the tables in the same order you may still get deadlocks [1]. I wrote <a href="http://samsaffron.com/archive/2008/08/27/Deadlocked+" rel="noreferrer">a post on my blog</a> that elaborates through some approaches that will help you avoid and resolve deadlock situations. </p>
<p>If you want to ensure two statements/transactions will never deadlock you may be able to achieve it by observing which locks each statement consumes using the <strong>sp_lock</strong> system stored procedure. To do this you have to either be very fast or use an open transaction with a holdlock hint.</p>
<hr>
<p>Notes:</p>
<ol>
<li>Any SELECT statement that needs more than one lock at once can deadlock against an intelligently designed transaction which grabs the locks in reverse order.</li>
</ol>
|
<p>Quick answer is no, there is no guaranteed technique.</p>
<p>I don't see how you can make any application deadlock proof in general as a design principle if it has any non-trivial throughput. If you pre-emptively lock all the resources you could potentially need in a process in the same order even if you don't end up needing them, you risk the more costly issue where the second process is waiting to acquire the first lock it needs, and your availability is impacted. And as the number of resources in your system grows, even trivial processes have to lock them all in the same order to prevent deadlocks.</p>
<p>The best way to solve SQL deadlock problems, like most performance and availability problems is to look at the workload in the profiler and understand the behavior.</p>
| 13,695
|
<p>Do you have any examples of real life applications of mutation testing? Does it work better than simple test coverage tools? Or is it useless?</p>
<p>What are the advantages/disadvantages of mutation testing in the real world?</p>
|
<p>I looked at mutation test some time ago as a method for checking the efficacy of my automated regression testing scripts. Basically, a number of these scripts had missing checkpoints, so while they were exercising the application being tested correctly, they weren't verifying the results against the baseline data. I found that a far simpler method than changing the code was to write another application to introduce modifications to a copy of the baseline, and re-run the tests against the modified baseline. In this scenario, any test that passed was either faulty or incomplete.</p>
<p>This is not genuine mutation testing, but a method that uses a similar paradigm to test the efficacy of test scripts. It is simple enough to implement, and IMO does a good job.</p>
|
<p>Coverage vs mutation testing. An old question, but I recently came across a recent blog on the topic. Pretty opinionated. But the differences between coverage and mutation testing is clearly articulated.</p>
<p><a href="https://pedrorijo.com/blog/intro-mutation/" rel="nofollow noreferrer">https://pedrorijo.com/blog/intro-mutation/</a></p>
<p>My own experience shows that Pitest is pretty useful, but since the runtime explodes it works only one very fast test sets. In practice this limits where I apply mutation testing.</p>
| 30,048
|
<p>Suppose I have #define foo in various header files. It may expand to some different things. I would like to know (when compiling a .cc file) when a #define is encountered, to what it will expand, it which file it is and where it got included from.</p>
<p>Is it possible? If not, are there any partial solutions that may help?</p>
<p>Feel free to add comments with clarification requests.</p>
<p><strong>Edit: current answers seem to concentrate on the case when there is one #define and I just want to jump to definition or know what the definition is. That's the simple case and yes, your solutions work. But when I have the same #define in different files, and want to know which one kicks in first, none of these techniques is useful. Okay, I actually used #warning carefully to find the right place. But this requires much work.</strong></p>
|
<p>Use -E :</p>
<pre><code># shows preprocessed source with cpp internals removed
g++ -E -P file.cc
# shows preprocessed source kept with macros and include directives
g++ -E -dD -dI -P file.cc
</code></pre>
<p>The internals above are line-markers for gcc which are kinda confusing when you read the output. <code>-P</code> strips them</p>
<pre> -E Stop after the preprocessing stage; do not run the compiler proper.
The output is in the form of preprocessed source code, which is sent to the
standard output.
Input files which don't require preprocessing are ignored.</pre>
<p>Note: comments correctly complain this is only a partial solution. It won't tell you when a macro will be replaced. It shows you the preprocessed source, which can be helpful anyway.</p>
|
<p>Use #warning. It's described <a href="http://gcc.gnu.org/onlinedocs/gcc-3.1.1/cpp/Diagnostics.html#Diagnostics" rel="nofollow noreferrer">here</a>.</p>
| 37,103
|
<p>Is there any way to redefine a class or some of its methods without using typical inheritance? For example:</p>
<pre><code>class third_party_library {
function buggy_function() {
return 'bad result';
}
function other_functions(){
return 'blah';
}
}
</code></pre>
<p>What can I do to replace <code>buggy_function()</code>? Obviously this is what I would like to do</p>
<pre><code>class third_party_library redefines third_party_library{
function buggy_function() {
return 'good result';
}
function other_functions(){
return 'blah';
}
}
</code></pre>
<p>This is my exact dilemma: I updated a third party library that breaks my code. I don't want to modify the library directly, as future updates could break the code again. I'm looking for a seamless way to replace the class method.</p>
<p>I've found this <a href="http://pecl.php.net/package/classkit" rel="noreferrer">library</a> that says it can do it, but I'm wary as it's 4 years old.</p>
<p>EDIT:</p>
<p>I should have clarified that I cannot rename the class from <code>third_party_library</code> to <code>magical_third_party_library</code> or anything else because of framework limitations.</p>
<p>For my purposes, would it be possible to just add a function to the class? I think you can do this in C# with something called a "partial class."</p>
|
<p>It's called <a href="http://en.wikipedia.org/wiki/Monkey_patch" rel="noreferrer">monkey patching</a>. But, PHP doesn't have native support for it.</p>
<p>Though, as others have also pointed out, the <a href="http://docs.php.net/runkit" rel="noreferrer">runkit library</a> is available for adding support to the language and is the successor to <a href="http://docs.php.net/manual/en/book.classkit.php" rel="noreferrer">classkit</a>. And, though it seemed to have been <a href="http://pecl.php.net/package/runkit" rel="noreferrer">abandoned</a> by its creator (having stated that it wasn't compatible with PHP 5.2 and later), the project does now appear to have a <a href="https://github.com/zenovich/runkit" rel="noreferrer">new home and maintainer</a>.</p>
<p>I still <a href="https://stackoverflow.com/revisions/137028/3">can't say I'm a fan</a> of its approach. Making modifications by evaluating strings of code has always seemed to me to be potentially hazardous and difficult to debug.</p>
<p>Still, <a href="http://us2.php.net/manual/en/function.runkit-method-redefine.php" rel="noreferrer"><code>runkit_method_redefine</code></a> appears to be what you're looking for, and an example of its use can be found in <a href="https://github.com/zenovich/runkit/blob/master/tests/runkit_method_redefine.phpt" rel="noreferrer"><code>/tests/runkit_method_redefine.phpt</code></a> in the repository:</p>
<pre class="lang-php prettyprint-override"><code>runkit_method_redefine('third_party_library', 'buggy_function', '',
'return \'good result\''
);
</code></pre>
|
<p>There's alway extending the class with a new, proper, method and calling that class instead of the buggy one.</p>
<pre><code>class my_better_class Extends some_buggy_class {
function non_buggy_function() {
return 'good result';
}
}
</code></pre>
<p>(Sorry for the crappy formatting)</p>
| 16,574
|
<p>I love vim and the speed it gives me. But sometimes, my fingers are too speedy and I find myself typing <code>:WQ</code> instead of <code>:wq</code>. (On a German keyboard, you have to press <kbd>Shift</kbd> to get the colon <code>:</code>.) Vim will then complain that <code>WQ</code> is <code>Not an editor command</code>.</p>
<p>Is there some way to make <code>W</code> and <code>Q</code> editor commands?</p>
|
<p>Try </p>
<pre><code> :command WQ wq
:command Wq wq
:command W w
:command Q q
</code></pre>
<p>This way you can define your own commands. See <code>:help command</code> for more information.</p>
|
<p>And you can use </p>
<pre><code>:cmap WQ wq
</code></pre>
<p>as well.
E.g. I have </p>
<pre><code>cmap h tab help
</code></pre>
<p>in my <code>.vimrc</code> which means opening help pages in a new tab.</p>
<p><a href="https://stackoverflow.com/questions/117150/can-i-re-map-commands-in-vim/119821#comment18676583_119821">Thanks for the tip Jim Stewart</a>:</p>
<blockquote>
<p>But here is a much better solution as the above (for the help mapping,
so that it only applies when you do :h):</p>
<pre><code>cnoreabbrev <expr> h getcmdtype() == ":" && getcmdline() == "h" ? "tab h" : "h"
</code></pre>
</blockquote>
| 14,271
|
<p>Does anyone know where I can get some samples/resources on 4GL language for Progress Database OTHER THAN THE PROGRESS DATABASE WEBSITE?</p>
<p>Thanks</p>
|
<p>Here's a copy of the 4GL handbook from the Progress website.</p>
<p><a href="http://www.progress.com/progress/products/documentation/docs/dvhbk/dvhbk.pdf" rel="nofollow noreferrer">http://www.progress.com/progress/products/documentation/docs/dvhbk/dvhbk.pdf</a></p>
|
<p>What kind of samples do you exactly need? If you want to improve 4GL skills, then 4GL Handbook is a very nice way to get known to the language, it comes with Progress Documentation.</p>
| 49,747
|
<p>I am using a <B> FTPS </b> connection to send a text file
<i>[this file will contain EDI(Electronic Data Interchange) information]</i>to a mailbox INOVIS.I have configured the system to open a FTPS connection and using the PUT command I write the file to a folder on the FTP server.
The problem is: what mode of file transfer should I use? How do I switch between modes?</p>
<p>Moreover which mode is the 'best-practice' to use when transferring file over FTPS connection.
If some one can provide me a small ftp script it would be helpful.</p>
|
<p>Many of the other answers to this question are a collection of nearly correct to outright wrong information.</p>
<p>ASCII mode means that the file should be converted to canonical text form on the wire. Among other things this means:</p>
<ul>
<li>NVT-ASCII character set. Even if the original file is in some other character set, such as ASCII, EBCDIC or UTF-8. Technically this disallows characters with the 8th bit set, but most implementations won't enforce this.</li>
<li>CRLF line endings.</li>
</ul>
<p>EBCDIC mode means a similar set of rules, except that the data on the wire should be in EBCDIC.</p>
<p>LOCAL mode allows sending data with a size other than 8 bits per byte.</p>
<p>IMAGE (or BINARY) mode means that the data should be send without any changes. It is up to the user to ensure that the target system can understand the data once it arrives.</p>
<p>Among other things, this means that the recommendation to use BINARY mode to send text data will fail if one of the systems involved doesn't use a ASCII based character set.</p>
|
<p>If you want an exact copy the data use binary mode - using ascii mode will assume the data is 7bit text (chars 0-127) and truncate any data outside of this range. Dates back to arcane 7bit networking days where ascii mode could save you time.</p>
<p>In a globalized environment that we live in - such that it is quite common to find non-ascii characters e.g. foreign languages, currency symbols etc. - you should always use BINARY mode.</p>
| 10,715
|
<p>How do I setup Public-Key Authentication for SSH?</p>
|
<p>If you have SSH installed, you should be able to run..</p>
<pre><code>ssh-keygen
</code></pre>
<p>Then go through the steps, you'll have two files, <code>id_rsa</code> and <code>id_rsa.pub</code> (the first is your private key, the second is your public key - the one you copy to remote machines)</p>
<p>Then, connect to the remote machine you want to login to, to the file <code>~/.ssh/authorized_keys</code> add the contents of your that <code>id_rsa.pub</code> file.</p>
<p>Oh, and <code>chmod 600</code> all the <code>id_rsa*</code> files (both locally and remote), so no other users can read them:</p>
<pre><code>chmod 600 ~/.ssh/id_rsa*
</code></pre>
<p>Similarly, ensure the remote <code>~/.ssh/authorized_keys</code> file is <code>chmod 600</code> also:</p>
<pre><code>chmod 600 ~/.ssh/authorized_keys
</code></pre>
<p>Then, when you do <code>ssh remote.machine</code>, it should ask you for the key's password, not the remote machine.</p>
<hr>
<p>To make it nicer to use, you can use <code>ssh-agent</code> to hold the decrypted keys in memory - this means you don't have to type your keypair's password every single time. To launch the agent, you run (including the back-tick quotes, which eval the output of the <code>ssh-agent</code> command)</p>
<pre><code>`ssh-agent`
</code></pre>
<p>On some distros, ssh-agent is started automatically. If you run <code>echo $SSH_AUTH_SOCK</code> and it shows a path (probably in /tmp/) it's already setup, so you can skip the previous command.</p>
<p>Then to add your key, you do</p>
<pre><code>ssh-add ~/.ssh/id_rsa
</code></pre>
<p>and enter your passphrase. It's stored until you remove it (using the <code>ssh-add -D</code> command, which removes all keys from the agent)</p>
|
<p>For windows <a href="http://the.earth.li/~sgtatham/putty/0.53b/htmldoc/Chapter8.html" rel="noreferrer">this</a> is a good introduction and guide</p>
<p>Here are some good ssh-agents for systems other than linux.</p>
<ul>
<li>Windows - <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html" rel="noreferrer">pageant</a></li>
<li>OS X - <a href="http://www.askbjoernhansen.com/2005/01/07/sshkeychain_ssh.html" rel="noreferrer">SSHKeychain</a></li>
</ul>
| 2,889
|
<p>I want to make a very simple event bus which will allow any client to subscribe to a particular type of event and when any publisher pushes an event on the bus using <code>EventBus.PushEvent()</code> method only the clients that subscribed to that particular event type will get the event.</p>
<p>I am using C# and .NET 2.0.</p>
|
<p>Tiny Messenger is a good choice, I've been using it in a live project for 2.5 years now. Some code examples from the Wiki (link below):</p>
<p><strong>Publishing</strong></p>
<pre><code>messageHub.Publish(new MyMessage());
</code></pre>
<p><strong>Subscribing</strong></p>
<pre><code>messageHub.Subscribe<MyMessage>((m) => { MessageBox.Show("Message Received!"); });
messageHub.Subscribe<MyMessageAgain>((m) => { MessageBox.Show("Message Received!"); }, (m) => m.Content == "Testing");
</code></pre>
<p>The code's on GitHub: <a href="https://github.com/grumpydev/TinyMessenger" rel="noreferrer">https://github.com/grumpydev/TinyMessenger</a></p>
<p>The Wiki is here: <a href="https://github.com/grumpydev/TinyMessenger/wiki" rel="noreferrer">https://github.com/grumpydev/TinyMessenger/wiki</a></p>
<p>It has a Nuget package also</p>
<pre><code>Install-Package TinyMessenger
</code></pre>
|
<p>You should check out episode 3 in <a href="http://ayende.com/hibernating-rhinos.aspx" rel="nofollow noreferrer">Hibernating Rhinos</a>, Ayende's screen casts series - "Implementing the event broker".</p>
<p>It shows how you can implement a very simple event broker using Windsor to wire things up. Source code is included as well.</p>
<p>The proposed event broker solution is very simple, but it would not take too many hours to augment the solution to allow arguments to be passed along with the events.</p>
| 48,075
|
<p>I am reading through the Public Review Draft of the <a href="http://docs.jboss.org/webbeans/spec/PDR/html/" rel="nofollow noreferrer">Web Beans specification</a> (JSR-299) and I am wondering why it is so 'tightly coupled' to JSF?</p>
<p>Especially the Conversation Context seems only be specified for JSF.</p>
<p>I understand, that it is a goal of WebBeans to integrate JSF and EJB3. But would it not make sense to specify the concept of conversations on a more general level (maybe for Servlets in general and not for a specific web framework)?</p>
<p>Is there any technical reason for this? I think it can hardly be, because Seam (which is some Kind of WebBeans-Prototype) does also support Wicket and provides the concept of conversations.</p>
<p>I think it would be helpful to have a Conversation Scope on Servlet level (injecting of conversation-scoped beans into servlets). In my understanding, this is not the case with the ciurrent specification (see chapter 8.5.4). Or am I misinterpreting something here ...</p>
|
<p>You'll find more answers in my <a href="https://stackoverflow.com/questions/91791/grep-and-sed-equivalent-for-xml-command-line-processing" title="Grep and Sed Equivalent for XML">previous question</a>. <a href="http://xmlstar.sourceforge.net/" rel="nofollow noreferrer" title="XMLStarlet tool collection">xmlstar</a> seems to be the most popular answer.</p>
|
<p>NAnt, the .NET cousin of Ant, has <a href="http://nant.sourceforge.net/release/latest/help/tasks/xmlpeek.html" rel="nofollow noreferrer">XmlPeek</a> and <a href="http://nant.sourceforge.net/release/latest/help/tasks/xmlpoke.html" rel="nofollow noreferrer">XmlPoke</a> tasks that I've used to very good effect in editing WCF configuration files which are quite complex. If you can find similar tasks for Ant, then you might have a winner.</p>
<p>Alternatively, another approach might be to have a "template" version of the configuration file that contains %placeholders% suitable for replacing with one of the more classic text processing tools.</p>
<p>A thought - Ant has the idea of a <a href="http://ant.apache.org/manual/Types/filterchain.html" rel="nofollow noreferrer">filter chain</a>, which can be used to transform a file while copying - NAnt has the same concept and I've recently used that to good effect configuring deployment files.</p>
| 40,883
|
<p>I'm playing with Java for the first time and need to be able to replace some words in a template. example template - </p>
<p>"Dear PUT_THEIR_NAME_HERE,</p>
<p>I'm contacting you ..... bla bla bla</p>
<p>Regards,</p>
<p>PUT_COMPANY_NAME_HERE"</p>
<p>What's the simplest way (preferably using the standard library) to make a copy of this template file and add the correct words at the correct place then save it to the file system? I have to do many such simple templates so a way that can be easily replicated would be nice.</p>
<p>I'm also accessing Java through JavaScript using Rhino, not sure if this makes any difference or not.</p>
<p>Regards,</p>
<p>Chris</p>
|
<p>You're looking for java.text.MessageFormat:</p>
<p>Here are some examples of usage (from JavaDoc):</p>
<pre><code> Object[] arguments = {
new Integer(7),
new Date(System.currentTimeMillis()),
"a disturbance in the Force"
};
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
arguments);
output: At 12:30 PM on Jul 3, 2053, there was a disturbance
in the Force on planet 7.
</code></pre>
|
<p>Well, the simplest way would be to read the file into a string, do a replaceAll (once for each word you want to replace) and then write the result out to a new file. This isn't the most efficient approach but it works quite well for simple tasks.</p>
| 41,775
|
<p>I've long used cygwin's nm command for all my .lib symbol debugging needs, but recently I thought about referring to it in a SO answer and realized that most Windows developers don't have cygwin installed.</p>
<p>So what is the Microsoft equivalent to nm, i.e., what command will list the symbols exported by a .lib file, the undefined symbols in the .lib, and so forth?</p>
<p>For the curious, a sample nm man page is <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?nm" rel="noreferrer">here</a>.</p>
|
<p>Try dumpbin.exe.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/c1h23y6c(v=vs.120).aspx" rel="noreferrer">MSDN dumpbin.exe reference</a>.</p>
|
<ol>
<li><p>Run <code>vcvarsall.bat</code> which might present in your installed path of Microsoft Visual Studio. This sets environmental variable required for <code>dumpbin.exe</code>.</p>
<p><code>D:>"D:\Program Files (x86)\Microsoft Visual Studio 10.0\vcvarsall.bat" x86</code></p>
</li>
<li><p>Then use <code>dumpbin.exe</code>. For example <code>dumpbin.exe /ALL <bin_file></code> gives all symbols.</p>
</li>
</ol>
| 49,105
|
<p>I want to add the selected item from the <code>TreeView</code> to the <code>ListBox</code> control using <code>DataBinding</code> (If it can work with <code>DataBinding</code>). </p>
<pre><code><TreeView HorizontalAlignment="Left"
Margin="30,32,0,83"
Name="treeView1"
Width="133" >
</TreeView>
<ListBox VerticalAlignment="Top"
Margin="208,36,93,0"
Name="listBox1"
Height="196" >
</ListBox>
</code></pre>
<p><code>TreeView</code> is populated from the code behind page with some dummy data. </p>
|
<p>You can bind to an element using ElementName, so if you wanted to bind the selected tree item to the ItemsSource of a ListBox:</p>
<pre><code>ItemsSource="{Binding SelectedItem, ElementName=treeView1}"
</code></pre>
|
<p>I'm pretty sure it is possible, since WPF is really flexible with data binding, but I haven't done that specific scenario yet.</p>
<p>I've been following a <a href="http://blogs.msdn.com/wpfsdk/archive/2006/10/19/wpf-basic-data-binding-faq.aspx" rel="nofollow noreferrer">WPF Databinding FAQ</a> from the MSDN blogs as of late and it provides a lot of insights that might help.</p>
| 7,806
|
<p>Does anyone know where to find an explanation to the warnings in VS 2005 Code Analyses tool. I would like some documentation, explaining why it creates the warnings it does and what course of action one should take.</p>
|
<p>You should be able to right click the warnings it gives you in the Error List and view Error Help, right from within Visual Studio. There's also a <a href="http://msdn.microsoft.com/en-us/library/ee1hzekz(VS.80).aspx" rel="nofollow noreferrer">section of MSDN articles</a>, if you'd prefer.</p>
|
<p>I'm not sure which codeanalysis tool you are referring to.</p>
<p>If you mean FxCop, look here: <a href="http://msdn.microsoft.com/en-us/library/bb429379(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb429379(VS.80).aspx</a></p>
<p>If you mean StyleCop, see the download here: <a href="http://code.msdn.microsoft.com/sourceanalysis/Release/ProjectReleases.aspx?ReleaseId=1425" rel="nofollow noreferrer">http://code.msdn.microsoft.com/sourceanalysis/Release/ProjectReleases.aspx?ReleaseId=1425</a></p>
| 15,001
|
<p>I am using VMWare tools for Ubuntu Hardy, but for some reason <code>vmware-install.pl</code> finds fault with my LINUX headers. The error message says that the "address space size" doesn't match.</p>
<p>To try and remediate, I have resorted to <code>vmware-any-any-update117</code>, and am now getting the following error instead:</p>
<pre><code>In file included from include/asm/page.h:3,
from /tmp/vmware-config0/vmmon-only/common/hostKernel.h:56,
from /tmp/vmware-config0/vmmon-only/common/task.c:30:
include/asm/page_32.h: In function βpte_t native_make_pte(long unsigned int)β:
include/asm/page_32.h:112: error: expected primary-expression before β)β token
include/asm/page_32.h:112: error: expected β;β before β{β token
include/asm/page_32.h:112: error: expected primary-expression before β.β token
include/asm/page_32.h:112: error: expected `;' before β}β token
</code></pre>
<p>Can anyone help me make some sense of this, please?</p>
|
<p>This error ofter occurs because incompatibility of VMWare Tools Version and recent Kernels (You can test it using older Kernels). Sometimes you can fix some thing with patches all over the internet, but I prefer to downgrade my kernel or don't using latest distribution's version in VMWare. It can be really annoying. Another problem you may have is with your mouse pointer in X Windows, like if it was a inch to left or below than it really shows.</p>
<p>About vmware-any-any-update117, it's a patch to VMWare running under linux, usually Workstation version. It won't have effect in Tools. </p>
|
<p>I've heard a lot of good things about VirtualBox from Sun. If you get fed up with VMWare, it's worth a look.</p>
| 5,118
|
<p>I need to do a union of two tables using NHibernate and HQL. I have found very little help online, and I want to know if it is possible and if so how?</p>
|
<p>Found my answer:</p>
<p><a href="http://www.hibernate.org/117.html#A21" rel="nofollow noreferrer">http://www.hibernate.org/117.html#A21</a></p>
<p>It doesn't currently support union or intersect.</p>
|
<p>I don't believe HQL supports unions, but you can write your own record transformer and author the sql by hand.</p>
| 30,686
|
<p>I have a situation where I am using wpf data binding and validation using the ExceptionValidationRule.</p>
<p>Another part of the solution invovles collapsing some panels and showing others.</p>
<p>If a validation exception is set - i.e. the UI is showing a red border around the UI element with the validation problem, and the containing panel is collapsed, the red border is still displayed. This is clearly not meant to be? Is there a workaround for this? Anyone know if this is by design?</p>
<p>Minimal code example provided (not my actual code, but replicates the problem). Create a new WpfApplication (I called mine WpfDataBindingProblem).</p>
<p>The xaml for window1 is as follows:</p>
<pre><code><Window x:Class="WpfDataBindingProblem.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel Margin="5">
<StackPanel Name="panel1" Visibility="Visible" Margin="5">
<TextBox Name="DataBoundTextBox">
<Binding Path="TextValue">
<Binding.ValidationRules>
<ExceptionValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox>
</StackPanel>
<StackPanel Name="panel2" Visibility="Collapsed" Margin="5">
<TextBlock>
The quick brown fox jumps over the lazy dog.
</TextBlock>
</StackPanel>
<Button Click="Button_Click" Margin="5">
Toggle panels
</Button>
</StackPanel>
</Window>
</code></pre>
<p>The code for window1 is as follows:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfDataBindingProblem {
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
this.DataContext = new MyClass("default");
}
private void Button_Click(object sender, RoutedEventArgs e) {
panel1.Visibility = panel1.Visibility == Visibility.Collapsed ?
Visibility.Visible : Visibility.Collapsed;
panel2.Visibility = panel2.Visibility == Visibility.Collapsed ?
Visibility.Visible : Visibility.Collapsed;
}
}
public class MyClass : INotifyPropertyChanged {
private string mTextValue;
public MyClass(string defaultText) {
TextValue = defaultText;
}
public string TextValue {
get {
return mTextValue;
}
set {
mTextValue = value;
if (string.IsNullOrEmpty(mTextValue)) {
throw new ApplicationException("Text value cannot be empty");
}
OnPropertyChanged(new PropertyChangedEventArgs("TextValue"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
if (this.PropertyChanged != null) {
this.PropertyChanged(this, e);
}
}
}
}
</code></pre>
<p>To reproduce the problem, run the application. Delete the <strong>default</strong> text from the textbox and tab off - red rectangle is shown indicating a validation problem. Click the button. Panel containing control with red rectangle is hidden and another panel is shown, but the red rectangle remains. Aargh!</p>
<p>All help much appreciated.</p>
<p>PS apologies for long question title!</p>
|
<p>If I remember correctly, this is a known issue. We re-templated textbox to include the following:</p>
<pre><code><Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<ControlTemplate.Resources>
<BooleanToVisibilityConverter x:Key="converter" />
</ControlTemplate.Resources>
<DockPanel LastChildFill="True">
<Border
BorderThickness="1"
BorderBrush="Red"
Visibility="{Binding ElementName=placeholder, Mode=OneWay, Path=AdornedElement.IsVisible, Converter={StaticResource converter}}">
<AdornedElementPlaceholder x:Name="placeholder" />
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</code></pre>
|
<p>I have an answer to the problem myself which is to change my button click event which changes the visibility of the panels. This would change to something like this:</p>
<pre><code>private void Button_Click(object sender, RoutedEventArgs e) {
if (panel1.Visibility == Visibility.Collapsed) {
panel1.Visibility = Visibility.Visible;
DataBoundTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
panel2.Visibility = Visibility.Collapsed;
}
else {
panel1.Visibility = Visibility.Collapsed;
DataBoundTextBox.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
panel2.Visibility = Visibility.Visible;
}
}
</code></pre>
<p>The <strong>UpdateSource()</strong> and <strong>UpdateTarget()</strong> have the effect of reapplying and removing the red rectangle, but this seems like an ugly hack. Surely the wpf framework should be hiding the red rectangle for me when the containing panel is collapsed. Any cleaner fix that doesn't require me to fiddle with the binding expression gets my vote.</p>
<p>Thanks,</p>
<p>Sam</p>
| 41,585
|
<p>I have some simple .doc files I made in Word 2007 where I changed the text color and used highlights to compare some similar texts. What I'd like to do is change any instances of green text or gray highlighting to different respective colors for each.</p>
<p>I'm sure there is a simple way to do this with VBA but any other sort of answers are also welcome.</p>
<p>EDIT: While I do appreciate answers, one that allows me to keep the .doc files as .docs is preferred.</p>
|
<p>This is not from 2007, but the idea should suit. This example changes any current highlight to the new default highlight (wdBrightGreen) and any green text to red.</p>
<pre><code>Sub ChangeColor
Options.DefaultHighlightColorIndex = wdBrightGreen
Selection.Find.ClearFormatting
Selection.Find.Highlight = True
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
Selection.Find.Execute Replace:=wdReplaceAll
Selection.Find.ClearFormatting
Selection.Find.Font.Color = wdColorBrightGreen
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Font.Color = wdColorRed
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
</code></pre>
|
<p>This should work for your purpose:</p>
<pre><code>Sub RehiliteAll()
Const YOUR_REQUIRED_COLOR_IDX As Integer = 6 'RED'
Dim doc As Range
Set doc = ActiveDocument.Range
With doc.Find
.ClearFormatting 'resets default search options'
.Highlight = True
.Wrap = wdFindStop
While .Execute
If doc.HighlightColorIndex = YOUR_REQUIRED_COLOR_IDX Then
doc.Select
MsgBox doc.HighlightColorIndex
'Do stuff here'
End If
'doc has been reassigned to the matching'
'range; we do this so word keeps searching'
'forward'
doc.Collapse wdCollapseEnd
Wend
End With
Set doc = Nothing
End Sub
'I am closing comment quotes so that SO formatting'
'does not get messed up too much.'
</code></pre>
| 28,453
|
<p>Has anyone seen this error before?</p>
<p>An error occurred creating the configuration section handler for cachingConfiguration: Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\WorkingDir\Projects\ReportCentral\ReportCentral\bin\Debug\ReportCentral.vshost.exe.config line 5)</p>
<p>I am using Ent Lib 4.0. I changed my App Traget Framework from 2.0 to 3.5. </p>
<p>Edit ~ </p>
<p>I have the following in the bin</p>
<p>Caching.dll
Common.dll
ObjectBuilder2.dll</p>
<p>Edit ~ "Solution"</p>
<p>This was the deal, when referencing dlls in the C:\EntLib4Src\bin, they are signed and could only be configured by the EntLibConfig.exe found in that same folder and not the one from "Start>Programs>Microsoft Patterns...>Ent Wasn't that tricky? </p>
|
<p>That means it can't find the file. So you either need to put it into the GAC or the bin folder so that the assembly can be loaded.</p>
|
<p>This was the deal, when referencing dlls in the C:\EntLib4Src\bin, they are signed and could only be configured by the EntLibConfig.exe found in that same folder and not the one from "Start>Programs>Microsoft Patterns...>Ent Wasn't that tricky?</p>
| 22,833
|
<p>One of the tenants of DDD is to not allow your objects to enter an invalid state. To me this means there shouldn't be a public parameterless constructor because that's going to be an object in an invalid state 99% of the time. </p>
<p>Is this a good way to move forward? It becomes a huge PITA when you just want to new-up a class real quick.</p>
|
<p>Good question. I have DDD nazi friends who say parameterless constructors are the devil. I agree with that to a certain extent, but I also feel it depends on the class's purpose.</p>
|
<p>It all depends on who calls the constructor. If only your factories do, then there isn't really a problem, because your factory methods become the "domain-side" constructors and the real constructors are an implementation detail.</p>
| 39,850
|
<p>I'm writing a C# wrapper for a third-party native library, which we have as a DLL. I would like to be able to distribute a single DLL for the new assembly. Is it possible for me to embed the win32 DLL in my .NET DLL, and still make calls into it using P/Invoke? If so, how?</p>
|
<p>I've never done it but I know of an opensource project that does this. They embed the native SQLite3 code into the managed SQLite assembly using their own tool called <a href="http://www.koushikdutta.com/2008/09/day-6-mergebin-combine-your-unmanaged.html" rel="nofollow noreferrer">mergebin</a>.</p>
<p>Go and take a look at the <a href="http://sqlite.phxsoftware.com/" rel="nofollow noreferrer">SQLite project for .NET by PHX</a> and grab the source and you can see how it's done.</p>
|
<p>I don't think you can do it directly, but it's possible to extract it at runtime to some temporary location and make call to that copy.</p>
| 48,051
|
<p>I'm attempting to utilize <a href="http://en.wikipedia.org/wiki/VBScript" rel="nofollow noreferrer">VBScript</a> to connect pull the <code>physicalDeliveryOfficeName</code> attribute in <a href="http://en.wikipedia.org/wiki/Active_Directory" rel="nofollow noreferrer">Active Directory</a> by providing the email address. </p>
<p>I know how to do it with a common name like the following:</p>
<pre><code>Set MyUser = GetObject ("LDAP://cn=" & uname & ",ou=" & strname & ",DC=bobdom,DC=net")
</code></pre>
<p>However only the email address is available. How to do this? I've even tried </p>
<pre><code>Set MyUser = GetObject ("LDAP://mail=" & uname & ",ou=" & strname & ",DC=bobdom,DC=net")
</code></pre>
<p>and that doesn't work. </p>
|
<p>I ended up writing the following: </p>
<pre><code>Function getOffice (strname, uname)
strEmail = uname
WScript.Echo "email: " & strEmail
Dim objRoot : Set objRoot = GetObject("LDAP://RootDSE")
Dim objDomain : Set objDomain = GetObject("LDAP://" & objRoot.Get("defaultNamingContext"))
Dim cn : Set cn = CreateObject("ADODB.Connection")
Dim cmd : Set cmd = CreateObject("ADODB.Command")
cn.Provider = "ADsDSOObject"
cn.Open "Active Directory Provider"
Set cmd.ActiveConnection = cn
cmd.CommandText = "SELECT physicalDeliveryOfficeName FROM '" & objDomain.ADsPath & "' WHERE mail='" & strEmail & "'"
cmd.Properties("Page Size") = 1
cmd.Properties("Timeout") = 300
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Dim objRS : Set objRS = cmd.Execute
If IsNull(objRS.Fields(0)) = TRUE Then
getOffice = "BLANK"
Else
getOffice = objRS.Fields(0)
WScript.Echo getOffice
End If
Set objRS = Nothing
Set cmd = Nothing
Set cn = Nothing
Set objDomain = Nothing
Set objRoot = Nothing
End Function
</code></pre>
|
<p>If using an <a href="http://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol" rel="nofollow noreferrer">LDAP</a> query (not sure if you need the server name in there in your case):</p>
<pre><code><LDAP://SERVERNAME/DC=bobdom,DC=net>;(&(objectClass=user)(mail=mike.spencer@kenblanchard.com));
</code></pre>
<p>Trying it out in my own environment, it looks like this (with a couple things genericized):</p>
<pre><code><LDAP://SERVERNAME/DC=bobdom,DC=net>;(&(mail=email@company.com));name,mail,member,description,memberOf,userParameters,userAccountControl,whenCreated,CN;subTreeCount=1
</code></pre>
<p>And the whole batch looks like this (in ASP; if done in a .vbs file you'll need to change the <code>Server.CreateObject</code> to just <code>CreateObject</code>... I think).</p>
<pre><code>Set oCon = Server.CreateObject("ADODB.Connection")
oCon.Provider = "ADsDSOObject"
oCon.Open "ADProvider", "ADUsername", "ADPassword"
Set oCmd = Server.CreateObject("ADODB.Command")
Set oCmd.ActiveConnection = oCon
sQuery = "<LDAP://SERVERNAME/DC=bobdom,DC=net>;(&(mail=email@company.com));name,distinguishedName,physicalDeliveryOfficeName;subTreeCount=1>"
oCmd.CommandText = sQuery
Set ADRecordSet = oCmd.Execute
</code></pre>
<p>You may need to fiddle with <code>subTreeCount</code>.</p>
| 35,797
|
<p>Kinda long title, but anyways...</p>
<p>I've been looking at these examples, specifically on the parts on writing and reading the size of the message to the byte streams<br>
<a href="http://doc.trolltech.com/4.4/network-fortuneclient-client-cpp.html" rel="nofollow noreferrer">http://doc.trolltech.com/4.4/network-fortuneclient-client-cpp.html</a><br>
<a href="http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html" rel="nofollow noreferrer">http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html</a></p>
<p>But I can't seem to figure it out in C#.</p>
<pre><code>StreamWriter writer = new StreamWriter(tcpClient.GetStream());
writer.Write(data.Length + data);
</code></pre>
<p>This doesn't work very well at all. Could someone give me a nudge in the right direction?</p>
|
<p>Generally you would send the length first. Both ends should agree on what a length looks like - for example, you might be happy to use fixed 4-byte length prefix as binary:</p>
<pre><code> byte[] data = ...
int len = data.Length;
byte[] prefix = Bitconverter.GetBytes(len);
stream.Write(prefix, 0, prefix.Length); // fixed 4 bytes
stream.Write(data, 0, data.Length);
</code></pre>
<p>Obviously the caller needs to do the same - i.e. read the first 4 bytes to get the length. For reading, the receiver should take care not to read too much data. One way is with a limiting stream - for example, <a href="http://code.google.com/p/protobuf-net/source/browse/trunk/protobuf-net/SubStream.cs" rel="nofollow noreferrer">this class</a> can be used to get a Stream that won't read too much.</p>
<p>If you don't want the overhead of always sending 4 bytes, then some more interesting encodings are possible - for example, using the msb as a continuation block.</p>
<p>For info, <a href="http://code.google.com/p/protobuf-net/" rel="nofollow noreferrer">protobuf-net</a> is a binary serializer designed around Google's "protocol buffers" message-based format. It handles a lot of the details for you, and might be of interest if you don't want to spend lots of time writing serialization code. There are examples for sockets in the QuickStart project, <a href="http://code.google.com/p/protobuf-net/source/browse/trunk/QuickStart/3%20Sockets.cs" rel="nofollow noreferrer">for example here</a></p>
|
<p>When you say, "This doesn't work very well at all", I'd be curious about specifically what doesn't work. Are they .NET applications on both ends of the socket? If so, ignore this answer. If not, then could the problem be the byte ordering of the integer? A little endian vs big endian issue? This thread here discusses it:</p>
<p><a href="http://bytes.com/forum/thread225649.html" rel="nofollow noreferrer">http://bytes.com/forum/thread225649.html</a></p>
<p><a href="http://books.google.com/books?id=2zT5b2BS1OUC&pg=PA64&lpg=PA64&dq=c%23+sockets+integers+byte+ordering&source=web&ots=_ISzZZ6HHT&sig=tUHdNT0NGv0uxusmHG9YjFw6j9k&hl=en&sa=X&oi=book_result&resnum=2&ct=result" rel="nofollow noreferrer">http://books.google.com/books?id=2zT5b2BS1OUC&pg=PA64&lpg=PA64&dq=c%23+sockets+integers+byte+ordering&source=web&ots=_ISzZZ6HHT&sig=tUHdNT0NGv0uxusmHG9YjFw6j9k&hl=en&sa=X&oi=book_result&resnum=2&ct=result</a></p>
<p>Another problem if both ends aren't .NET could be that the other end expects ANSI strings whereas you are sending Unicode.</p>
| 24,948
|
<p>Would this be right??</p>
<ol>
<li><p>Black Box</p>
<p>1.1 Functional</p>
<pre><code> 1.1.1 Equivalence
1.1.2 BVA
1.1.3 Use case
1.1.4 Regression
1.1.5 UAT
</code></pre>
<p>1.2 Non Functional</p>
<pre><code> 1.2.1 Testing the System Design
</code></pre></li>
<li><p>White box</p>
<p>2.1. Functional</p>
<pre><code> 2.1.1 Unit
2.1.2 Integration
2.1.3 System
</code></pre></li>
</ol>
<p><strong>Do the above fall under the right categories?</strong></p>
<p>The reason I ask this is because as a part of a report I was trying to come up with a good reference that categorised Test Techniques well. This is what my analysis and research from various sources gave me. And I hope this is helpful for someone else who might be doing the same research, but if its incorrect it should be updated.</p>
|
<p>You might also consider the case when several programs depending one on another are developed simultaneously. You have then to take into account the <strong><em>applicative architecture</em></strong> which groups all those applications into several <em>functional domains</em></p>
<p>So, for instance, a financial application having to process a large number of data would be <em>one</em> functional domain, in which you would have to develop a:</p>
<ul>
<li>dispatcher module in order to process those data on several computers</li>
<li>GUI in order to see what is going on</li>
<li>launcher in order to initiate the right connections retrieve the correct data and format them</li>
<li>and so on</li>
</ul>
<p>But that would only be <em>one</em> functional domain, as others would have to be developed in order to <em>exploit the results</em> of your programs (for instance, a "referential domain" would be there to store those results into various databases, and offer a communication bus for other programs to access them: that would be a second functional domain).</p>
<p>So I would add to your tests the following categories:</p>
<ul>
<li><strong>Assembly testing</strong>: when you test within your own functional domain (on an assembly server when you deploy the different applications of your domain, with a set of testing data)</li>
<li><strong>Integration testing</strong>: when you test <strong><em>all the applications from all the functional domains</em></strong>, which is also called <strong><em>front-to-end testing</em></strong>.</li>
</ul>
<p>Note: "integration testing" is not the same as "continuous integration testing", which basically can process the black and white tests you describe, for <strong><em>one</em></strong> program, on a very regular basis.</p>
<p>The tests I am referring to are executed a few times a week by an:</p>
<ul>
<li>"<em>Project Operational Architecture</em>" team of your domain for assembly tests: usually some developers of your team which set up an assembly server, check if the data are up-to-date and deploy the various program you are in charge to develop.</li>
<li>"<em>Production Operational Architectural</em>" team, in charge of setting a "production-like" environment and who is the only one able to really <em>test</em> the all chain of application from font to back.</li>
</ul>
<p>Note: an "Operation Architecture" team has the role to "make operational an execution environment", meaning to have:</p>
<ul>
<li>the right logistic team contacts in order to have the right servers and networks, </li>
<li>the right application teams contacts in order to know about the various start/stop application processes and deployment procedures of <em>all</em> the application of your system!</li>
</ul>
<p>In short: your categories are for <em>one program</em>, but when you are developing an IS (Information System), you are forced to acknowledge the fact that you are not talking about "<em>one</em> exe developed by <em>one</em> team deployed on <em>one</em> production machine"... and then, welcome to an all new world of testing ;)</p>
|
<p>I think that your categorisation is a good first step.</p>
<p>Separation between black box and white box (some prefer glass box) testing focuses on whether you have access only to the specification or more (design, source code).</p>
<p>I would add a second separation between functional and structural testing, which focuses on whether you want to consider what the software does (functional) or how it does it (structural).</p>
<p>A third separation deals with how you generate test inputs, deterministically or statistically (with a deliberate distribution and not randomly). Either way, your focus is on what coverage you target.</p>
<p>Finally a well known separation is between different levels of software cycle: unit testing, integration, system, acceptance, ...</p>
| 23,559
|
<p>I am using ActiveState Perl 5.6 on a Windows 2003 Server, and am having some memory leak issues. Are there any good tools (or even bad tools which would give a clue) which I would be able to use to help find them.</p>
|
<p>All perl program memory leaks will either be an XS holding onto a reference, or a circular data structure. <a href="http://search.cpan.org/dist/Devel-Cycle/" rel="noreferrer">Devel::Cycle</a> is a great tool for finding circular references, if you know what structures are likely to contain the loops. <a href="http://search.cpan.org/dist/Devel-Peek/" rel="noreferrer">Devel::Peek</a> can be used to find objects with a higher-than-expected reference count.</p>
<p>If you don't know where else to look, <a href="http://search.cpan.org/dist/Devel-LeakTrace-Fast/" rel="noreferrer">Devel::LeakTrace::Fast</a> could be a good first place, but you'll need a perl built for debugging.</p>
<p>If you suspect the leak is inside XS-space, it's much harder, and <a href="http://valgrind.org/" rel="noreferrer">Valgrind</a> will probably be your best bet. <a href="http://search.cpan.org/dist/Test-Valgrind/" rel="noreferrer">Test::Valgrind</a> may help you lower the amount of code you need to search, but this won't work on Windows, so you'd have to port (at least the leaky portion) to Linux in order to do this.</p>
|
<p>Since it's not been mentioned yet, <a href="https://metacpan.org/module/Devel::Size" rel="nofollow">Devel::Size</a> will report the size of a data structure. There's no other information given and the rules it uses to determine the 'boundary' of your data structure are opaque. For simple structures this isn't a problem.</p>
<p><a href="https://metacpan.org/module/Devel::SizeMe" rel="nofollow">Devel::SizeMe</a> is a hobby project of mine that aims to resolve the problems of Devel::Size and enable visualization of the <em>entire</em> memory usage of a perl interpreter. See <a href="http://blog.timbunce.org/tag/sizeme/" rel="nofollow">my blog</a> for extra information, including links to screencasts and videos. One of my goals is to enable detection and visualization of leaks, but that's still a way off yet.</p>
<p>Updates:</p>
<p>In addition to the other comments, you may find my <a href="http://www.slideshare.net/Tim.Bunce/perl-memory-use-lpw2013" rel="nofollow">Perl Memory Use talk</a> at LPW2013 useful. I'd recommend watching <a href="https://archive.org/details/Perl-Memory-Profiling-LPW2013" rel="nofollow">the screencast</a> as it explains the slides and has some cute visuals and some Q&A at the end.</p>
<p>I'd also suggest looking at Paul Evans <a href="https://metacpan.org/pod/Devel::MAT" rel="nofollow">Devel::MAT</a> module which I mention in the talk.</p>
| 37,747
|
<p>I'm trying to produce just the day number in a WPF text block, without leading zeroes and without extra space padding (which throws off the layout). The first produces the day number with a space, the second produces the entire date. According to the <a href="http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx" rel="nofollow noreferrer">docs</a>, 'd' should produce the day (1-31).</p>
<pre><code>string.Format("{0:d }", DateTime.Today);
string.Format("{0:d}", DateTime.Today);
</code></pre>
<p>UPDATE:Adding % is indeed the trick. Appropriate docs <a href="http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers" rel="nofollow noreferrer">here</a>.</p>
|
<p>See <a href="http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx" rel="nofollow noreferrer">here</a></p>
<blockquote>
<p>d, %d</p>
<p>The day of the month. Single-digit days do not have a leading zero. The application specifies "%d" if the format pattern is not combined with other format patterns.</p>
</blockquote>
<p>Otherwise d is interpreted as:</p>
<blockquote>
<p>d - 'ShortDatePattern'</p>
</blockquote>
<p>PS. For messing around with format strings, using <a href="http://www.linqpad.net/" rel="nofollow noreferrer">LinqPad</a> is invaluable.</p>
|
<p>The <code>{0:d}</code> format uses the patterns defined in the <a href="http://msdn.microsoft.com/en-us/library/az4se3k1.aspx" rel="nofollow noreferrer">Standard Date and Time Format Strings document of MSDN</a>. 'd' translates to the short date pattern, 'D' to the long date pattern, and so on and so forth.</p>
<p>The format that you want appears to be the <a href="http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx" rel="nofollow noreferrer">Custom Date and Time Format Modifiers</a>, which work when there is no matching specified format (e.g., 'd ' including the space) or when you use ToString().</p>
<p>You could use the following code instead:</p>
<pre><code>string.Format("{0}", DateTime.Today.ToString("d ", CultureInfo.InvariantCulture));
</code></pre>
| 19,976
|
<p>I'm currently monitoring a large network with Hobbit and have been tasked with lowering the amount of false (or at least irrelevant) alarms. At the top of my list are the tests "http" and "conn", initiated by bbtest-net. This command checks ping, ssh, etc, and if for instance a ping times out, it immediately sets the status to red. One minute later, the bbretest command kicks in, checks all the newly reddened hosts, and finds it to be green again. This happens <strong>all the time</strong>, and it clutters up my log. </p>
<p>Is there any way for me to make Hobbit report a red status AFTER bbretest has been run the first time? </p>
|
<p>First, this is a programming site so you won't get many answers.</p>
<p>But.... but ...</p>
<p>If your server times out, isn't that a problem?</p>
<p>Sounds to me like Hobbit does the job it is designed for: Telling you that you have something that needs your attention.</p>
<p>Fix the timeout problem, and your log should be fine.</p>
|
<p>You can use:</p>
<pre><code><ip> <hostname> # noconn
</code></pre>
<p>In bb-hosts for a server that doesn't respond to ping. Then test its aliveness through a service. </p>
| 38,302
|
<p>If so, how do you deal with things that just don't "feel" right such as:</p>
<ul>
<li>not writing unit tests</li>
<li>not having a continuous build</li>
<li>not refactoring</li>
<li>not having a team coding standard</li>
<li>not pair programming</li>
<li>not doing iterations</li>
<li>no daily standups</li>
<li>no retrospectives</li>
</ul>
<p>Now, some agile organizations do leave out some of these practices, but most successful ones incorporate most of them.</p>
<p>What do you do to deal with the seeming chaos of the traditional development processes?</p>
|
<p>Actually, I'm a Waterfall developer in an Agile organization. </p>
<p>Things that don't "feel" right to me include:</p>
<ul>
<li>Starting work on a project with barely any idea what it should do.</li>
<li>Documenting the processes, but not the products; being unable to get information without having to go talk to someone. All I should need is a Requirements document, a Design document (which I may write myself), and Google.</li>
<li>Spending more time in meetings than coding.</li>
<li>Spending more time coding at home than at work.</li>
<li>Having no idea when the project will be done.</li>
<li>PM's being useful in any way.</li>
<li>Having a meeting to prepare for a meeting to prepare for a meeting where somebody else logs onto a server and copies a file; thus spending six hours on a process that takes six minutes</li>
<li>Multiple checkouts</li>
<li>Knowing how something should flow, but not having actual requirements.</li>
<li>Developers' unique skill sets are downplayed or outright ignored as they make the developer non-interchangeable.</li>
<li>When there are no stories remaining... nothing to do... just kinda sit there... Could be adding a new feature; may not be needed but the time isn't being wasted... </li>
<li>Every six months when I change contracts, I have to adapt to a new coding standard? By the time I get used to it, I'm already looking for my next contract.</li>
</ul>
|
<p>Firstly, Agile methodologies emphasize on these practices but they have not introduced them. They have been there in software development process well before Agile came in. So simply saying that if you are not using Scrum/XP/RUP then you are not following these practices is plain wrong. If you are a professional software development organization, these practices will exist in one form or other. </p>
<p>Secondly, whether you are an agile developer in a Waterfall organization or vice-versa, you can not do much, at-least not effectively or significantly. What development 'culture' the organization has is a function of the commitment and focus of the management and executive. If that does not exist, you can do your 'bit' but you will lose out in the end. That is the reason Agile fails in many organizations when they transition to it, because they are unwilling to make the cultural change. </p>
| 29,199
|
<p>How do get the startup path ( system.windows.forms.application.StartupPath ) of my exe without adding a reference to system.windows.forms?</p>
|
<p>You could try</p>
<pre><code>System.AppDomain.CurrentDomain.BaseDirectory
</code></pre>
<p>which would work for most cases. </p>
|
<p>EDIT: @KiwiBastard's answer is the correct method:</p>
<pre><code>System.AppDomain.CurrentDomain.BaseDirectory
</code></pre>
<hr>
<p>Add a reference to <code>System.Reflection</code> and use</p>
<pre><code>Assembly.GetExecutingAssembly().Location
</code></pre>
<p>EDIT: Depending where you intend getting the startup path, this might be more appropriate:</p>
<pre><code>Assembly.GetEntryAssembly().Location
</code></pre>
| 38,534
|
<p>I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise...</p>
<p>is there a way to simplify a c++ integration function like this:</p>
<pre><code>// Integral Function
double integrate(double a, double b, double (*f)(double))
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0 ; n <= 100; ++n)
{
double x = a + n*(b-a)/100.0;
sum += (*f)(x) * (b-a)/101.0;
}
return sum;
}
</code></pre>
<p>by using c# and lambda expressions?</p>
|
<p>What about this:</p>
<pre><code>public double Integrate(double a,double b, Func<double, double> f)
{
double sum = 0.0;
for (int n = 0; n <= 100; ++n)
{
double x = a + n * (b - a) / 100.0;
sum += f(x) * (b - a) / 101.0;
}
return sum;
}
</code></pre>
<p>Test:</p>
<pre><code> Func<double, double> fun = x => Math.Pow(x,2);
double result = Integrate(0, 10, fun);
</code></pre>
|
<p>The real power comes, as stated, when calling it. For example, in C#</p>
<pre><code> static double Integrate(double a, double b, Func<double, double> func)
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0 ; n <= 100; ++n)
{
double x = a + n*(b-a)/100.0;
sum += func(x) * (b - a) / 101.0;
}
return sum;
}
</code></pre>
<p>Then:</p>
<pre><code> double value = Integrate(1,2,x=>x*x); // yields 2.335
// expect C+(x^3)/3, i.e. 8/3-1/3=7/3=2.33...
</code></pre>
| 36,676
|
<p>In C# if I want to convert a double (1.71472) to an int then I get the answer 2. If I do this in Java using intValue() method, I get 1 as the answer.</p>
<p>Does Java round down on conversions?</p>
<p>Why do the Java API docs have such scant information about their classes i.e. </p>
<blockquote>
<p>Returns the value of the specified
number as an int. This may involve
rounding or truncation.</p>
</blockquote>
<p>A bit more info about the rounding would have been helpful!</p>
|
<p>Java rounds toward zero when narrowing from a floating point to an integer type—and so does C#, when you use the casting conversion. It's <code>Convert.ToInt32</code> that rounds:</p>
<pre><code>double d = 1.71472;
int x = (int) d; // x = 1
int y = Convert.ToInt32(d); // y = 2
</code></pre>
<p>Details can be found in the <a href="http://java.sun.com/docs/books/jls/third_edition/html/conversions.html" rel="nofollow noreferrer">Java Language Specification</a>. Note that while the documentation cited in <code>Number</code> leaves options open for subclasses, the documentation on the concrete boxing types, like <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Double.html" rel="nofollow noreferrer"><code>Double</code>,</a> is explicit about the implementation: </p>
<blockquote>
<p>Returns the value of this Double as an
int (by casting to type int).</p>
</blockquote>
<p>When using <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html" rel="nofollow noreferrer"><code>BigDecimal</code></a>, you can specify one of eight different rounding policies.</p>
|
<p>Jon Skeet is correct, but something else to watch for is that .NET uses <a href="http://blogs.msdn.com/ericlippert/archive/2003/09/26/bankers-rounding.aspx" rel="nofollow noreferrer">Banker's Rounding</a> as its rounding algorithm. When you're halfway between round towards the even integer.</p>
| 38,456
|
<p>Does anyone have a good technique (or tutorial) to implement rulers within a C# Windows Forms application? I want to display an image while showing rulers that indicate your mouse position to allow a more accurate positioning of the cursor. Just like the image below:</p>
<p><img src="https://i.stack.imgur.com/QfIIi.png" alt="Ruler depicting where the cursor is located."></p>
<p>I tried using splitter controls to hold the tick marks but I don't know how to make the top-left the gray blank area. Any advice? Thanks.</p>
|
<p>I would build a custom control to do this in both X and Y location and use two controls.</p>
<p>The control would have to override <code>Paint()</code> and use GDI methods to display the tick marks, it would then capture mouse events and update locations appropriately.</p>
|
<p>This is the best article I've found and used on the matter:
<a href="http://www.codeproject.com/KB/miscctrl/ruler.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/miscctrl/ruler.aspx</a></p>
| 18,076
|
<p>I recently asked this question: <a href="https://stackoverflow.com/questions/368521/api-design-expose-xml-or-objects" title="Expose XML or Objects">Expose XML or Objects</a> - thanks all for the responses.</p>
<p>One point to clarify.</p>
<ul>
<li>The API will always be accessed remotely (i.e. as a service), most probably via webservices or WCF.</li>
</ul>
<p>I agree that in theory a strongly typed API exposing objects as the inputs/outputs is the <em>right</em> way to go. However, I feel that there is still an argument to be made for exposing XML. As I see it the reasons for using XML are:</p>
<ol>
<li>The business rules can be written by business analysts in Schematron.</li>
<li>The interface is weakly typed, but as soon as it is called the data can be validated against data and business rules.</li>
<li>The service's implementation will be simpler. There won't be any need to create an domain object model.</li>
<li>The XML schema is already defined (we have a data dictionary of schema).</li>
<li><p>Using web services technology means that an XML based API will not need to change as new car 'types' are added, e.g. </p>
<pre><code>void AddNewCar( string newCarXml )
string[] GetCars( /* some query conditions */ )
</code></pre>
<p>If we used an object based API then adding a new type would require a new query method defining the possible derived types that could be returned (see <a href="https://stackoverflow.com/questions/374253/extend-webservice-without-impacting-existing-clients-returning-derived-types-fr" title="extending webservices">extending web services</a>). Updating the web service like this would require this services and <em>all</em> existing clients to be rebuilt and redeployed.</p></li>
</ol>
<p>What does an object based API give us? A strongly typed declarative interface. It does not provide any more abstraction than XML (XML is itself an abstraction). What does the object based API cost? It costs an entire set of domain objects which will need business rules and data validation.</p>
<p>So, what is my question? Give me an un-defeatble, unarguable reason why I should go with objects.</p>
|
<ul>
<li>Objects can perform better (thinking binary serialization here). </li>
<li>Objects can have stronger simple type validations. </li>
<li>Objects allow you to put the validation and business rules closer to the data structure definition. </li>
<li>Objects by their nature allow you to write simpler business rules and validation, since much of that is embedded in the object definition itself.</li>
<li><strong>Objects can also define behaviors.</strong></li>
<li>.Net makes it simple to turn Objects into Xml and back again via serialization, giving objects most of the same benefits as xml.</li>
</ul>
|
<p>If you're looking for an argument in favour of XML (not that I am particularly in favour of XML) are:</p>
<ul>
<li><p>Exposing the XML and providing an XSD is self explanatory when it comes to data. You can pass off all the data in that form, it's self documenting and can be validated reasonably simply.</p></li>
<li><p>I can write a bunch of safe code against my database or code model and I can release the data in a self contained and safe manner to other business units that requires minimal further documentation or explanation.</p></li>
<li><p>It's so easy to read that often you can read it as easily as you could read the documentation or code comments.</p></li>
</ul>
<p>The arguments against it however, go on and on...to name the worst offenders:</p>
<ul>
<li>Overly verbose.</li>
<li>Huge network overhead.</li>
<li>Require an understanding of an extra technology, perhaps needlessly(?).</li>
<li>The more complex you make something, the greater opportunity for errors there are.</li>
</ul>
| 49,149
|
<p>Below is what I'm trying to achieve. The problem is "errors" is not defined. If I remove my match logic, the errors are displayed on the web page. Is there anyway of evaluating the text the error contains?</p>
<pre><code><logic:messagesPresent>
<tr>
<td class="errorcicon"><img src="images/icon_caution.gif" width="18" height="18" alt="Caution" /></td>
<td></td>
<td colspan="4"><html:errors /></td>
</tr>
</logic:messagesPresent>
<logic:match name="errors" property="text" value="Service Start date is required" >
<% pageContext.setAttribute("NOORIGIONALSERVICEDATE", "-1");%>
</logic:match>
</code></pre>
|
<pre><code>$(this).contents('img.expander')
</code></pre>
<p>This is what you want. It will select all of the nodes that are children of your list. In your case, all of your images are nested inside of the list element, so this will filter out only what you want.</p>
|
<p>Have you tried the .siblings() method?</p>
<pre><code>$(this).siblings('img.expander').attr('src','img/content/info-close.gif');
</code></pre>
| 34,323
|
<p>In a one-to-many relationship what's the best way to handle data so it's flexible enough for the user to save the slave data before he saves the master table data.</p>
<ul>
<li>reserving the row ID of the master so the I can save de slave data with the reserved master id</li>
<li>save slave data in a temporary table so that when we save the master data we can "import" the data in the temporary table</li>
<li>other??</li>
</ul>
<p>Example in a ticket/upload multiple files form where the users has the possibility to upload the files before sendind the ticket information:</p>
<p>Master table
PK
ticket description</p>
<p>Slave table
PK
Master_FK
File</p>
|
<p>Are your id's autogenerated? </p>
<p>You have several choices all with possible problems.</p>
<p>First don't define a FK relationship. Now how do you account for records in a partial state and those who never get married up to the real record? And how do you intend to marry up the records when the main record is inserted?</p>
<p>Insert a record into the master table first that where everything is blank except the id. This makes enforcing all required fields default to the user application, which I'm not wild about from a data integrity standpoint.</p>
<p>Third and most complex but probably safest - use 3 tables. Create the master record in a table that only contains the master recordid and return that to your application on opening the form to create a new record. Create a pk/fk relationship to both the orginal master table and the foreign key table. Remove the autogeneration of the id from the orginal master table and insert the id from the new master table instead when you insert the record. Insert the new master table id when you insert records to the orginal FK table as well. At least this way, you can continue to have all the required fields marked as required in the database but the relationship is between the new table and the other table not the original table and the other table. This won't affect querying (as long as you have proper indexing), but will make things more complicated if you delete records as you could leave some hanging out if you aren't careful. Also you would have to consider if there are other processes (such as data imports from another source) which might be inserting records to the main table which would have to be adjusted as the id would no longer be autogenerated..</p>
|
<p>Why can't you create the master row and flag it as incomplete?</p>
| 44,401
|
<p>So, what is the best way to prevent an XSRF attack for a GAE application? Imagine the following:</p>
<ol>
<li>Anyone can see a user's public object, and the db.Model id is used in the request to figure out which object to show. Malicious user now has the id.</li>
<li>Malicious user creates their own object and checks out the delete form. They now know how to delete an object with a certain id.</li>
<li>Malicious user gets innocent user to submit a delete request for that user's object.</li>
</ol>
<p>What steps can I add to prevent #3? Note that when I say ID, I am using the actual ID part of the key. One idea I had was to use the full key value in delete requests, but would that prevent a malicious user from being able to figure this out? As far as I know, the key is some combination of the model class type, the app id, and the object instance id, so they could probably derive the key from the id if they wanted to.</p>
<p>Any other ideas? Jeff wrote <a href="http://www.codinghorror.com/blog/archives/001171.html" rel="noreferrer">a post about this</a>, and suggested a couple methods - a hidden form value that would change on each request, and a cookie value written via js to the form. I won't want to exclude non-javascript users, so the cookie solution is no good - for the hidden form value, I would have to do a datastore write on every request that displayed a deletable object - not an ideal situation for a scalable app!</p>
<p>Any other ideas out there?</p>
|
<p>When you generate the page that lets the user delete an object, generate a random token and include it in a hidden form field. Also set a HTTP-only cookie with that value. When you receive a delete request, check that the random token from the form and the value from the cookie match.</p>
<p>Your random token shouldn't just be a random number. You should encrypt the combination of a random number and the user's identity, to make it difficult for attackers to forge their own tokens. You should also use different encryption keys for the value stored in the form and the value stored in the cookie, so if one of the tokens does leak, it is still difficult for an attacker to forge the other token.</p>
<p>This approach verifies that the delete request originates from your form, by the presence of the security token in the form; and doesn't require writing to the datastore.</p>
<p>This approach is still vulnerable to cross-site scripting attacks, where an attacker could retrieve the hidden value from the form or submit the form, so thoroughly test your site for cross-site scripting vulnerabilities. This approach is also vulnerable to <a href="http://en.wikipedia.org/wiki/Clickjacking" rel="noreferrer" title="clickjacking">"clickjacking"</a> attacks.</p>
|
<p>In server's response displaying the form create a magic hash (based on client ip + date/time + random salt, whatever). Put it into a cookie and store somewhere on the server. During submit action handling check the cookie hash against the database entry.</p>
<p>If there's no such hash or it's different, reject the submission.</p>
<p>After successful submit you can remove the hash entry, change it's state to submitted - whatever suits you.</p>
<p>That method should protect you in many cases, but surely is still not 100% bulletproof.</p>
<p>Do a search for articles on CSRF, maybe you'll find some good answers on this <a href="http://stackoverflow.com">Stack Overflow</a> thing. ;)</p>
<p>Don't do any referrer checks or client ip validations - it's too error-prone (the referrer information might be cleared by the user agent, a proxy or by user's preferences) and client's IP might change between the form creation and submission - don't punish the user for dynamic IP address allocation.</p>
| 24,184
|
<p>Jeff has previously blogged about <a href="https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/">using the cache</a> to perform "out of band" processing on his websites, however I was wondering what other techniques people are using to process these sorts of tasks?</p>
|
<p>Years ago, I saw Rob Howard describe a way to use an HttpModule to process tasks in the background. It doesn't seem as slick as using the Cache, but it might be better for certain circumstances.</p>
<p><strong><a href="http://blogs.telerik.com/KevinBabcock/Posts/08-07-24/Using_an_HttpModule_to_Run_a_Background_Service.aspx" rel="noreferrer">This blog post</a></strong> has the details, and there are many others that capture the same information if you look around.</p>
|
<p>Scheduled tasks, or cron jobs.</p>
| 6,441
|
<p>We created a tool which converts a language called P2, a language similar to assembly which I think exists only in Japan, to C#. There are at least a hundred modules written in P2 and we want to verify if the conversion to C# is right? How can we test this?</p>
|
<p>You don't test the converter, you test the final code. </p>
<p>If the code doesn't compile, clearly your converter is failing. If the code compiles and your functionality tests fail, then you can tweak the code so that it passes the test. If you are fairly successful you should see that you only need to fix the modules that actually fail.</p>
<p>Goodluck!</p>
|
<p>Short of a formal mathematical proof (which I imagine would be difficult), the proof of the pudding is in the unit tests. You have to find a way to wrap the converted C# snippets, compile the and run them under a similar environment, then compare the output against the original. Unless you're rigorous in your testing, there's no way you can be confident of the result.</p>
| 3,808
|
<p>I have written a game that uses GLUT, OpenGL and FMOD. The problem is that the binary won't run, unless Visual Studio 2008 is installed on the computer.</p>
<p>Why is this?</p>
|
<p>Most likely you're linking with DLL versions of the C/C++ runtime. Go to project properties -> C++ -> Code Generation, and set Runtime Library to <em>not</em> be one of "DLL" kinds.</p>
<p>Alternatively, you can link to DLL runtimes, but then you have to redistribute the runtime with your application.</p>
<p>MSDN has more information on various aspects of C++ application deployment: <a href="http://msdn.microsoft.com/en-us/library/zebw5zk9.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/zebw5zk9.aspx</a></p>
<p>Also, <a href="http://www.dependencywalker.com/" rel="noreferrer">Dependency Walker (depends.exe)</a> will show what libraries your executable depends on. It ships with some versions of Visual Studio as well.</p>
|
<p>Do you have dependencies on debug libraries?</p>
| 45,411
|
<p>I'm wondering if it is possible to add methods in main program to an existing class defined in header file.
For example:
There is <code>class CFun</code> defined in file <code>CFun.hpp</code>, but in our <code>party.cpp</code> we want to add a method <code>void hello() {cout << "hello" << endl;};</code>without editing <code>CFun.hpp</code></p>
<p>Obviously (unfortunately) construction:</p>
<pre><code>#include "CFun.hpp"
class CFun
{
public:
void hello() {cout << "hello" << endl;};
};
</code></pre>
<p>doesn't work returning an error <code>Multiple declaration for 'CFun'</code></p>
<p>Is it possible to make it work without class inheritance?</p>
|
<p>No, but you could add a method that takes a reference/pointer to a CFun class - you just won't have access to private data:</p>
<pre><code>void Hello(CFun &fun)
{
cout << "hello" << endl;
}
</code></pre>
<p>This is probably the best you'll be able to do. As pointed out by litb - this function has to be in the same namespace as CFun. Fortunately, namespaces, unlike classes, can be added to in multiple places.</p>
|
<p>Not to my knowledge. Although, you could do some kind of jury-rigging and make a namespace-y solution.</p>
| 30,898
|
<p>I am writing a DDL script to drop a number of tables but need to identify all dependencies for those tables first. Those dependencies include foreign key constraints, stored procedures, views, etc. Preferably, I want to programmatically script out dropping those dependencies using the system tables/views before dropping the dependent table.</p>
|
<p>This is extremely messy to write from scratch. Have you considered a 3rd party tool like
<a href="http://www.red-gate.com/products/SQL_Dependency_Tracker/index.htm" rel="nofollow noreferrer" title="Red-Gate SQL Dependency Tracker">Red-Gate SQL Dependency Tracker</a>?</p>
|
<p>You can use the sp_depends stored procedure to do this:</p>
<p><code>USE AdventureWorks
GO
EXEC sp_depends @objname = N'Sales.Customer' ;</code></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms189487(SQL.90).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms189487(SQL.90).aspx</a></p>
| 7,648
|
<p>I have a library that reads/writes to a USB-device using CreateFile() API. The device happens to implement the HID-device profile, such that it's compatible with Microsoft's HID class driver.</p>
<p>Some other application installed on the system is opening the device in read/write mode with no share mode. Which prevents my library (and anything that consumes it) from working with the device. I suppose that's the rub with being an HID-compatible device -- other driver software (mice, controllers, PHIDGETS, etc) can be uncooperative. </p>
<p>Anyway, the device file path is of the form: </p>
<pre>
1: "\\?\hid#hpqremhiddevice&col01#5&21ff20e7&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".
2: "\\?\hid#vid_045e&pid_0023#7&34aa9ece&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".
3: "\?\hid#vid_056a&pid_00b0&col01#6&5b05f29&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".
</pre>
<p>And I'm trying to open it using code, like:</p>
<pre><code>// First, open it with minimum permissions, this device may not be ours.
// we'll re-open it later in read/write
hid_device_ref = CreateFile(
device_path, GENERIC_READ,
0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
</code></pre>
<p>I've considered a tool like FileMon or Process Monitor from SysInternals. But I can't seem to get it to report usage on device file handles like the one listed above.</p>
|
<p>Have you tried the tool called <a href="http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx" rel="nofollow noreferrer">handle</a> from sysinternals?</p>
<p>Anyway, neither windows does this (display the name of the application that locked the device): when you try to eject an USB device, Windows just says that the device is currently in use and cannot be remove right now.</p>
|
<p>Cool - I'll try those options, as they're probably better defaults given my intentions. Unfortunately, I know my device is there and I'll eventually need read/write access later on (once I inspect the descriptors and have verifed it is infact my device).</p>
<p>Which means that my real goal IS to know what's using it, so I can inform the customer/user: "Hey man, 'iexplore.exe' is currently using your SuperWidget device. You'll have to close that down in order to use SuperWidget application." (if not at the application-level, then at least at the phone support level.)</p>
<p>I forgot to mention that the windows error reported by GetLastError() is:</p>
<blockquote>
<p>0x20. The process cannot access the file because it is being used by another process.</p>
</blockquote>
<p>(So your sharing alternatives will probably get the file open, assuming no FILE_SHARE_NONE on behalf of the other process).</p>
<p>[edit]</p>
<blockquote>
<p>Yeah, it's painful alright. I have seen mice and keyboards get locked by whatever Windows uses to read from them. I've also seen a lot of people have trouble inside a VM like Paralells on OS X, where the HID class driver has the device open exclusively preventing the VM from using standard USB requests.</p>
<p>I've seen some code that recreates what <em>ProcessMonitor</em> does. Maybe SysInternals is just electing to ignore device handles, but the same method (or a slight variation) can be employed here to determine the PID.</p>
<p><strong>Mike</strong></p>
</blockquote>
| 4,319
|
<p><a href="http://tinlizzie.org/ometa/" rel="noreferrer">Ometa</a> is "a new object-oriented language for pattern matching." I've encountered pattern matching in languages like Oz tools to parse grammars like Lexx/Yacc or Pyparsing before. Despite looking at example code, reading discussions, and talking to a friend, I still am not able to get a real understanding of what makes Ometa special (or at least, why some people think it is). Any explanation?</p>
|
<p>Also, most important to me, the Squeak port of Ometa allows for left-recursive rules.</p>
<p>From its PEG heritage it gets backtracking and unlimited lookahead. Memoization of previous parse results allows for linear parse times (nearly all the time (*)).</p>
<p>Higher-order productions allow one to easily refactor a grammar.</p>
<p><a href="http://www.vpri.org/pdf/tr2007002_packrat.pdf" rel="noreferrer">This paper</a> - Packrat Parsers Can Support Left Recursion - explains the left recursive properties.</p>
<p>(*) Section 5 of the paper explains that one can suffer superlinear parse times, but this problem doesn't manifest in practical grammars.</p>
|
<p>It's a metalanguage, from what I can tell. You can create new language constructs, and create DSLs; but the most compelling thing is that you can subclass from existing parsers to extend a language. That's what I can remember about it, anyway.</p>
<p>I found this to be interesting: <a href="http://www.moserware.com/2008/06/ometa-who-what-when-where-why.html" rel="noreferrer">http://www.moserware.com/2008/06/ometa-who-what-when-where-why.html</a></p>
| 13,194
|
<p>A VBScript cannot edit the registry by default on Vista. How do I get elevation (even if the user has to do something when they run the script) so that the script can edit the registry?</p>
<p>The error is:</p>
<pre><code>---------------------------
Windows Script Host
---------------------------
Script: blah blah blah.vbs
Line: 6
Char: 1
Error: Permission denied
Code: 800A0046
Source: Microsoft VBScript runtime error
---------------------------
OK
---------------------------
</code></pre>
|
<p>My understanding was that you could edit HKCU as a normal user, but the others were restricted. I could be wrong. Regardless, there are a couple of example <a href="http://www.winhelponline.com/articles/185/1/VBScripts-and-UAC-elevation.html" rel="nofollow noreferrer">here</a> to do what you want to do.</p>
|
<p>To make it work with native VBScript, you will most likely need a code signing certificate and sign your script with that. More info is in that thread at <a href="http://www.tek-tips.com/viewthread.cfm?qid=1475626" rel="nofollow noreferrer">tek-tips.com</a>.</p>
<p>You could try to write the intended changes to a .reg file and call <code>regedit.exe</code> with that. Maybe this triggers UAC. Did not tried that, though. I have no Vista around right now. :-)</p>
| 31,139
|
<p>Is there an similar property like System.getProperty("java.home") that will return the JDK directory instead of the JRE directory? I've looked <a href="https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperties()" rel="nofollow noreferrer">https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperties()</a> and there doesn't seem to be anything for the JDK.</p>
|
<p>One route would be to set a system environment variable like "JAVA_HOME" and use that. </p>
<p>It may not be the best solution, but it would work, and this is what other apps which require JDK rather than JRE (like CruiseControl) require you to do when you set them up.</p>
|
<p>An alternative is to define the path to the JDK via a properties file. This can be in addition to the System environment variable to allow an override. </p>
<p>Depending on your use case, you could put this properties file in the home directory or package with your app.</p>
| 46,084
|
<p>Ok, I've seen a few posts that <em>mention</em> a few other posts about not using SP wikis because they suck.</p>
<p>Since we are looking at doing our wiki <em>in</em> SP, I need to know why we shouldn't do it for a group of 6 automation-developers to document the steps in various automated processes and the changes that have to be made from time to time.</p>
|
<p>The default wiki included with Sharepoint doesn't support common wiki features well at all. There is no way to edit a single section of a page, and no way to link directly to a particular section on another page. The backend is in HTML so you lose the ability to edit in plaintext using simple syntax. The diff feature can't span multiple versions. Poor cross browser support of WYSIWYG editing. No way to auto-insert a table of contents...</p>
<p>There are, however, other wiki add-ins for Sharepoint which I can't categorically dismiss, for instance <a href="http://www.atlassian.com/software/confluence/" rel="nofollow noreferrer">Confluence</a> makes an <a href="http://www.atlassian.com/sharepoint/" rel="nofollow noreferrer">add-in for Sharepoint</a>. I haven't evaluated this software myself, and Confluence is somewhat expensive ($1,200 for 25 user license) although if you are already on Sharepoint I sense large corporate coffers :P. There also appear to be some free add-ins like <a href="http://www.codeplex.com/CKS/Wiki/View.aspx?title=Enhanced%20Wiki%20Edition&referringTitle=Home" rel="nofollow noreferrer">CKS Enhanced Wiki</a> but that appears to have a lot of the same problems mentioned above.</p>
|
<p>My company rolled out sharepoint recently, and I have to say my user experience was <strong><em>Very Bad</em></strong>. And I'm not just saying I was apprehensive to using it: I went in with an open mind and tried it, and many things just felt like they didn't really work right.</p>
<p>The reasons Luke mentioned more or less cover it. </p>
<p>Why wouldn't you consider using something else like <a href="http://www.screwturn.eu/Default.aspx?AspxAutoDetectCookieSupport=1" rel="nofollow noreferrer">Screwturn Wiki</a> which <a href="http://www.codinghorror.com/blog/archives/001098.html" rel="nofollow noreferrer">Jeff donated</a> to a short while ago? I haven't used Screwturn myself, but it is free and open source, and may be a faster lightweight solution for what you need.</p>
| 3,258
|
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey.
I will try to explain this with an example:</p>
<pre><code>class Project(models.Model):
name = models.CharField(max_length=100)
employees = models.ManyToManyField(Profile, limit_choices_to={'active': '1'})
class TimeWorked(models.Model):
project = models.ForeignKey(Project, limit_choices_to={'user': user})
hours = models.PositiveIntegerField()
</code></pre>
<p>Of course that code doesn't work because there is no 'user' object, but that was my idea and I was trying to send the object 'user' to the model to just limit the choices where the current user has projects, I don't want to see projects where I'm not in.</p>
<p>Thank you very much if you can help me or give me any advice, I don't want to you write all the app, just a tip how to deal with that. I have 2 days with this in my head and I can't figure it out :(</p>
<p><strong>UPDATE</strong>: The solution is here: <a href="http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/" rel="noreferrer">http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/</a> sending <code>request.user</code> to a model.</p>
|
<p>This limiting of choices to current user is a kind of validation that needs to happen dynamically in the request cycle, not in the static Model definition.</p>
<p>In other words: at the point where you are creating an <em>instance</em> of this model you will be in a View and at that point you will have access to the current user and can limit the choices.</p>
<p>Then you just need a custom ModelForm to pass in the request.user to, see the example here:
<a href="http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/" rel="noreferrer">http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/</a></p>
<pre><code>from datetime import datetime, timedelta
from django import forms
from mysite.models import Project, TimeWorked
class TimeWorkedForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(ProjectForm, self).__init__(*args, **kwargs)
self.fields['project'].queryset = Project.objects.filter(user=user)
class Meta:
model = TimeWorked
</code></pre>
<p>then in your view:</p>
<pre><code>def time_worked(request):
form = TimeWorkedForm(request.user, request.POST or None)
if form.is_valid():
obj = form.save()
# redirect somewhere
return render_to_response('time_worked.html', {'form': form})
</code></pre>
|
<p>Hmmm, I don't fully understand your question. But if you can't do it when you declare the model maybe you can achieve the same thing with overriding methods of the class of objects where you "send" the user object, maybe start with the constructor.</p>
| 19,350
|
<p>I'm a bit stuck on this. Basically I want to do something like the following SQL query in LINQ to SQL:</p>
<pre><code>SELECT f.*
FROM Foo f
WHERE f.FooId IN (
SELECT fb.FooId
FROM FooBar fb
WHERE fb.BarId = 1000
)
</code></pre>
<p>Any help would be gratefully received.</p>
|
<p>Have a look at <a href="http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql" rel="noreferrer">this article</a>. Basically, if you want to get the equivalent of IN, you need to construct an inner query first, and then use the Contains() method. Here's my attempt at translating:</p>
<pre><code>var innerQuery = from fb in FoorBar where fb.BarId = 1000 select fb.FooId;
var result = from f in Foo where innerQuery.Contains(f.FooId) select f;</code></pre>
|
<p>Try this</p>
<pre><code>var fooids = from fb in foobar where fb.BarId=1000 select fb.fooID
var ff = from f in foo where f.FooID = fooids select f
</code></pre>
| 7,438
|
<p>I've got two tables:</p>
<pre><code>TableA
------
ID,
Name
TableB
------
ID,
SomeColumn,
TableA_ID (FK for TableA)
</code></pre>
<p>The relationship is one row of <code>TableA</code> - many of <code>TableB</code>.</p>
<p>Now, I want to see a result like this:</p>
<pre><code>ID Name SomeColumn
1. ABC X, Y, Z (these are three different rows)
2. MNO R, S
</code></pre>
<p>This won't work (multiple results in a subquery):</p>
<pre><code>SELECT ID,
Name,
(SELECT SomeColumn FROM TableB WHERE F_ID=TableA.ID)
FROM TableA
</code></pre>
<p>This is a trivial problem if I do the processing on the client side. But this will mean I will have to run X queries on every page, where X is the number of results of <code>TableA</code>. </p>
<p>Note that I can't simply do a GROUP BY or something similar, as it will return multiple results for rows of <code>TableA</code>. </p>
<p>I'm not sure if a UDF, utilizing COALESCE or something similar might work?</p>
|
<h3>1. Create the UDF:</h3>
<pre><code>CREATE FUNCTION CombineValues
(
@FK_ID INT -- The foreign key from TableA which is used
-- to fetch corresponding records
)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @SomeColumnList VARCHAR(8000);
SELECT @SomeColumnList =
COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20))
FROM TableB C
WHERE C.FK_ID = @FK_ID;
RETURN
(
SELECT @SomeColumnList
)
END
</code></pre>
<h3>2. Use in subquery:</h3>
<pre><code>SELECT ID, Name, dbo.CombineValues(FK_ID) FROM TableA
</code></pre>
<h3>3. If you are using stored procedure you can do like this:</h3>
<pre><code>CREATE PROCEDURE GetCombinedValues
@FK_ID int
As
BEGIN
DECLARE @SomeColumnList VARCHAR(800)
SELECT @SomeColumnList =
COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20))
FROM TableB
WHERE FK_ID = @FK_ID
Select *, @SomeColumnList as SelectedIds
FROM
TableA
WHERE
FK_ID = @FK_ID
END
</code></pre>
|
<p>Solution below:</p>
<pre><code>SELECT GROUP_CONCAT(field_attr_best_weekday_value)as RAVI
FROM content_field_attr_best_weekday LEFT JOIN content_type_attraction
on content_field_attr_best_weekday.nid = content_type_attraction.nid
GROUP BY content_field_attr_best_weekday.nid
</code></pre>
<p>Use this, you also can change the Joins</p>
| 13,650
|
<p>I'm trying to write a simple routine where I pass it a URL and it goes and renders the content of the webresponse as a jpg. I found a solution somehwere in C# and ported it to vb.net, however when I run it, it throws an argumentexception "parameter is not valid" when trying to instantiate the image. Can someone take a look at the following code and let me know if I'm on the right track?</p>
<pre><code>Sub SaveUrl(ByVal aUrl As String)
Dim response As WebResponse
Dim remoteStream As Stream
Dim readStream As StreamReader
Dim request As WebRequest = WebRequest.Create(aUrl)
response = request.GetResponse
remoteStream = response.GetResponseStream
readStream = New StreamReader(remoteStream)
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(remoteStream)
img.Save(aUrl & ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
response.Close()
remoteStream.Close()
readStream.Close()
End Sub
</code></pre>
<p><strong>To Clarify:</strong> Yes, I know i need a LOT more code to accomplish what I want to do, which is to render/take a screen capture of a URL (html, images, all the markup, everything) and save it as a jpg thumbnail. </p>
<p>If you've used Google Chrome, you've seen the launch page that has thumbnails of all the sites you use frequently. Something like that.</p>
<p><strong>Update:</strong> Ok I've found commercial paid products to accomplish this, like <a href="http://www.websitesscreenshot.com/Index.html" rel="nofollow noreferrer">http://www.websitesscreenshot.com/Index.html</a> but no open source implementations. </p>
|
<p>What are you trying to do?</p>
<p>Are you trying convert a web page to JPEG? This will require a bit more code, as what your code is trying to do is to download an already existing image (such as a gif, png, or even another jpeg) and converts it to jpeg. You would need to have something render the HTML document, then you would need to capture an image of the rendered document, and then save that as a JPEG.</p>
|
<p>I know you're asking for VB, but here's some C# code that I use in a project of mine to capture local thumbnails from image URLs (asynchronously). I've tried to strip out all the project-specific stuff so it makes sense as a stand-alone example.</p>
<pre><code>var wc = new WebClient();
wc.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
wc.DownloadDataCompleted += wc_DownloadDataCompleted;
wc.DownloadDataAsync(imageProvider.Image, "yourFilenameHere");
</code></pre>
<p>And here's the wc_DownloadDataCompleted event handler:</p>
<pre><code>private void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
var filename = e.UserState.ToString();
using (var ms = new MemoryStream(e.Result))
{
var bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.DecodePixelWidth = 80; // _maxThumbnailWidth;
bi.EndInit();
var encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bi));
var filename = Path.Combine(_thumbFolder, filename);
try
{
using (var fs = new FileStream(filename, FileMode.Create))
{
encoder.Save(fs);
}
}
catch { }
}
}
}
</code></pre>
<p><strong>Edit</strong></p>
<p>I guess I should add that this was in a WPF application - hence the use of "BitmapImage" and "BitmapFrame" to decode the stream. So it may not help you. I'm gonna leave it here anyway.</p>
| 49,720
|
<p>We have a few SGI Onyx 350 and Orgin 350 systems running IRIX 6.5.x that we would like to install Subversion on. One of them will likely be used as a simple repository server running svnserve. The others will only need client installs.</p>
<p>The Subversion webpage has links to unofficial binaries for many *NIX systems, including HP-UX, Solaris, AIX, the BSDs and Linux distros. Unfortunately, there aren't any for IRIX. A Google search also comes up empty.</p>
<p>So, is there someplace on the web that publishes IRIX binaries for Subversion? </p>
<p>If not, does anyone have experience compiling SVN from source on such systems? How hard is it to track down all of the dependencies? Are there any caveats we should be aware of?</p>
|
<p>For a machine like yours, the source code build is probably the way to go(it's one of the advantages of having source). The dependencies aren't that bad. The dependencies are <a href="http://www.zlib.net/" rel="nofollow noreferrer">zlib</a>, the <a href="http://apr.apache.org" rel="nofollow noreferrer">Apache Portable Runtime</a> (and the apr-utils), <a href="http://www.webdav.org/neon/" rel="nofollow noreferrer">neon</a> (optional), and <a href="http://www.oracle.com/technology/software/products/berkeley-db/index.html" rel="nofollow noreferrer">BerkelyDB</a>(optional also).<br>
Get the Apache and neon, and berkelyDB stuff first.
then just ./configure --prefix=;make;make install</p>
|
<p>The guy that maintains <a href="http://www.futuretech.blinkenlights.nl/sgi.html" rel="nofollow noreferrer">This website</a> sells secondhand SGI gear. He sells them with CD's of contributed software. Maybe he can do something for you.</p>
<p>Also, <a href="http://www.nekochan.net/weblog/archives/irix-software/" rel="nofollow noreferrer">The SGI forum on nekochan.net</a> has postings of contributed software. You may be able to ask for something there.</p>
<p>Subversion is fairly pernickety about its dependencies (as you have probably already worked out). <a href="http://www.peregrinehw.com/downloads/subversion/INSTALL-rh7.3-last" rel="nofollow noreferrer">This link</a> gives some of the dependencies for installing on Redhat 7.3, which dates back to the early 2000's (I don't know what minor release of Irix you're using). You may find it to be a reasonable guide to the dependencies.</p>
| 36,165
|
<p>I wouldn't dare do anything complex in a database without transactions. There is nearly always a simple to use in-built command. But when you start working with other persistent data you just don't get this simple to use transaction support. Some example are</p>
<ul>
<li>file systems</li>
<li>web services (none that I've used)</li>
</ul>
<p>Even in non-persistent data it is often useful to undo a block of work, following an exception. None of the standard data structures you get with a language, support transactions.</p>
<p>What I would like to know is, why are databases the special case?</p>
<p>Are there any useful links to the topic of transactional behavior out-side of databases?</p>
|
<p>I must respectfully disagree: transactional systems are not automatically and exclusively database engines, quite the contrary...</p>
<p>I have implemented an application transaction mechanism (in .NET) that is distinct from a database transaction. It is actually rather easy (a few hours work including a unit test suite). It is completely written in C# with no dependencies on any database functionality or any other component. But first some context...</p>
<p>This non-database-transaction feature exists in several manifestations on the Java platform, such as with EJBs, ESBs, JMS, and often in association with BPM. Some of these manifestations use an underlying database, but not always and not out of necessity. Other platforms have comparable manifestations, such as MSMQ.</p>
<p>Most legacy version control systems do NOT implement ACID transaction semantics. As ddaa said, CVS does not but Subversion (its successor) does. Visual Source Safe does not. If you research Subversion, you can find comparison charts that make a point of this.</p>
<p>Now for the critical point, a database transaction or its equivalent does not guarantee safe business logic. Although I love Subversion, it is ironically a great example of this fact.</p>
<p>You can use Subversion religiously, along with an automated build script (one command that compiles, tests, and packages your application), and still commit a broken build to the source control repository. I have seen it repeatedly. Of course, it is even easier with non-ACID-transaction-based source control tools like VSS. But it is shocking to many people to learn that it is possible with tools like Subversion.</p>
<p>Allow me please to lay out the scenario. You and a coworker are developing an application, and using Subversion for the source control repository. Both of you are coding away and occasionally committing to the repository. You make a few changes, run a clean build (recompile all source files), and all the tests pass. So, you commit your changes and go home. Your coworker has been working on his own changes, so he also runs a clean build, sees all the tests pass, and commits to the repository. But, your coworker then updates from the repository, makes a few more changes, runs a clean build, and the build blows up in his face! He reverts his changes, updates from the repository again (just to be sure), and finds that a clean build still blows up! Your coworker spends the next couple of hours troubleshooting the build and the source, and eventually finds a change that you made before you left that is causing the build failure. He fires off a nasty email to you, and your mutual boss, complaining that you broke the build and then carelessly went home. You arrive in the morning to find your coworker and your boss waiting at your desk to cuss you out, and everyone else is watching! So you quickly run a clean build and show them that the build is not broke (all the tests pass, just like last night).</p>
<p>So, how is this possible? It is possible because each developer's workstation is not part of the ACID transaction; Subversion only guarantees the contents of the repository. When your coworker updated from the repository, his workstation contained a mixed copy of the contents of the repository (including your changes) and his own uncommitted changes. When your coworker ran a clean build on his workstation, he was invoking a business transaction that was NOT protected by ACID semantics. When he reverted his changes and performed an update, his workstation then matched the repository but the build was still broke. Why? Because your workstation was also part of a separate business transaction that also was NOT protected by ACID semantics, unlike your commit to the repository. Since you had not updated your workstation to match the repository before running your clean build, you were not actually building the source files as they existed in the repository. If you performed such an update, you would then find that the build also fails on your workstation.</p>
<p>Now I can expound on my initial point--transactions have scope/context that must be considered carefully. Just because you have an ACID transaction does not mean that your business logic is safe, UNLESS the scope/context of the ACID transaction and the business logic matches EXACTLY. If you are relying on some form of database ACID transaction, but you do ANYTHING in your business logic that is not covered by that database transaction, then you have a gap that can allow a comparable and catastrophic error. If you can force your business logic to exactly match your database transaction, then all is well. If not, then you probably need a separate business transaction. Depending on the nature of the unprotected logic, you may need to implement your own transaction mechanism.</p>
<p>So, messaging can be transactional, but the scope is merely the message. Regarding the example above, Subversion's context is only an individual commit to the repository. However, the business transaction is a clean build, which involves a much larger scope. This particular problem is usually solved by scripting a clean build together with a clean checkout, ideally using a continuous integration implementation (e.g., via CruiseControl or the like). On the developer workstations, it requires each developer to exercise the discipline to perform a full update (or even a clean checkout) before a clean build.</p>
<p>So, to recap, every transaction has a scope or context that limits its protection. Business transactions often incorporate logic that exceeds the scope of the transaction mechanisms (such as a database engine) that we commonly use. You might have to make up the difference. On rare occasion, it might even make sense to write your own transaction mechanism to do so.</p>
<p>I architected a rewrite of a critical business system for a modest ninety-person company. I found it necessary to implement such a mechanism, and I found the experience to be easy, worthwhile, and rewarding. I would do it again, perhaps a little more readily, but I would always question why I could not stick to just a database transaction.</p>
|
<p>I had the situation I needed to treat a filesystem and a database as one transactional unit.</p>
<p>In my case I only needed to download a set of files into the filesystem. I did it by creating random directories each time, putting the data there, and storing the directory name in a database table. Therefore all my database work, and the directory name in the database table (= filesystem work), could be done in one database transaction.</p>
<p><a href="http://www.databasesandlife.com/atomic-operations-over-filesystem-and-database/" rel="nofollow">http://www.databasesandlife.com/atomic-operations-over-filesystem-and-database/</a></p>
| 37,970
|
<p>There have been a few questions asked here about why you can't define static methods within interfaces, but none of them address a basic inconsistency: why can you define static fields and static inner types within an interface, but not static methods?</p>
<p>Static inner types perhaps aren't a fair comparison, since that's just syntactic sugar that generates a new class, but why fields but not methods?</p>
<p>An argument against static methods within interfaces is that it breaks the virtual table resolution strategy used by the JVM, but shouldn't that apply equally to static fields, i.e. the compiler can just inline it?</p>
<p>Consistency is what I desire, and Java should have either supported no statics of any form within an interface, or it should be consistent and allow them. </p>
|
<p>An <a href="http://docs.google.com/Doc?docid=dfkwr6vq%5F30dtg2z9d8&hl=en" rel="noreferrer">official proposal</a> has been made to allow static methods in interfaces in Java 7. This proposal is being made under <a href="http://blogs.oracle.com/darcy/entry/project_coin" rel="noreferrer">Project Coin</a>. </p>
<p>My personal opinion is that it's a great idea. There is no technical difficulty in implementation, and it's a very logical, reasonable thing to do. There are several proposals in Project Coin that I hope will <em>never</em> become part of the Java language, but this is one that could clean up a lot of APIs. For example, the <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List)" rel="noreferrer"><code>Collections</code> class has static methods</a> for manipulating any <code>List</code> implementation; those could be included in the <code>List</code> interface.</p>
<hr>
<p><em>Update:</em> In the <a href="http://javaposse.com/index.php?post_id=442910" rel="noreferrer">Java Posse Podcast #234,</a> Joe D'arcy mentioned the proposal briefly, saying that it was "complex" and probably would not make it in under Project Coin.</p>
<hr>
<p><em>Update:</em> While they didn't make it into Project Coin for Java 7, Java 8 does support <a href="http://hg.openjdk.java.net/lambda/lambda/langtools/rev/67030038d40b" rel="noreferrer">static functions in interfaces.</a></p>
|
<p>Only static final fields may be declared in an interface (much like methods, which are public even if you don't include the "public" keyword, static fields are "final" with or without the keyword).</p>
<p>These are only values, and will be copied literally wherever they are used at compile time, so you never actually "call" static fields at runtime. Having a static method would not have the same semantics, since it would involve calling an interface without an implementation, which Java does not allow.</p>
| 15,716
|
<p>What fonts do you use for programming, and for what language/IDE? I use <a href="http://www.microsoft.com/downloads/details.aspx?familyid=22e69ae4-7e40-4807-8a86-b3d36fab68d3&displaylang=en" rel="nofollow noreferrer" title="Consolas">Consolas</a> for all my Visual Studio work, any other recommendations?</p>
|
<p>Either Consolas <a href="http://www.microsoft.com/downloads/details.aspx?familyid=22e69ae4-7e40-4807-8a86-b3d36fab68d3&displaylang=en">(download)</a> or Andale Mono <a href="http://prdownloads.sourceforge.net/corefonts/andale32.exe?download">(download)</a>. I mostly use Andale Mono. I wrote an article about programming fonts <a href="http://www.deadprogrammer.com/the-programmers-font">a long time ago</a>, I think Consolas wasn't even out yet.</p>
<p><a href="http://www.deadprogrammer.com/photos/fonts.gif">http://www.deadprogrammer.com/photos/fonts.gif</a></p>
<p>I find that typing <code>Illegal1 = O0</code> is a good test of suitability.</p>
|
<p>Any sans-serif.</p>
| 2,672
|
<p>I'm storing all localizable strings in a <code>ResourceDictionary</code> (in <code>App.xaml</code>) and assign those via the <code>StaticResource</code> markup extension to <code>TextBlock.Text</code>, <code>Button.Content</code> etc.</p>
<p>In Beta 2 and RC0, <em>sometimes</em> parsing the XAML in <code>InitializeComponent()</code> will fail with an <code>AG_E_PARSER_BAD_PROPERTY_VALUE</code> on the line and position where I set the attribute value to the <code>StaticResource</code>.</p>
<p>It only happens sometimes: When restarting the app, it parses and displays without any problems. The same interface code works for days or weeks, then it happens again.</p>
<p>Any ideas?</p>
|
<p>Parser, at least in beta 2, didnt like whitespace...</p>
<p>For instance: </p>
<pre><code>Text="{StaticResource bleh}"
</code></pre>
<p>worked</p>
<p>however this:</p>
<pre><code>Text = "{StaticResource bleh}"
</code></pre>
<p>bombed</p>
|
<p>Basically it means bad xaml somewhere in the code you can see the Line number and Position and see something is wrong .. I got the same error in my xaml Once corrected everything seems working </p>
| 20,732
|
<p>I have a Windows Form project that I've just started. On the form I have a listbox that I'm loading with Products. When someone double clicks a Product, I want it to raise a ProductChanged event. Other things in my project will subscribe to this event and update things like other parts of the GUI when the Product changes. </p>
<p>My question is, where should the event be and who should raise it? Should the event be on the form and be raised by the listbox's double click handler? Or should I set it up where the event is in my Products class and the listbox calls a method on this class to let it know that the product has changed. And then the Product class will raise the event? Or should it be done another way?</p>
|
<p>The product changed is a UI event, it would make sense if its raised on the form, and the other UI elements suscribe to the event.</p>
|
<p>Depends on what your event signifies. If the intent is to notify subscribers that the Product object was modified, then it belongs to the Product class and should be fired by a code inside that class. If the intent is to notify that another Product object was selected, then it belongs to the view that manages the list of Products (your listbox/form).</p>
| 17,378
|
<p>I am making a small <strong>C#</strong> application and would like to extract a <strong>tag cloud</strong> from a simple plain text. Is there a function that could do that for me?</p>
|
<p>Building a tag cloud is, as I see it, a two part process:</p>
<p>First, you need to split and count your tokens. Depending on how the document is structured, as well as the language it is written in, this could be as easy as counting the space-separated words. However, this is a very naive approach, as words like the, of, a, etc... will have the biggest word-count and are not very useful as tags. I would suggest implementing some sort of word black list, in order to exclude the most common and meaningless tags. </p>
<p>Once you have the result in a (tag, count) way, you could use something similar to the following code:</p>
<p>(Searches is a list of SearchRecordEntity, SearchRecordEntity holds the tag and its count, SearchTagElement is a subclass of SearchRecordEntity that has the TagCategory attribute,and ProcessedTags is a List of SearchTagElements which holds the result)</p>
<pre><code>double max = Searches.Max(x => (double)x.Count);
List<SearchTagElement> processedTags = new List<SearchTagElement>();
foreach (SearchRecordEntity sd in Searches)
{
var element = new SearchTagElement();
double count = (double)sd.Count;
double percent = (count / max) * 100;
if (percent < 20)
{
element.TagCategory = "smallestTag";
}
else if (percent < 40)
{
element.TagCategory = "smallTag";
}
else if (percent < 60)
{
element.TagCategory = "mediumTag";
}
else if (percent < 80)
{
element.TagCategory = "largeTag";
}
else
{
element.TagCategory = "largestTag";
}
processedTags.Add(element);
}
</code></pre>
|
<p>The <a href="http://www.tansharp.com/tag-cloud.aspx" rel="nofollow">Zoomable TagCloud Generator</a> which extracts keywords from a given source (text file and other sources) and displays the TagCloud as Zooming User Interface (ZUI)</p>
| 46,218
|
<p>How to do svn update of multiple files located across different directories ? </p>
<p>For committing multiple files from different directories, we can put them all up in a text file and give that file as an argument to svn commit and it will happily commit all those files. But <b>update</b> ?</p>
<p><b>EDIT:</b> Mr. Fooz's answer is definitely an option whereby I can create a .bat or .sh file with all the svn updates. But I would like to know if there are any special arguments that svn provide that can be used instead of a file with loads of svn update commands in it. Please note that the file that is used by svn commit contains <i>only</i> the filenames and no svn commands. </p>
|
<p>Given that there are valid reasons for selectively updating from a repository when there are a lot of downstream changes available, my question would be whether you're trying to do this on a UNIX/Linux/etc. system or Windows. If Windows, I don't know how to do an equivalent of the following:</p>
<pre><code>svn update `cat list_of_files`
</code></pre>
<p>(There are corner-cases, similar to running "find ... | xargs cmd ...", where spaces or shell-sensitive characters in the file names could cause problems. You'll have to deal with those by properly escaping such problem-characters.)</p>
<p>If, for some frightening reason, your list of files is so astronomically-large that it breaks the shell command-line-length limit, you can do this instead:</p>
<pre><code>cat list_of_files | xargs svn update
</code></pre>
<p>Two things to keep in mind while using either of these:</p>
<ol>
<li>All file names will have to be either absolute, or relative to the point you're running the command from.</li>
<li>If one of the "files" in your list is actually a directory, <strong><em>all</em></strong> the files in that directory that have changes available will be updated.</li>
</ol>
|
<p>THe fact that you even want to do this suggests to me that you're perhaps not using subversion particularly sensibly.</p>
| 29,277
|
<p>I've got an ASP.NET 2.0 website that connects to a SQL database. I've upgraded the SQL server from 2000 to 2008 and since then, one page refuses to work. </p>
<p>I've worked out the problem is that the call to SqlDataReader.HasRows is returning false even though the dataset is not empty and removing the check allows the loop through reader.Read() to access the expected data. </p>
<pre><code> _connectionString = WebConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString;
SqlConnection connection = new SqlConnection(_connectionString);
SqlCommand command = new SqlCommand(searchtype, connection);
SqlParameter _parSeachTerm = new SqlParameter("@searchterm", SqlDbType.VarChar, 255);
_parSeachTerm.Value = searchterm;
command.Parameters.Add(_parSeachTerm);
command.CommandType = CommandType.StoredProcedure;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows) //this always returns false!?
{
while (reader.Read())
{...
</code></pre>
<p>Does anybody have any idea what's going on? There are similar code blocks on other pages where HasRows returns the correct value.</p>
<p>EDIT- Just to clarify, the stored procedure DOES return results which I have confirmed because the loop runs through fine if I remove the HasRows check. Changing just the name of the SQL server in the connection string to an identical database running on SQL 2000 makes the problem go away. I've checked that NOCOUNT is off, so what else could make HasRows return false when that's not the case??</p>
<p>EDIT2- Here's the SP</p>
<pre><code>CREATE PROCEDURE StaffEnquirySurnameSearch
@searchterm varchar(255)
AS
SELECT AD.Name, AD.Company, AD.telephoneNumber, AD.manager, CVS.Position, CVS.CompanyArea, CVS.Location, CVS.Title, AD.guid AS guid,
AD.firstname, AD.surname
FROM ADCVS AD
LEFT OUTER JOIN CVS ON
AD.Guid=CVS.Guid
WHERE AD.SurName LIKE @searchterm
ORDER BY AD.Surname, AD.Firstname
GO
</code></pre>
<p>Many thanks in advance.</p>
|
<p>Does the stored procedure work if you invoke it in directly, say in SSMS? I'd start by making sure that it does.</p>
|
<p>First, check the procedure as @tvanfosson says.
Second, the check for HasRows() is actually unnecessary in the code snippet. </p>
| 23,988
|
<p>When I debug locally in fire fox 2.0x many times my page won't have the styles added properly or the page will not completely render (the end is seemingly cut off). Sometimes it takes multiple refreshes or shift-refreshes to fix this. Is this a common issue or is it just me? Any solutions?</p>
<p>I want to add that this is happening in fire fox 3.x to me as well. I add my javascript to the pages dynamically and this might be part of the issue. This is when I am working locally with Visual Studio.</p>
<p>Update: This does happen in IE but it happens much more often in Fire Fox. The issue seems to be only javascript and CSS files not loading. For example I get jQuery is not defined, $ is not defined etc. I don't think I have local IIS to test this on but from the server it always works perfectly. Fire Bug shows all my css and javascript files to be requested and received.</p>
|
<p>This could be a <strong>problem with IPv6 and DNS</strong> of the Firefox browser. This issue is known to <em>slow down</em> Firefox on localhost:SOMEPORT. The effect would be that some external files won't load (css, js etc.) resulting in a partially rendered page.</p>
<p>You can solve this issue by simply deactivating IPv6 in Firefox:</p>
<ol>
<li>Insert <code>about:config</code> in the Firefox address bar</li>
<li>Set <code>network.dns.disableIPv6</code> to <code>true</code> or alternatively add <code>localhost</code> to <code>network.dns.ipv4OnlyDomains</code></li>
</ol>
<p>A different way to fix this issue, is to a remove the ipv6 address from your hosts file this way: open the file</p>
<pre><code>C:\Windows\System32\drivers\etc\hosts
</code></pre>
<p>(with administrator privileges) and remove (or comment out #):</p>
<pre><code> :: localhost
</code></pre>
|
<p>One thing to do would be to check the source of the page(s) in question. My guess would be that the local server that VS runs is not giving you the entire source of the page. One way to verify this would be to run exactly the same code in the debug environment, as well as from a "real" server like IIS 6. If the same behavior is seen on loading the page from both servers, as well as insuring that the full page source is being recieved by the browser(s), then it is a bug in Firefox and should be reported. This is especially true if other browsers, ie. IE, Chrome, Safari, Opera, render the page fully.</p>
| 22,261
|
<p>I'm trying to access the Reporting Services via Web Services in my Visual Studio 2008 Application. How/where can I find my WSDL? </p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/ms154052.aspx" rel="noreferrer">The following example shows the format of the URL to the Reporting Services management WSDL file:</a></p>
<p><a href="http://server/reportserver/ReportService2005.asmx?wsdl" rel="noreferrer">http://server/reportserver/ReportService2005.asmx?wsdl</a></p>
|
<p>See <a href="http://msdn.microsoft.com/en-us/library/ms169816.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms169816.aspx</a></p>
| 21,206
|
<p>I have the following unmanaged C++ code:</p>
<pre><code>MessageBox( NULL, strMessage, "Cool Product", MB_RETRYCANCEL | MB_ICONEXCLAMATION);
</code></pre>
<p>I want to disable the RETRY button for 10 seconds (for example), then enable it.</p>
<p>How can I do this?</p>
|
<p>Like <a href="https://stackoverflow.com/questions/176062/how-do-i-disable-and-then-enable-the-retry-button-in-a-messagebox-c#176082">@ffpf</a> says, you need to make your own dialog to do this, using MFC, ATL, raw Win32, etc.</p>
<p>Then create a timer that would enable and disable the button.</p>
|
<p>With the standard MessageBox call, you can't. You'd need to implement your own MessageBox in order to do this.</p>
| 21,210
|
<p>Is '' a valid piece of XML?
Can '' insert into oracle xblob column or XML column from MSSQL?</p>
|
<p>No. The <a href="http://www.w3.org/TR/REC-xml/#sec-well-formed" rel="noreferrer">spec</a> says a well-formed XML document satisfies:</p>
<pre><code>document ::= prolog element Misc*
</code></pre>
<p>where</p>
<pre><code>element ::= EmptyElemTag
| STag content ETag
</code></pre>
|
<p>It's not valid xml. Valid xml requires an xml declaration with encoding type and a root node. Whether or not Oracle or SQL Server will accept it anyway is something you can check for yourself.</p>
| 49,257
|
<p>Good morning,</p>
<p>I am the developer of a medium sized PDA application that will be used out on the streets. The PDA will contain some vaguely sensitive data (names and addresses, etc). The encryption on the mobile database is already handled, however if someone got hold of the PDA whilst it was logged in they could happily go through the data until the battery died or they closed the application and had to log in again.</p>
<p>When the users access the PDA application they need to enter their username and PIN number. Version 1 of this software had an event hooked into every button in the system so that when the button was pressed, it updated a variable called LastActionTime. A timer ran on the main form and if that LastActionTime was more than 10 minutes ago then the system would throw up the login form again until the previous user/admin logged back in again (just like the windows lockout screen).</p>
<p>This worked fine... in a sense... the problem with that is that it was only handling buttons and wasn't handling the other controls, like ListViews, PictureBoxes, etc.</p>
<p>Is there any good way of achieving this? For example, is there a way I could extend a Windows Form Class to handle every single event and update that variable accordingly? Or can I do something windows-esque that would handle every single mouse event on the form? </p>
<p>To be completely concise, what I want to achieve is that when the PDA screen/buttons have not been touched for 10 minutes, the PDA will know this and allow me to fire my lockout method.</p>
<p>Any thoughts, help and guidance would be much appreciated.</p>
<p><strong>Edit</strong>: I am using Compact Framework 2.0 on Windows Mobile 6.0, however the function needs to work on Windows Mobile 5.0 and above.</p>
|
<p>One possible solution is to rely on the PDA's entering power idle state. You can register a notification for this using OpenNETCF.WindowsCE.PowerManager.PowerIdle Event. In fact it is a good idea to take into account power management considerations. You can't expect your PDA to be in the same state all the time.</p>
<p>Another solution would be to monitor the inactive event of the input driver (See this <a href="http://msdn.microsoft.com/en-us/library/ms889826.aspx" rel="nofollow noreferrer">link</a>). However, this solution is very device specific.</p>
<p>Unfortunately there is no way in Windows CE to register a global mouse event hook.</p>
<p>The above were OS solutions. There is not an easy way to do it with extending Windows Form and Control classes. Probably you would need to extend all the controls you would be using. The easiest solution would be to implement the GetFocus method for all your controls and the form. You could reset your counter there.</p>
<p>By the way, in a desktop environment this can easily achieved with GetLastInputInfo.</p>
|
<p>Check this post out:</p>
<p><a href="http://social.msdn.microsoft.com/Forums/en-US/netfxcompact/thread/906b016d-f1ee-4b3e-b3df-1e3a6fea282a/" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/netfxcompact/thread/906b016d-f1ee-4b3e-b3df-1e3a6fea282a/</a> </p>
<p>I wrestled with the same problem, and ended up using Application.AddMessageFilter to get the appropriate results. That thread eventually contains a link to a sample project I wrote showing the inactivity timer working, including shutting down subdialogs if necessary to return to a main window screen.</p>
<p>David</p>
| 45,445
|
<p>What is exactly the function of Python's Global Interpreter Lock?
Do other languages that are compiled to bytecode employ a similar mechanism?</p>
|
<p>In general, for any thread safety problem you will need to protect your internal data structures with locks.
This can be done with various levels of granularity.</p>
<ul>
<li><p>You can use fine-grained locking, where every separate structure has its own lock.</p></li>
<li><p>You can use coarse-grained locking where one lock protects everything (the GIL approach).</p></li>
</ul>
<p>There are various pros and cons of each method. Fine-grained locking allows greater parallelism - two threads can
execute in parallel when they don't share any resources. However there is a much larger administrative overhead. For
every line of code, you may need to acquire and release several locks.</p>
<p>The coarse grained approach is the opposite. Two threads can't run at the same time, but an individual thread will run faster because its not doing so much bookkeeping. Ultimately it comes down to a tradeoff between single-threaded speed and parallelism.</p>
<p>There have been a few attempts to remove the GIL in python, but the extra overhead for single threaded machines was generally too large. Some cases can actually be slower even on multi-processor machines
due to lock contention. </p>
<blockquote>
<p>Do other languages that are compiled to bytecode employ a similar mechanism?</p>
</blockquote>
<p>It varies, and it probably shouldn't be considered a language property so much as an implementation property.
For instance, there are Python implementations such as Jython and IronPython which use the threading approach of their underlying VM, rather than a GIL approach. Additionally, the next version of Ruby looks to be moving <a href="http://www.infoq.com/news/2007/05/ruby-threading-futures" rel="noreferrer">towards</a> introducing a GIL.</p>
|
<p>Maybe <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=214235" rel="nofollow noreferrer">this</a> article by the BDFL will help.</p>
| 33,312
|
<p>I've got a C++ Win32 application that has a number of threads that might be busy doing IO (HTTP calls, etc) when the user wants to shutdown the application. Currently, I play nicely and wait for all the threads to end before returning from <code>main</code>. Sometimes, this takes longer than I would like and indeed, it seems kind of pointless to make the user wait when I could just exit. However, if I just go ahead and return from <code>main</code>, I'm likely to get crashes as destructors start getting called while there are still threads using the objects.</p>
<p>So, recognizing that in an ideal, platonic world of virtue, the best thing to do would be to wait for all the threads to exit and then shutdown cleanly, what is the next best real world solution? Simply making the threads exit faster may not be an option. The goal is to get the process dead as quickly as possible so that, for example, a new version can be installed over it. The only disk IO I'm doing is in a transactional db, so I'm not terribly concerned about pulling the plug on that.</p>
|
<p>Use overlapped IO so that you're always in control of the threads that are dealing with your I/O and can always stop them at any point; you either have them waiting on an IOCP and can post an application level shutdown code to it, OR you can wait on the event in your OVERLAPPED structure AND wait on your 'all threads please shutdown now' event as well.</p>
<p>In summary, avoid blocking calls that you can't cancel.</p>
<p>If you can't and you're stuck in a blocking socket call doing IO then you could always just close the socket from the thread that has decided that it's time to shut down and have the thread that's doing IO always check the 'shutdown now' event before retrying...</p>
|
<p>Instruct the user to unplug the computer. Short of that, you have to abandon your asynchronous activities to the wind. Or is that HWIND? I can never remember in C++. Of course, you could take the middle road and quickly note in a text file or reg key what action was abandoned so that the next time the program runs it can take up that action again automatically or ask the user if they want to do so. Depending on what data you lose when you abandon the asynch action, you may not be able to do that. If you're interacting with the user, you may want to consider a dialog or some UI interaction that explains why its taking so long.</p>
<p>Personally, I prefer the instruction to the user to just unplug the computer. :)</p>
| 25,652
|
<p>Let's say I have a line of text like this</p>
<pre><code>Small 0.0..20.0 0.00 1.49 25.71 41.05 12.31 0.00 80.56
</code></pre>
<p>I want to capture the last six numbers and ignore the <em>Small</em> and the first two groups of numbers.</p>
<p>For this exercise, let's ignore the fact that it might be easier to just do some sort of string-split instead of a regular expression.</p>
<p>I have this regex that works but is kind of horrible looking</p>
<pre><code>^(Small).*?[0-9.]+.*?[0-9.]+.*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+)
</code></pre>
<p>Is there some way to compact that?</p>
<p>For example, is it possible to combine the check for the last 6 numbers into a single statement that still stores the results as 6 separate group matches?</p>
|
<p>If you want to keep each match in a separate backreference, you have no choice but to "spell it out" - if you use repetition, you can either catch all six groups "as one" or only the last one, depending on where you put the capturing parentheses. So no, it's not possible to compact the regex and still keep all six individual matches.</p>
<p>A somewhat more efficient (though not beautiful) regex would be:</p>
<pre><code>^Small\s+[0-9.]+\s+[0-9.]+\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)
</code></pre>
<p>since it matches the spaces explicitly. Your regex will result in a lot of backtracking. My regex matches in 28 steps, yours in 106.</p>
<p>Just as an aside: In Python, you could simply do a</p>
<pre><code>>>> pieces = "Small 0.0..20.0 0.00 1.49 25.71 41.05 12.31 0.00 80.56".split()[-6:]
>>> print pieces
['1.49', '25.71', '41.05', '12.31', '0.00', '80.56']
</code></pre>
|
<p>For usability, you should use string substitution to build regex from composite parts. </p>
<pre><code>$d = "[0-9.]+";
$s = ".*?";
$re = "^(Small)$s$d$s$d$s($d)$s($d)$s($d)$s($d)$s($d)$s($d)";
</code></pre>
<p>At least then you can see the structure past the pattern, and changing one part changes them all. </p>
<p>If you wanted to get really ANSI you could make a short use metasyntax and make it even easier to read: </p>
<pre><code>$re = "^(Small)_#D_#D_(#D)_(#D)_(#D)_(#D)_(#D)_(#D)";
$re = str_replace('#D','[0-9.]+',$re);
$re = str_replace('_', '.*?' , $re );
</code></pre>
<p>( This way it also makes it trivial to change the definition of what a space token is, or what a digit token is ) </p>
| 37,409
|
<p>This is a question that was sparked by <a href="https://stackoverflow.com/users/3631/rob-walker">Rob Walker</a>'s answer <a href="https://stackoverflow.com/questions/36455/alignment-restrictions-for-mallocfree#36466">here</a>.</p>
<p>Suppose I declare a class/struct like so:</p>
<pre><code>struct
{
char A;
int B;
char C;
int D;
};
</code></pre>
<p>Is it safe to assume that these members will be declared in exactly that order in memory, or is this a compiler dependent thing? I'm asking because I had always assumed that the compiler can do whatever it wants with them.</p>
<p>This leads into my next question. If the above example causes memory alignment issues, why can the compiler not just turn that into something like this implicitly:</p>
<pre><code>struct
{
char A;
char C;
int B;
int D;
};
</code></pre>
<p>(I'm primarily asking about C++, but I'd be interested to hear the C answer as well)</p>
<h3>Related topics</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/118068/why-doesnt-gcc-optimize-structs">Why doesn't GCC optimize structs?</a></li>
</ul>
|
<p>C99 Β§6.7.2.1 clause 13 states:</p>
<blockquote>
<p>Within a structure object, the
non-bit-ο¬eld members and the units in
which bit-ο¬elds reside have addresses
that increase in the order in which
they are declared.</p>
</blockquote>
<p>and goes on to say a bit more about padding and addresses. The C89 equivalent section is Β§6.5.2.1.</p>
<p>C++ is a bit more complicated. In the 1998 and 2003 standards, there is Β§9.2 clause 12 (clause 15 in C++11):</p>
<blockquote>
<p>Nonstatic data members of a
(non-union) class declared without an
intervening access-specifier are
allocated so that later members have
higher addresses within a class
object. The order of allocation of
nonstatic data members separated by an
access-specifier is unspecified
(11.1). Implementation alignment
requirements might cause two adjacent
members not to be allocated
immediately after each other; so might
requirements for space for managing
virtual functions (10.3) and virtual
base classes (10.1).</p>
</blockquote>
|
<p>While browsing the related topics at the right, I looked at <a href="https://stackoverflow.com/questions/127290/is-it-possible-to-subclass-a-c-struct-in-c-and-use-pointers-to-the-struct-in-c">this question</a>. I figure this may be an interesting corner case when thinking about these issues (unless it's more common than I realize).</p>
<p>To paraphrase, if you have a struct in C that looks something like this:</p>
<pre><code>struct foo{};
</code></pre>
<p>and subclass it like so in C++ (using a separate compilation unit):</p>
<pre><code>extern "C" foo;
struct bar: public foo{};
</code></pre>
<p>Then the memory alignment won't necessarily be the same for the reasons <a href="https://stackoverflow.com/questions/281045/do-classstruct-members-always-get-created-in-memory-in-the-order-they-were-decl#281082">aib</a> mentions (even amongst compilers from the same vendor).</p>
| 35,556
|
<p>In VS2008, I have a web-site project. When I use find in files and search for a string, the find results window will list every occurence twice.</p>
<p>What could be causing this?</p>
<p>[EDIT]</p>
<p>Below is the screen capture from VS. I was searching for the work CommissionBucketProductID within my website project. Notice that each line is returned twice.</p>
<p><img src="https://i.stack.imgur.com/LXSyr.gif" alt="Screen Capture"></p>
<p>[EDIT2]</p>
<p>In response to your questions. I am only searching within the project, not the whole solution. I currently don't have these files under VSS, although they were in the past.</p>
|
<p>I had the same issue which was annoying. I just fixed it. What I've done is to change "Entire solution" to "current project" in "Look in" field when doing search. Then I noticed the result would not be doubled. After I switched back to "entire solution" the problem was gone.</p>
|
<p>Try closing VS2008, renaming the file (USPostalApplciation.aspx and the code behind file too), then re-opening VS2008, refresh everything you can think of (project, solution, etc...) then try doing the search again.</p>
| 28,857
|
<p>How can I use JUnit idiomatically to test that some code throws an exception?</p>
<p>While I can certainly do something like this:</p>
<pre><code>@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
</code></pre>
<p>I recall that there is an annotation or an Assert.xyz or <em>something</em> that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.</p>
|
<p>It depends on the JUnit version and what assert libraries you use.</p>
<ul>
<li>For JUnit5 and 4.13 <a href="https://stackoverflow.com/a/2935935/2986984">see answer</a></li>
<li>If you use AssertJ or google-truth, <a href="https://stackoverflow.com/a/41019785/2986984">see answer</a></li>
</ul>
<p>The original answer for <code>JUnit <= 4.12</code> was:</p>
<pre class="lang-java prettyprint-override"><code> @Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
</code></pre>
<p>Though <a href="https://stackoverflow.com/a/31826781/2986984">answer</a> has more options for JUnit <= 4.12.</p>
<p>Reference:</p>
<ul>
<li><a href="https://junit.org/junit4/faq.html#atests_7" rel="nofollow noreferrer">JUnit Test-FAQ</a></li>
</ul>
|
<p>I wanted to comment with my solution to this problem, which avoided needing any of the exception related JUnit code.</p>
<p>I used assertTrue(boolean) combined with try/catch to look for my expected exception to be thrown. Here's an example:</p>
<pre><code>public void testConstructor() {
boolean expectedExceptionThrown;
try {
// Call constructor with bad arguments
double a = 1;
double b = 2;
double c = a + b; // In my example, this is an invalid option for c
new Triangle(a, b, c);
expectedExceptionThrown = false; // because it successfully constructed the object
}
catch(IllegalArgumentException e) {
expectedExceptionThrown = true; // because I'm in this catch block
}
catch(Exception e) {
expectedExceptionThrown = false; // because it threw an exception but not the one expected
}
assertTrue(expectedExceptionThrown);
}
</code></pre>
| 18,931
|
<p>Coming from a corporate IT environment, the standard was always creating a class library project for each layer, Business Logic, Data Access, and sometimes greater isolation of specific types.</p>
<p>Now that I am working on my own web application project, I don't see a real need to isolate my code in this fashion. </p>
<p>I don't have multiple applications that need to share this logic or service enable it. I also don't see any advantage to deployment scenarios.</p>
<p>I am leaning towards putting all artifacts in one web application, logically separated by project folders.</p>
<p>I wanted to know what the thoughts are of the community.</p>
<hr>
<p>Let me add more information...</p>
<p>I am writing this application using MVC preview 5, so the unit testing piece will be supported by the separation of concerns inherit in the framework. I do like to have tests for everything!</p>
|
<p>Start with the simplest thing possible and add complexity if and when required. Sounds as though a single assembly would work just fine for your case. However, do take care not to violate the layers by having layer A access an internal member of layer B. That would make it harder to pull the layers into separate assemblies at a later date.</p>
|
<p>I'd say it depends on how serious you are about testing and unit-testing.</p>
<p>If you plan to only do user/manual tests, or use basically, only test from the UI downward, then it doesn't really make a difference.</p>
<p>On the other hand, if you plan on doing sort of unit-testing, or business rules validation, it definitely makes sense to split up your work into different assemblies.</p>
<p>Even for smaller personal projects, I find this approach makes my life easier as the project goes on. I still run everything from the same solution, just with a web project for the UI, library for the business rules / application logic and another library for the DAL.</p>
| 8,333
|
<p>I have a table in SQL server that has the normal tree structure of Item_ID, Item_ParentID.
Suppose I want to iterate and get all CHILDREN of a particular Item_ID (at any level).</p>
<p>Recursion seems an intuitive candidate for this problem and I can write an SQL Server function to do this. </p>
<p>Will this affect performance if my table has many many records?
How do I avoid recursion and simply query the table? Please any suggestions?</p>
|
<p>With the new MS SQL 2005 you could use the <code>WITH</code>keyword</p>
<p>Check out <a href="https://stackoverflow.com/questions/91360/how-to-calculate-the-sum-of-values-in-a-tree-using-sql">this question</a> and particularly <a href="https://stackoverflow.com/questions/91360/how-to-calculate-the-sum-of-values-in-a-tree-using-sql#93202">this answer</a>.</p>
<p>With Oracle you could use <code>CONNECT BY</code> keyword to generate hierarchical queries (<a href="http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14200/queries003.htm" rel="nofollow noreferrer">syntax</a>).</p>
<p>AFAIK with MySQL you'll have to use the recursion.</p>
<p>Alternatively you could always build a cache table for your records parent->child relationships</p>
|
<p>Perhaps some more detail is in order.</p>
<p>If you have a master-detail relationship as you describe, then won't a simple JOIN get what you need?</p>
<p>As in:</p>
<pre><code>SELECT
SOME_FIELDS
FROM
MASTER_TABLE MT
,CHILD_TABLE CT
WHERE CT.PARENT_ID = MT.ITEM_ID
</code></pre>
| 23,216
|
<p>I need to create a historical timeline starting from 1600's to the present day. I also need to have some way of showing events on the timeline so that they do not appear cluttered when many events are close together.</p>
<p>I have tried using Visio 2007 as well as Excel 2007 Radar Charts, but I could not get the results I wanted. the timeline templates in Visio are not great and using Radar charts in Excel leads to cluttered data.</p>
<p>Are there any other tools or techniques I could use to create these?</p>
<p><b>@Darren:</b><br>
The first link looks great. Thanks! The second link did not work in Firefox and was rendered as ASCII. It opened up fine in IE.<br>
And yes, this is for the end users. So I want it to look as presentable as possible, if you know what I mean. <br>
Thanks again!</p>
|
<p>SIMILIE Timeline would probably suit your needs.
<a href="http://simile.mit.edu/timeline/" rel="noreferrer">http://simile.mit.edu/timeline/</a></p>
<p>Timeline .NET: <a href="http://www.codeplex.com/timelinenet" rel="noreferrer">http://www.codeplex.com/timelinenet</a></p>
<p>Oh, i guess i should ask... for personal use or for display to end users? that might change what i would suggest, but this could work for internal purposes too i suppose.</p>
|
<p>@Pascal this page? <a href="http://tools.mscorlib.com/timeline/Default.aspx" rel="nofollow noreferrer">http://tools.mscorlib.com/timeline/Default.aspx</a>. If it's looking like ascii maybe look for a js error, but that renders on my system fine. If all else fails, it's a decent js library by the MIT team as it is, so you could wire up your own implementation</p>
| 3,333
|
<p>It seems that IE6 ignores any form of cache invalidation sent via http headers, I've tried setting Pragma to No Cache and setting Cache Expiration to the current time, yet in IE6, hitting back will always pull up a cached version of a page I am working on.</p>
<p>Is there a specific HTTP Header that IE6 does listen too?</p>
|
<p><code>Cache-Control: private, max-age=0</code> should fix it. From classic ASP this is done with <code>Response.Expires=-1</code>.</p>
<p>Keep in mind when testing that just because your server is serving pages with caching turned off doesn't mean that the browser will obey that when it has an old cached page that it was told was okay to cache. Clear the cache or use F5 to force that page to be reloaded.</p>
<p>Also, for those cases where the server is serving cached content it you can use <KBD>Ctrl+F5</KBD> to signal the server not to serve it from cache.</p>
|
<p>Have you tried setting an ETag in the header? They're a pretty reliable way to indicate that content has changed <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19" rel="nofollow noreferrer">w3c Spec</a> & <a href="http://en.wikipedia.org/wiki/HTTP_ETag" rel="nofollow noreferrer">Wikipedia</a></p>
<p>Beyond that, a little more crude way is to append a random query string parameter to the request, such as the current unix timestamp. As I said, crude, but then IE6 is not the most subtle of beasts </p>
| 6,371
|
<p>A client wants me to do some maintenance work to a VB 6.0 application (migration to .NET is also in the pipeline), but he doesn't have the development tools because he received just the source code and running application from the original programmer, who is no longer available.</p>
<p>Microsoft doesn't sell Visual Studio 6.0, as far as I know. <strong>How can I modify and compile the source code for a VB6 application without VB6?</strong> or <strong>Where do I get Visual Studio 6.0 if Microsoft is not selling it?.</strong></p>
<p>Even if I migrate everything to .NET without releasing a new VB6 version, I would like to be able to open the project and see it compile and run to better understand it.</p>
<p>I have VS 2005 and VB 2008. But I understand that if I try to open the project the code will be converted to VB.NET and that's not what I would want before getting to know the project better.</p>
|
<p>From what I recall the Visual Studio 6.0 is available for MSDN Subscribers.</p>
|
<p>To get a feel of the code, you could try to compile parts of the application in MS Office / VBA.</p>
<p>Of course, this will only offer limited functionality, but may suffice for some testing.</p>
| 22,523
|
<p>OK -- a bit of an undefined question (is the pattern of plugs in an Eniac plugboard a language ??) but contenders include:</p>
<ul>
<li>Konrad Zuse's PlanKalkΓΌl (1940s) -
never implemented (generally
accepted as the first). </li>
<li>Whatever Ada Lovelace (1840s) programmed in (not
Ada) -- if she is the first
programmer, as everyone says, she
must have used the first programming
language, no? Again probably never
implemented - but did Babbage have
anything that could be called a
language? </li>
<li>Turing's description of
his Turing machine (1936 paper). In
the paper he actually writes
programs and simulates their
execution mathematically - that
makes it as good as (and earlier
than) PlanKalkΓΌl in my book.</li>
<li><p>Autocode for the Machester Mark 1 computer (1952) -- compiled, high level, beats Fortan to the punch (?). Mr Turing again (!).</p></li>
<li><p>Fortran (Early 1950's) - beats out Lisp by a couple of years and undoubtedly passes the sniff test. But was it earlier than Mark 1 autocode ??</p></li>
</ul>
|
<p>The PBS series Connections made the argument that the holes punched in tiles to control the patterns created on looms (circa 1700s??) were the first programming "language".</p>
<p>These were followed by player piano scrolls: Codes, on paper, which are read by, and control the operation of a machine. That's a programming language, isn't it?</p>
|
<p>I would say that the first programming language actually <em>used</em> was the machine language of the first stored program computer, which I believe was Baby: <a href="http://www.computer50.org/" rel="nofollow noreferrer">http://www.computer50.org/</a></p>
| 11,092
|
<p>In Java, suppose I have a String variable S, and I want to search for it inside of another String T, like so:</p>
<pre><code> if (T.matches(S)) ...
</code></pre>
<p>(note: the above line was T.contains() until a few posts pointed out that that method does not use regexes. My bad.)</p>
<p>But now suppose S may have unsavory characters in it. For instance, let S = "[hi". The left square bracket is going to cause the regex to fail. Is there a function I can call to escape S so that this doesn't happen? In this particular case, I would like it to be transformed to "\[hi".</p>
|
<p>String.contains does not use regex, so there isn't a problem in this case.</p>
<p>Where a regex is required, rather rejecting strings with regex special characters, use java.util.regex.Pattern.quote to escape them.</p>
|
<p>Regex uses the backslash character '\' to escape a literal. Given that java also uses the backslash character you would need to use a double bashslash like:</p>
<pre><code> String S = "\\[hi"
</code></pre>
<p>That will become the String:</p>
<pre><code> \[hi
</code></pre>
<p>which will be passed to the regex. </p>
<p>Or if you only care about a literal String and don't need a regex you could do the following:</p>
<pre><code>if (T.indexOf("[hi") != -1) {
</code></pre>
| 20,358
|
<p>I used a query a few weeks ago in MySQL that described a table and suggested possible improvements to its structure. For example, if I have an int field but only the numbers 1-3 in that field, it will suggest set(1,2,3) as the type.</p>
<p>I think I was using phpMyAdmin but I've been through all the functions I can find - Analyze, Describe, Explain, Optimize, etc - to no avail. I can't for the life of me remember what the query was!</p>
|
<p>This is what phpMyAdmin gives me:</p>
<pre><code>SELECT *
FROM `table_name`
PROCEDURE ANALYSE ( )
</code></pre>
|
<p>In phpMyAdmin 2.11.6
Go to Structure tab of your table. Below list of fields there are 3 buttons with labels:
"Print view" "Relation view" "Propose table structure" .</p>
<p>Last one is what you need.</p>
| 45,448
|
<p>I have a collection of objects in a database. Images in a photo gallery, products in a catalog, chapters in a book, etc. Each object is represented as a row. I want to be able to arbitrarily order these images, storing that ordering in the database so when I display the objects, they will be in the right order.</p>
<p>For example, let's say I'm writing a book, and each chapter is an object. I write my book, and put the chapters in the following order:</p>
<blockquote>
<p>Introduction, Accessibility, Form vs. Function, Errors, Consistency, Conclusion, Index</p>
</blockquote>
<p>It goes to the editor, and comes back with the following suggested order:</p>
<blockquote>
<p>Introduction, Form, Function, Accessibility, Consistency, Errors, Conclusion, Index</p>
</blockquote>
<p>How can I store this ordering in the database in a robust, efficient way?</p>
<p>I've had the following ideas, but I'm not thrilled with any of them:</p>
<ol>
<li><p>Array. Each row has an ordering ID, when order is changed (via a removal followed by an insertion), the order IDs are updated. This makes retrieval easy, since it's just <code>ORDER BY</code>, but it seems easy to break.</p>
<blockquote>
<p><code>// REMOVAL</code><br>
<code>UPDATE ... SET orderingID=NULL WHERE orderingID=removedID</code><br>
<code>UPDATE ... SET orderingID=orderingID-1 WHERE orderingID > removedID</code><br>
<code>// INSERTION</code><br>
<code>UPDATE ... SET orderingID=orderingID+1 WHERE orderingID > insertionID</code><br>
<code>UPDATE ... SET orderID=insertionID WHERE ID=addedID</code></p>
</blockquote></li>
<li><p>Linked list. Each row has a column for the id of the next row in the ordering. Traversal seems costly here, though there may by some way to use <code>ORDER BY</code> that I'm not thinking of.</p></li>
<li><p>Spaced array. Set the orderingID (as used in #1) to be large, so the first object is 100, the second is 200, etc. Then when an insertion happens, you just place it at <code>(objectBefore + objectAfter)/2</code>. Of course, this would need to be rebalanced occasionally, so you don't have things too close together (even with floats, you'd eventually run into rounding errors).</p></li>
</ol>
<p>None of these seem particularly elegant to me. Does anyone have a better way to do it?</p>
|
<p>An other alternative would be (if your RDBMS supports it) to use columns of type array. While this breaks the normalization rules, it can be useful in situations like this. One database which I know about that has arrays is PostgreSQL.</p>
|
<p>I had the same issue and have probably spent at least a week concerning myself about the proper data modeling, but I think I've finally got it. Using the array datatype in PostgreSQL, you can store the primary key of each ordered item and update that array accordingly using insertions or deletions when your order changes. Referencing a single row will allow you to map all your objects based on the ordering in the array column.</p>
<p>It's still a bit choppy of a solution but it will likely work better than option #1, since option 1 requires updating the order number of all the other rows when ordering changes. </p>
| 4,155
|
<p>When the view property of a UIViewController is accessed, it first checks to see if it's got an existing view, and returns that. If not, it loads its nib or calls -loadView. </p>
<p>When a controller receives a -didReceiveMemoryWarning message, the default behavior is to remove that cached view (assuming it's not in use at the time). </p>
<p>If I override -didReceiveMemoryWarning, how can I determine whether the view has been cleared? My understanding is that the default implementation checks to see if self.view.superview == nil. If so, it clears the cached view. Of course, it first checks to see if there <em>is</em> a cached view, and if not, it does nothing. However, I, as a subclass, can't call self.view.superview, for if there <em>isn't</em> a view, it'll generate one.</p>
<p>So, how do I figure out if _view exists? (I can't just look at _view; I get linking errors when building for the device).</p>
|
<p>Since iPhone OS 3.0, you can use the <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instm/UIViewController/isViewLoaded" rel="noreferrer"><code>isViewLoaded</code></a> method to see if a view is loaded.</p>
|
<p>You could use <a href="http://developer.apple.com/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/doc/uid/TP40001418-CH1g-SW1" rel="nofollow noreferrer">object_getIvar()</a> to get at the value without going through the accessor. In essence, it lets you get at _view without needing to link against it. On the other hand, it has the potential to break if the actual ivar goes away or is renamed. Traditionally that was never a real concern, but the iPhone uses the modern runtime which does not suffer from fragile base class issues, so Apple might feel more inclined to make those sorts of changes.</p>
| 44,111
|
<p>I've been using Emacs's sql interactive mode to talk to the MySQL db server and gotten to enjoy it. A developer has set up another db on a new non-default port number but I don't know how to access it using sql-mysql.</p>
<p>How do I specify a port number when I'm trying to connect to a database?</p>
<p>It would be even better if Emacs can prompt me for a port number and just use the default if I don't specify. Any chances of that?</p>
|
<p>After digging through the sql.el file, I found a variable that allows me to specify a port when I try to create a connection.</p>
<p>This option was added GNU Emacs 24.1.</p>
<blockquote>
<p><strong>sql-mysql-login-params</strong></p>
<p>List of login parameters needed to connect to MySQL.</p>
</blockquote>
<p>I added this to my Emacs init file:</p>
<pre><code>(setq sql-mysql-login-params (append sql-mysql-login-params '(port)))
</code></pre>
<p>The default port is 0. If you'd like to set that to the default MySQL port you can customize <code>sql-port</code></p>
<pre><code>(setq sql-port 3306) ;; default MySQL port
</code></pre>
<p>There is a <code>sql-*-login-params</code> variable for all the popular RDMS systems in GNU Emacs 24.1. <code>sql-port</code> is used for both MySQL and PostreSQL</p>
|
<pre><code>(setq sql-mysql-options (list "-P <port number>"))
</code></pre>
| 3,369
|
<p>Has anyone got the steps to compile darwin libraries on gcc for arm on ubuntu?</p>
|
<p>There is a <a href="http://ostatic.com/darwin-arm" rel="nofollow noreferrer">site</a> that provides patches for and arm darwin kernel.</p>
<blockquote>
<p>Darwin on ARM develops and provides patches for the Apple Darwin-xnu kernel sources so that it can be cross-compiled to run on an ARM processor.</p>
</blockquote>
<p>This ubuntu <a href="http://ubuntuforums.org/showthread.php?t=360877" rel="nofollow noreferrer">forum entry</a> shows how to install the arm-linux-gcc cross compiler.</p>
<p>Put the two together and you should get what you asked for.</p>
|
<p><a href="https://github.com/tpoechtrager/osxcross" rel="nofollow noreferrer">https://github.com/tpoechtrager/osxcross</a></p>
<p>step by step install it ref to <a href="https://enigma-dev.org/docs/wiki/index.php?title=CrossCompileLinuxOSX" rel="nofollow noreferrer">https://enigma-dev.org/docs/wiki/index.php?title=CrossCompileLinuxOSX</a></p>
| 37,729
|
<p>I have VS2005 and I am currently trying to debug an ASP.net web application. I want to change some code around in the code behind file, but every time I stop at a break point and try to edit something I get the following error message: "Changes are not allowed when the debugger has been attached to an already running process or the code being debugged is optimized."</p>
<p>I'm pretty sure I have all the "Edit and Continue" options enabled. Any suggestions?</p>
|
<p>The application is actually running off of a compiled version of your code. If you modify it it will have to recompile it in order for your changes to work, which means that it will need to swap out the running version for the new compiled version. This is a pretty hard problem - which is why I think Microsoft has made it impossible to do. It's more to protect you from THINKING some changes were made when they really weren't.</p>
|
<p>Check that you are not in release mode.
In release mode you cannot edit your code while debugging. Just change mode to Debug</p>
| 10,198
|
<p>How do you do your own fonts? I don't want a heavyweight algorithm (freetype, truetype, adobe, etc) and would be fine with pre-rendered bitmap fonts.</p>
<p>I do want anti-aliasing, and would like proportional fonts if possible.</p>
<p>I've heard I can use Gimp to do the rendering (with some post processing?)</p>
<p>I'm developing for an embedded device with an LCD. It's got a 32 bit processor, but I don't want to run Linux (overkill - too much code/data space for too little functionality that I would use)</p>
<p>C. C++ if necessary, but C is preferred. Algorithms and ideas/concepts are fine in any language...</p>
<p>-Adam</p>
|
<p>In my old demo-scene days I often drew all characters in the font in one big bitmap image. In the code, I stored the (X,Y) coordinates of each character in the font, as well as the width of each character. The height was usually constant throughout the font. If space isn't an issue, you can put all characters in a grid, that is - have a constant distance between the top-left corner of each character.</p>
<p>Rendering the text then becomes a matter of copying one letter at a time to the destination position. At that time, I usually reserved one color as being the "transparent" color, but you could definitely use an alpha-channel for this today.</p>
<p>A simpler approach, that can be used for small b/w fonts, is to define the characters directly in code:</p>
<pre><code>LetterA db 01111100b
db 11000110b
db 11000110b
db 11111110b
db 11000110b
db 11000110b
</code></pre>
<p>The XPM file format is actually a file format with C syntax that can be used as a hybrid solution for storing the characters.</p>
|
<p>Pre-rendered bitmap fonts are probably the way to go. Render your font using whatever, arrange the characters in a grid, and save the image in a simple uncompressed format like PPM, BMP or TGA. If you want antialiasing, make sure to use a format that supports transparency (BMP and TGA do; PPM does not).</p>
<p>In order to support proportional widths, you'll need to extract the widths of each character from the grid. There's no simple way to do this, it depends on how you generate the grid. You could probably write some short little program to analyze each character and find the minimal bounding box. Once you have the width data, you put it in an auxiliary file which contains the coordinates and sizes of each character.</p>
<p>Finally, to render a string, you look up each character and bitblit its rectangle from the font bitmap onto your frame buffer, advancing the raster position by the width of the character.</p>
| 17,341
|
<p>If a company often requires users to be created in a partner's active directory, and vice versa, does it make sense to set up a federated / trusted relationship between the AD instances? If so, what should be considered? Does the ACL for users in the partner AD still work the same way? What security risks does this expose?</p>
<p>Thanks!</p>
<p>KA</p>
<p><strong>Update:</strong> </p>
<p>I've learned that there's a better way to do this by having the application itself check user stores. The best way to do this is by moving the application into a domain trusted by both user stores. I've provided more detail in my answer below.</p>
|
<p>I've been researching this a bit more, and I've found a good solution. Since both companies both need to use the same system, the system itself just needs to verify if a user exists in either of the user stores(authentication), and then to the authorization at the system level. </p>
<p>The idea behind giving both companies access is solid - If we are working together and didn't have a way to do this, we'd need to re-create all the users from the company without access in the connected user store. Obviously, this would be a total mess and a maintenance nightmare. </p>
<p>I found out that in my case, even though both ADs are on the same WAN, it's necessary to have a formal federation or trust. Thankfully, we already have a domain that's trusted between both companies, so I just have to move the applications used by the partners into this domain. After that, it's simply a matter of fully-qualifying the DNS suffix to indicate the AD being used. Application-specific ACLs then reference the desired user store.</p>
|
<p>I've been researching this a bit more, and I've found a good solution. Since both companies both need to use the same system, the system itself just needs to verify if a user exists in either of the user stores(authentication), and then to the authorization at the system level. </p>
<p>The idea behind giving both companies access is solid - If we are working together and didn't have a way to do this, we'd need to re-create all the users from the company without access in the connected user store. Obviously, this would be a total mess and a maintenance nightmare. </p>
<p>I found out that in my case, even though both ADs are on the same WAN, it's necessary to have a formal federation or trust. Thankfully, we already have a domain that's trusted between both companies, so I just have to move the applications used by the partners into this domain. After that, it's simply a matter of fully-qualifying the DNS suffix to indicate the AD being used. Application-specific ACLs then reference the desired user store.</p>
| 34,458
|
<p>When you plot things in Matlab, the most recently plotted data series is placed on top of whatever's already there. For example:</p>
<pre><code>figure; hold on
plot(sin(linspace(0,pi)),'linewidth',4,'color',[0 0 1])
plot(cos(linspace(0,pi)),'linewidth',4,'color',[1 0 0])
</code></pre>
<p>Here, the red line is shown on top of the blue line (where they intersect). Is there any way to set "how deep" a line is drawn, so that you can plot things <em>beneath</em> what's already there?</p>
|
<p>Use the <strong>uistack</strong> command. For example:</p>
<pre><code>h1 = plot(1:10, 'b');
hold on;
h2 = plot(1:10, 'r');
</code></pre>
<p>will plot two lines with the red line plotted on top of the blue line. If you then do:</p>
<pre><code>uistack(h1);
</code></pre>
<p>the blue line will be brought to the front.</p>
|
<p>You can also accomplish this by setting the order of the children vector of the current axes. If you do the following:</p>
<pre><code>figure; hold on
h1 = plot(sin(linspace(0,pi)),'linewidth',4,'color',[0 0 1]);
h2 = plot(cos(linspace(0,pi)),'linewidth',4,'color',[1 0 0]);
h = get(gca, 'Children');
</code></pre>
<p>you will see that h is a vector that contains h1 and h2. The graphical stacking order is represented by the order of the handles in h. In this example, to reverse the stacking order you could do:</p>
<pre><code>h = flipud(h);
set(gca, 'Children', h);
</code></pre>
| 25,419
|
<p>In Delphi, I want to be able to create an private object that's associated with a class, and access it from all instances of that class. In Java, I'd use:</p>
<pre><code>public class MyObject {
private static final MySharedObject mySharedObjectInstance = new MySharedObject();
}
</code></pre>
<p>Or, if MySharedObject needed more complicated initialization, in Java I could instantiate and initialize it in a static initializer block.</p>
<p>(You might have guessed... I know my Java but I'm rather new to Delphi...)</p>
<p>Anyway, I don't want to instantiate a new MySharedObject each time I create an instance of MyObject, but I do want a MySharedObject to be accessible from each instance of MyObject. (It's actually logging that has spurred me to try to figure this out - I'm using Log4D and I want to store a TLogLogger as a class variable for each class that has logging functionality.)</p>
<p>What's the neatest way to do something like this in Delphi?</p>
|
<p>Here is how I'll do that using a class variable, a class procedure and an initialization block:</p>
<pre><code>unit MyObject;
interface
type
TMyObject = class
private
class var FLogger : TLogLogger;
public
class procedure SetLogger(value:TLogLogger);
class procedure FreeLogger;
end;
implementation
class procedure TMyObject.SetLogger(value:TLogLogger);
begin
// sanity checks here
FLogger := Value;
end;
class procedure TMyObject.FreeLogger;
begin
if assigned(FLogger) then
FLogger.Free;
end;
initialization
TMyObject.SetLogger(TLogLogger.Create);
finalization
TMyObject.FreeLogger;
end.
</code></pre>
|
<p>Before version 7, Delphi didn't have static variables, you'd have to use a global variable.</p>
<p>To make it as private as possible, put it in the <code>implementation</code> section of your unit.</p>
| 9,730
|
<p>Are there major advantages to <a href="https://web.archive.org/web/20090207080811/http://www.innodb.com:80/hot-backup/features/" rel="nofollow noreferrer">InnoDB hot backup</a> vs ZRM <a href="https://www.zmanda.com/zrm-enterprise/" rel="nofollow noreferrer">snapshots</a> in terms of disruption to the running site, the size of compressed backup files, and speed of backup/restore on a medium-sized to largish all-InnoDB database?</p>
<p>My understanding is that InnoDB's approach is more reliable, faster, does not cause a significant outage when running, etc.</p>
|
<p>Rebooting while updating an access database can trash it.</p>
<p>You need some more info so that you have a better understanding of what is going on. They need to collect some information for you on a workstation that is having the problem. Using task manager you can have them get the following info:</p>
<ul>
<li>CPU utilization</li>
<li>What task is consuming the most cpu</li>
<li>Peak (committed) memory on XP - no equiv on Vista</li>
<li>Total (committed) memory on XP - no equiv on Vista</li>
<li>Available (physical) memory on XP - Free on Vista (made worthless by Superfetch)</li>
</ul>
<p>It's also possible to use the command line tool "SYSTEMINFO" on both XP and Vista to get Total and Available memory. If you have very little available and on XP if your Total committed is larger than your Total Physical then you are most likely swapping and lack of memory (or a memory leak) is causing your slow down.</p>
<p>Bottom line is you need more information. It may be another app on the workstation is causing the problem. We had a situation where Notes 5.0 had a problem where if most of the window is covered up by another window and you received a new mail message the cpu utilization on Notes went to 100%. This caused apps to run slow and unless you are on the workstation looking at task monitor you would never guess it was Notes causing the problem. The problem was always called in on a different program (the one in the foreground). Access can also use 100% cpu in different modes even though it doesn't seem like it's doing anything.</p>
<p>Gather as much info as you can. You might want to write a vbscript or program that will will gather some info for you so that whomever is having the problem can run it to gather the info before rebooting.</p>
<p>A batch file that does the following will give you quite a bit of info:</p>
<pre><code>
@echo off
SystemInfo >c:\systeminfo.log
tasklist /v >>c:\systeminfo.log
</code></pre>
|
<p>Sounds like a big memory leak to me. </p>
<p>Some customers will leave your application running for longer than others, and will be harder hit.</p>
<p>Using Access where there are more than a few concurrent users inevitably results in pain.</p>
| 35,628
|
<pre><code>Option Explicit On
Option Strict On
Public Class Class1
Dim l As List(Of A)
Public Sub New()
l = New List(Of B)
End Sub
End Class
Public Class A
End Class
Public Class B
Inherits A
End Class<p>
</code></pre>
<p>I've run into this problem.<br>
I have a list declared of a Generic Type 'A'<br>
I want to define the list as a Generic Type 'B', which is a subclass of 'A'.<p>
Why can't this be done, and how can the same effect be achieved?</p>
|
<p>It's a matter of variance, which C# doesn't support for generics. See <a href="http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx" rel="nofollow noreferrer">Rick Byer's post on the subject</a>.</p>
|
<p>If you could cast a list of As as a list of Bs, then what would happen if you added an A?</p>
| 21,769
|
<p>I'm wondering how slow it's going to be switching between 2 databases on every call of every page of a site. The site has many different databases for different clients, along with a "global" database that is used for some general settings. I'm wondering if there would be much time added for the execution of each script if it has to connect to the database, select a DB, do a query or 2, switch to another DB and then complete the page generation. I could also have the data repeated in each DB, I just need to mantain it (will only change when upgrading).</p>
<p>So, in the end, how fast is <code>mysql_select_db()</code>?</p>
<p><strong>Edit:</strong> Yes, I could connect to each DB separately, but as this is often the slowest part of any PHP script, I'd like to avoid this, especially since it's on every page. (It's slow because PHP has to do some kind of address resolution (be it an IP or host name) and then MySQL has to check the login parameters both times.)</p>
|
<p>Assuming that both databases are on the same machine, you don't need to do the mysql_select_db. You can just specify the database in the queries. For example;</p>
<pre><code>SELECT * FROM db1.table1;
</code></pre>
<p>You could also open two connections and use the DB object that is returned from the connect call and use those two objects to select the databases and pass into all of the calls. The database connection is an optional parameter on all of the mysql db calls, just check the docs.</p>
|
<p>You're asking two quite different questions.</p>
<ol>
<li><p>Connecting to multiple database instances</p></li>
<li><p>Switching default database schemas.</p></li>
</ol>
<p>MySQL is known to have quite fast connection setup time; making two <code>mysql_connect()</code> calls to different servers is barely more expensive than one.</p>
<p>The call <code>mysql_select_db()</code> is exactly the same as the <code>USE</code> statement and simply changes the default database schema for unqualified table references.</p>
<p>Be careful with your use of the term 'database' around MySQL: it has two different meanings.</p>
| 33,007
|
<p>I want to migrate from Embarcadero Delphi to Visual Studio, but without a <a href="http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate4/EN/html/delphivclwin32/DBClient_TClientDataSet.html" rel="nofollow noreferrer">TClientDataset</a> class it is very difficult.
This class represents an in-memory dataset.</p>
<p>I can't find any class like <a href="http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate4/EN/html/delphivclwin32/DBClient_TClientDataSet.html" rel="nofollow noreferrer">TClientDataset</a>.</p>
<p>Can anyone help me find something like this please?</p>
|
<p>Visual studio has DataSet and DataTable classes which are very close to what a TClientDataSet is in Delphi.</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx</a></p>
|
<p>Visual studio has DataSet and DataTable classes which are very close to what a TClientDataSet is in Delphi.</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx</a></p>
| 16,817
|
<p>Can someone explain this in a practical way? Sample represents usage for one, low-traffic Rails site using Nginx and 3 Mongrel clusters. I ask because I am aiming to learn about page caching, wondering if these figures have significant meaning to that process. Thank you. Great site!</p>
<pre><code>me@vps:~$ free -m
total used free shared buffers cached
Mem: 512 506 6 0 15 103
-/+ buffers/cache: 387 124
Swap: 1023 113 910
</code></pre>
|
<p>Physical memory is all used up. Why? Because it's there, the system should be using it.</p>
<p>You'll note also that the system is using 113M of swap space. Bad? Good? It depends. </p>
<p>See also that there's 103M of cached disk; this means that the system has decided that it's better to cache 103M of disk and swap out these 113M; maybe you have some processes using memory that are not being used and thus are paged out to disk.</p>
<p>As the other poster said, you should be using other tools to see what's happening:</p>
<ol>
<li>Your perception: is the site running appropiately when you use it?</li>
<li>Benchmarking: what response times are your clients seeing?</li>
<li>More fine-grained diagnostics:
<ol>
<li>top: you can see live which processes are using memory and CPU</li>
<li>vmstat: it produces this kind of output:</li>
</ol></li>
</ol>
<pre>
alex@armitage:~$ vmstat 1
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
r b swpd free buff cache si so bi bo in cs us sy id wa
2 1 71184 156520 92524 316488 1 5 12 23 362 250 13 6 80 1
0 0 71184 156340 92528 316508 0 0 0 1 291 608 10 1 89 0
0 0 71184 156364 92528 316508 0 0 0 0 308 674 9 2 89 0
0 0 71184 156364 92532 316504 0 0 0 72 295 723 9 0 91 0
1 0 71184 150892 92532 316508 0 0 0 0 370 722 38 0 62 0
0 0 71184 163060 92532 316508 0 0 0 0 303 611 17 2 81 0
</pre>
<p>which will show you whether swap is hurting you (high numbers on si, so) and a more easier to see performance-over-time statistic.</p>
|
<p>by my reading of this, you have used almost all your memory, have 6 M free, and are going into about 10% of your swap. A more useful tools is to use top or perhaps ps to see how much each of your individual mongrels are using in RAM. Because you're going into swap, you're probably getting more slowdowns. you might find having only 2 mongrels rather than 3 might actually respond faster because it likely wouldn't go into swap memory.</p>
<p>Page caching will for sure help a tonne on response time, so if your pages are cachable (eg, they don't have content that is unique to the individual user) I would say for sure check it out</p>
| 29,385
|
<p>Is there any persistence solution for Common Lisp, such as Elephant, that allows function persistence? Currently my app stores an identifier on the db and later searches in a function table which it is, but this method does not allow dynamically created functions to be stored.</p>
|
<p>It's not a database persistence mechanism, but most Common Lisps have a way of <a href="http://www.franz.com/support/documentation/8.1/doc/operators/excl/fasl-write.htm" rel="nofollow noreferrer">writing FASLs</a> for all kinds of objects, including functions. For example:</p>
<pre><code>cl-user(1): (compile (defun hello () (format t "~&Hello~%")))
hello
nil
nil
cl-user(2): (excl:fasl-write (symbol-function 'hello) "/tmp/hello.fasl")
t
cl-user(3): (excl:fasl-read "/tmp/hello.fasl")
(#<Function hello @ #x1000a964d2>)
</code></pre>
<p>You can write to a stream (here I used a file for convenience), so you can trivially capture those bytes and stuff them into a database if you wished.</p>
|
<p>Be careful that storing code may not be that good. The Zope developers learned it the hard way.</p>
| 37,399
|
<pre><code>SELECT pe.prodtree_element_id prodID, pe.prodtree_element_name_s, li.line_name, av2.value
FROM prodtree_element pe
LEFT JOIN prodtree_link pl
ON pe.prodtree_element_id = pl.to_prodtree_node_id
LEFT JOIN line li
ON pe.line_code = li.line_code
INNER JOIN attribute_values av
ON av.attribute_definition_id = #statusCode#
LEFT JOIN attribute_values av2
ON pe.prodtree_element_id = av.prodtree_element_id
WHERE pe.prodtree_element_func_type <> 'WIZARD'
AND pe.prodtree_element_topo_type = 'NODE'
</code></pre>
<p>"#statusCode#" is a static id that matches an id in the attribute definition table (let's say 22 for the sake of argument). The problem is, the query has some massive trouble finishing in any sane amount of time. The bigger problem is, I kinda need it to finish earlier, but the number of records is enormous that it has to draw back (around 30-50,000). I need data from multiple tables, which is where it starts to slow down. This is just a piece of what I need, I also need an entire other tables worth of data matching the current "prodtree_elment_id".</p>
<p>I'm using ColdFusion but even running the query directly in SQL Server 2005 creates the 15-30+ minute wait for this query (if it even finishes). Is there any conceivable way to speed up this query to take at most 5 minutes or less?</p>
|
<pre><code>INNER JOIN attribute_values av
ON av.attribute_definition_id = #statusCode#
LEFT JOIN attribute_values av2
ON pe.prodtree_element_id = av.prodtree_element_id
</code></pre>
<p>This is the problem.
There is a cross join between pe and av, followed by an outer join onto the cross join.
You're lucky it only takes 30 mins :-)</p>
<p>I think you want this:</p>
<pre><code>SELECT pe.prodtree_element_id prodID, pe.prodtree_element_name_s, li.line_name, av2.value
FROM prodtree_element pe
LEFT JOIN prodtree_link pl
ON pe.prodtree_element_id = pl.to_prodtree_node_id
LEFT JOIN line li
ON pe.line_code = li.line_code
--replacement
LEFT JOIN
attribute_values av
ON pe.prodtree_element_id = av.prodtree_element_id AND
av.attribute_definition_id = #statusCode#
--end replacement
WHERE pe.prodtree_element_func_type <> 'WIZARD'
AND pe.prodtree_element_topo_type = 'NODE'
</code></pre>
|
<p>Without knowing the DDL its very hard to test. 30-50K rows should still take only a few seconds. </p>
<p>Try switching the where clause ordering.
You should probably have this implemented</p>
<pre><code> INNER JOIN attribute_values av
ON av.attribute_definition_id = #statusCode#
</code></pre>
<p>in the where clause. </p>
| 46,109
|
<p>I need to deploy a few .net dlls. They need to be put in the GAC and the required entries need to be in the registry. On my machine I have both the SDK and Visual Studio running, so currently I am utilizing .net sdk tools like gacutil and regasm. However, when I need to install these dlls on a customer machine, how should I go about it. Can I accomplish this by just having the .net runtime. I am currently using .net 2.0.</p>
|
<p>The 'proper' way to do this is using MSI (via one of the various ways of making MSI files - like WiX)</p>
<p>This might be useful to you:</p>
<p><a href="http://blogs.msdn.com/astebner/archive/2006/11/04/why-to-not-use-gacutil-exe-in-an-application-setup.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/astebner/archive/2006/11/04/why-to-not-use-gacutil-exe-in-an-application-setup.aspx</a></p>
|
<p>The most robust way would be to use your setup project. Open the File System view for the project, add the special folder "Global Assembly Cache", and add your assemblies to it, then build the setup project and you're good.</p>
<p>If you don't use a setup project, I don't really know...</p>
| 43,026
|
<p>Is there something like a panel that I can use in a MFC application. This is to overlay the default window in MFC (a dialog application). Then to paint the panel black and paint some random stuff on top of it. Something like a view port.</p>
<p>is there a better option than this to achieve the same effect ?</p>
|
<p>Sure. It's called a window! Create a class that derives from CWnd and overrides OnPaint().</p>
<p>In your dialog's OnInitInstance(), instantiate a CMyWnd object and call it's Create() member. Of course, make sure the lifetime of your CMyWnd object is the same as the dialog's object lifetime window. iow, make it a member of you CMyDialog class.</p>
<p>Not very complicated but obviously an area where MFC shows why it doesn't fall in the RAD tools category.</p>
|
<p>Another solution would be to derive from <code>CDialog</code>. This way you can use the resource editor to edit the panel visually and you don't need to paint anything yourselve. Also the Panel class is rather thin and just needs to propagate the <code>Create()</code> and <code>Show()</code> calls to support subpanels and multiple panels within a single form.</p>
| 30,320
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.