qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
23,802 | <p>I'm wondering what the best practice is for handling the problem with having to "include" so many files in my PHP scripts in order to ensure that all the classes I need to use are accessible to my script. </p>
<p>Currently, I'm just using <a href="http://php.net/manual/en/function.include-once.php" rel="nofollow noreferrer">include_once</a> to include the classes I access directly. Each of those would <code>include_once</code> the classes that they access. </p>
<p>I've looked into using the <code>__autoload</code> function, but hat doesn't seem to work well if you plan to have your class files organized in a directory tree. If you did this, it seems like you'd end up walking the directory tree until you found the class you were looking for. <strong><em>Also, I'm not sure how this effects classes with the same name in different namespaces.</em></strong> </p>
<p><strong>Is there an easier way to handle this?</strong> </p>
<p>Or is PHP just not suited to "<strong>enterprisey</strong>" type applications with lots of different objects all located in separate files that can be in many different directories.</p>
| [
{
"answer_id": 23805,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p><code>__autoload</code> works well if you have a consistent naming convention for your classes that tell the functi... | 2008/08/23 | [
"https://Stackoverflow.com/questions/23802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862/"
] | I'm wondering what the best practice is for handling the problem with having to "include" so many files in my PHP scripts in order to ensure that all the classes I need to use are accessible to my script.
Currently, I'm just using [include\_once](http://php.net/manual/en/function.include-once.php) to include the classes I access directly. Each of those would `include_once` the classes that they access.
I've looked into using the `__autoload` function, but hat doesn't seem to work well if you plan to have your class files organized in a directory tree. If you did this, it seems like you'd end up walking the directory tree until you found the class you were looking for. ***Also, I'm not sure how this effects classes with the same name in different namespaces.***
**Is there an easier way to handle this?**
Or is PHP just not suited to "**enterprisey**" type applications with lots of different objects all located in separate files that can be in many different directories. | I my applications I usually have `setup.php` file that includes all core classes (i.e. framework and accompanying libraries). My custom classes are loaded using autoloader aided by directory layout map.
Each time new class is added I run command line builder script that scans whole directory tree in search for model classes then builds associative array with class names as keys and paths as values. Then, \_\_autoload function looks up class name in that array and gets include path. Here's the code:
**autobuild.php**
```
define('MAP', 'var/cache/autoload.map');
error_reporting(E_ALL);
require 'setup.php';
print(buildAutoloaderMap() . " classes mapped\n");
function buildAutoloaderMap() {
$dirs = array('lib', 'view', 'model');
$cache = array();
$n = 0;
foreach ($dirs as $dir) {
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $entry) {
$fn = $entry->getFilename();
if (!preg_match('/\.class\.php$/', $fn))
continue;
$c = str_replace('.class.php', '', $fn);
if (!class_exists($c)) {
$cache[$c] = ($pn = $entry->getPathname());
++$n;
}
}
}
ksort($cache);
file_put_contents(MAP, serialize($cache));
return $n;
}
```
**autoload.php**
```
define('MAP', 'var/cache/autoload.map');
function __autoload($className) {
static $map;
$map or ($map = unserialize(file_get_contents(MAP)));
$fn = array_key_exists($className, $map) ? $map[$className] : null;
if ($fn and file_exists($fn)) {
include $fn;
unset($map[$className]);
}
}
```
Note that file naming convention must be [class\_name].class.php. Alter the directories classes will be looked in `autobuild.php`. You can also run autobuilder from autoload function when class not found, but that may get your program into infinite loop.
Serialized arrays are darn fast.
@JasonMichael: PHP 4 is dead. Get over it. |
23,853 | <p>I am using Struts + Velocity in a Java application, but after I submit a form, the confirmation page (Velocity template) shows the variable names instead an empty label, like the Age in following example:</p>
<blockquote>
<p><strong>Name</strong>: Fernando</p>
<p><strong>Age</strong>: {person.age}</p>
<p><strong>Sex</strong>: Male</p>
</blockquote>
<p>I would like to know how to hide it!</p>
| [
{
"answer_id": 23879,
"author": "Jason Sparks",
"author_id": 512,
"author_profile": "https://Stackoverflow.com/users/512",
"pm_score": 7,
"selected": true,
"text": "<p>You can mark variables as \"<a href=\"https://velocity.apache.org/engine/1.5/user-guide.html#quietreferencenotation\" re... | 2008/08/23 | [
"https://Stackoverflow.com/questions/23853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274/"
] | I am using Struts + Velocity in a Java application, but after I submit a form, the confirmation page (Velocity template) shows the variable names instead an empty label, like the Age in following example:
>
> **Name**: Fernando
>
>
> **Age**: {person.age}
>
>
> **Sex**: Male
>
>
>
I would like to know how to hide it! | You can mark variables as "[silent](https://velocity.apache.org/engine/1.5/user-guide.html#quietreferencenotation)" like this:
```
$!variable
```
If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would. |
23,867 | <p>The <code>Close</code> method on an <code>ICommunicationObject</code> can throw two types of exceptions as MSDN outlines <a href="http://msdn.microsoft.com/en-us/library/ms195520.aspx" rel="nofollow noreferrer">here</a>. I understand why the <code>Close</code> method can throw those exceptions, but what I don't understand is why the <code>Dispose</code> method on a service proxy calls the <code>Close</code> method without a <code>try</code> around it. Isn't your <code>Dispose</code> method the one place where you want make sure you don't throw any exceptions?</p>
| [
{
"answer_id": 23879,
"author": "Jason Sparks",
"author_id": 512,
"author_profile": "https://Stackoverflow.com/users/512",
"pm_score": 7,
"selected": true,
"text": "<p>You can mark variables as \"<a href=\"https://velocity.apache.org/engine/1.5/user-guide.html#quietreferencenotation\" re... | 2008/08/23 | [
"https://Stackoverflow.com/questions/23867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] | The `Close` method on an `ICommunicationObject` can throw two types of exceptions as MSDN outlines [here](http://msdn.microsoft.com/en-us/library/ms195520.aspx). I understand why the `Close` method can throw those exceptions, but what I don't understand is why the `Dispose` method on a service proxy calls the `Close` method without a `try` around it. Isn't your `Dispose` method the one place where you want make sure you don't throw any exceptions? | You can mark variables as "[silent](https://velocity.apache.org/engine/1.5/user-guide.html#quietreferencenotation)" like this:
```
$!variable
```
If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would. |
23,907 | <p>Basically I want to get the number of lines-of-code in the repository after each commit.</p>
<p>The only (really crappy) ways I have found is to use <code>git filter-branch</code> to run <code>wc -l *</code>, and a script that runs <code>git reset --hard</code> on each commit, then runs <code>wc -l</code></p>
<p>To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on. This is what I want the tool to output (as an example):</p>
<pre class="lang-none prettyprint-override"><code>me@something:~/$ gitsloc --branch master
10
48
153
450
1734
1542
</code></pre>
<p>I've played around with the ruby 'git' library, but the closest I found was using the <code>.lines()</code> method on a diff, which seems like it should give the added lines (but does not: it returns 0 when you delete lines for example)</p>
<pre class="lang-rb prettyprint-override"><code>require 'rubygems'
require 'git'
total = 0
g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api')
last = nil
g.log.each do |cur|
diff = g.diff(last, cur)
total = total + diff.lines
puts total
last = cur
end
</code></pre>
| [
{
"answer_id": 24190,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>The first thing that jumps to mind is the possibility of your git history having a nonlinear history. You might have di... | 2008/08/23 | [
"https://Stackoverflow.com/questions/23907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] | Basically I want to get the number of lines-of-code in the repository after each commit.
The only (really crappy) ways I have found is to use `git filter-branch` to run `wc -l *`, and a script that runs `git reset --hard` on each commit, then runs `wc -l`
To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on. This is what I want the tool to output (as an example):
```none
me@something:~/$ gitsloc --branch master
10
48
153
450
1734
1542
```
I've played around with the ruby 'git' library, but the closest I found was using the `.lines()` method on a diff, which seems like it should give the added lines (but does not: it returns 0 when you delete lines for example)
```rb
require 'rubygems'
require 'git'
total = 0
g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api')
last = nil
g.log.each do |cur|
diff = g.diff(last, cur)
total = total + diff.lines
puts total
last = cur
end
``` | You might also consider [gitstats](http://gitstats.sourceforge.net/), which generates this graph as an html file. |
23,918 | <p>I'm trying to do a simple rotation in OpenGL but must be missing the point.
I'm not looking for a specific fix so much as a quick explanation or link that explains OpenGL rotation more generally.</p>
<p>At the moment I have code like this:</p>
<pre><code>glPushMatrix();
glRotatef(90.0, 0.0, 1.0, 0.0);
glBegin(GL_TRIANGLES);
glVertex3f( 1.0, 1.0, 0.0 );
glVertex3f( 3.0, 2.0, 0.0 );
glVertex3f( 3.0, 1.0, 0.0 );
glEnd();
glPopMatrix();
</code></pre>
<p>But the result is not a triangle rotated 90 degrees.</p>
<p><strong>Edit</strong>
Hmm thanks to Mike Haboustak - it appeared my code was calling a SetCamera function that use glOrtho. I'm too new to OpenGL to have any idea of what this meant but disabling this and rotating in the Z-axis produced the desired result. </p>
| [
{
"answer_id": 23925,
"author": "spate",
"author_id": 2276,
"author_profile": "https://Stackoverflow.com/users/2276",
"pm_score": 3,
"selected": false,
"text": "<p>Ensure that you're modifying the modelview matrix by putting the following before the glRotatef call:</p>\n\n<pre><code>glMa... | 2008/08/23 | [
"https://Stackoverflow.com/questions/23918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I'm trying to do a simple rotation in OpenGL but must be missing the point.
I'm not looking for a specific fix so much as a quick explanation or link that explains OpenGL rotation more generally.
At the moment I have code like this:
```
glPushMatrix();
glRotatef(90.0, 0.0, 1.0, 0.0);
glBegin(GL_TRIANGLES);
glVertex3f( 1.0, 1.0, 0.0 );
glVertex3f( 3.0, 2.0, 0.0 );
glVertex3f( 3.0, 1.0, 0.0 );
glEnd();
glPopMatrix();
```
But the result is not a triangle rotated 90 degrees.
**Edit**
Hmm thanks to Mike Haboustak - it appeared my code was calling a SetCamera function that use glOrtho. I'm too new to OpenGL to have any idea of what this meant but disabling this and rotating in the Z-axis produced the desired result. | Do you get a 1 unit straight line? It seems that 90deg rot. around Y is going to have you looking at the side of a triangle with no depth.
You should try rotating around the Z axis instead and see if you get something that makes more sense.
OpenGL has two matrices related to the display of geometry, the ModelView and the Projection. Both are applied to coordinates before the data becomes visible on the screen. First the ModelView matrix is applied, transforming the data from model space into view space. Then the Projection matrix is applied with transforms the data from view space for "projection" on your 2D monitor.
ModelView is used to position multiple objects to their locations in the "world", Projection is used to position the objects onto the screen.
Your code seems fine, so I assume from reading the documentation you know what the nature of functions like glPushMatrix() is. If rotating around Z still doesn't make sense, verify that you're editing the ModelView matrix by calling glMatrixMode. |
23,930 | <p>I want to see all the different ways you can come up with, for a factorial subroutine, or program. The hope is that anyone can come here and see if they might want to learn a new language.</p>
<h2>Ideas:</h2>
<ul>
<li>Procedural</li>
<li>Functional</li>
<li>Object Oriented</li>
<li>One liners</li>
<li>Obfuscated</li>
<li>Oddball</li>
<li>Bad Code</li>
<li><a href="http://en.wikipedia.org/wiki/Polyglot_%28computing%29" rel="nofollow noreferrer">Polyglot</a></li>
</ul>
<p>Basically I want to see an example, of different ways of writing an algorithm, and what they would look like in different languages.</p>
<p>Please limit it to one example per entry.
I will allow you to have more than one example per answer, if you are trying to highlight a specific style, language, or just a well thought out idea that lends itself to being in one post.</p>
<p>The only real requirement is it must find the factorial of a given argument, in all languages represented.</p>
<h1>Be Creative!</h1>
<h2>Recommended Guideline:</h2>
<pre>
# Language Name: Optional Style type
- Optional bullet points
Code Goes Here
Other informational text goes here
</pre>
<p>I will ocasionally go along and edit any answer that does not have decent formatting.</p>
| [
{
"answer_id": 23932,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 2,
"selected": false,
"text": "<h1>Perl 6: Functional</h1>\n\n<pre><code>multi factorial ( Int $n where { $n <= 0 } ){\n return 1;\n}\nmulti factor... | 2008/08/23 | [
"https://Stackoverflow.com/questions/23930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1337/"
] | I want to see all the different ways you can come up with, for a factorial subroutine, or program. The hope is that anyone can come here and see if they might want to learn a new language.
Ideas:
------
* Procedural
* Functional
* Object Oriented
* One liners
* Obfuscated
* Oddball
* Bad Code
* [Polyglot](http://en.wikipedia.org/wiki/Polyglot_%28computing%29)
Basically I want to see an example, of different ways of writing an algorithm, and what they would look like in different languages.
Please limit it to one example per entry.
I will allow you to have more than one example per answer, if you are trying to highlight a specific style, language, or just a well thought out idea that lends itself to being in one post.
The only real requirement is it must find the factorial of a given argument, in all languages represented.
Be Creative!
============
Recommended Guideline:
----------------------
```
# Language Name: Optional Style type
- Optional bullet points
Code Goes Here
Other informational text goes here
```
I will ocasionally go along and edit any answer that does not have decent formatting. | Polyglot: 5 languages, all using bignums
========================================
So, I wrote a polyglot which works in the three languages I often write in, as well as one from my other answer to this question and one I just learned today. It's a standalone program, which reads a single line containing a nonnegative integer and prints a single line containing its factorial. Bignums are used in all languages, so the maximum computable factorial depends only on your computer's resources.
* **Perl**: uses built-in bignum package. Run with `perl FILENAME`.
* **Haskell**: uses built-in bignums. Run with `runhugs FILENAME` or your favorite compiler's equivalent.
* **C++**: requires GMP for bignum support. To compile with g++, use `g++ -lgmpxx -lgmp -x c++ FILENAME` to link against the right libraries. After compiling, run `./a.out`. Or use your favorite compiler's equivalent.
* **brainf\*ck**: I wrote some bignum support in [this post](https://stackoverflow.com/questions/23930/factorial-algorithms-in-different-languages/432010#432010). Using [Muller's classic distribution](http://aminet.net/package.php?package=dev/lang/brainfuck-2.lha), compile with `bf < FILENAME > EXECUTABLE`. Make the output executable and run it. Or use your favorite distribution.
* **Whitespace**: uses built-in bignum support. Run with `wspace FILENAME`.
*Edit:* added Whitespace as a fifth language. Incidentally, do *not* wrap the code with `<code>` tags; it breaks the Whitespace. Also, the code looks much nicer in fixed-width.
```
char //# b=0+0{- |0*/; #>>>>,----------[>>>>,--------
#define a/*#--]>>>>++<<<<<<<<[>++++++[<------>-]<-<<<
#Perl ><><><> <> <> <<]>>>>[[>>+<<-]>>[<<+>+>-]<->
#C++ --><><> <><><>< > < > < +<[>>>>+<<<-<[-]]>[-]
#Haskell >>]>[-<<<<<[<<<<]>>>>[[>>+<<-]>>[<<+>+>-]>>]
#Whitespace >>>>[-[>+<-]+>>>>]<<<<[<<<<]<<<<[<<<<
#brainf*ck > < ]>>>>>[>>>[>>>>]>>>>[>>>>]<<<<[[>>>>*/
exp; ;//;#+<<<<-]<<<<]>>>>+<<<<<<<[<<<<][.POLYGLOT^5.
#include <gmpxx.h>//]>>>>-[>>>[>>>>]>>>>[>>>>]<<<<[>>
#define eval int main()//>+<<<-]>>>[<<<+>>+>->
#include <iostream>//<]<-[>>+<<[-]]<<[<<<<]>>>>[>[>>>
#define print std::cout << // > <+<-]>[<<+>+>-]<<[>>>
#define z std::cin>>//<< +<<<-]>>>[<<<+>>+>-]<->+++++
#define c/*++++[-<[-[>>>>+<<<<-]]>>>>[<<<<+>>>>-]<<*/
#define abs int $n //>< <]<[>>+<<<<[-]>>[<<+>>-]]>>]<
#define uc mpz_class fact(int $n){/*<<<[<<<<]<<<[<<
use bignum;sub#<<]>>>>-]>>>>]>>>[>[-]>>>]<<<<[>>+<<-]
z{$_[0+0]=readline(*STDIN);}sub fact{my($n)=shift;#>>
#[<<+>+>-]<->+<[>-<[-]]>[-<<-<<<<[>>+<<-]>>[<<+>+>+*/
uc;if($n==0){return 1;}return $n*fact($n-1); }//;#
eval{abs;z($n);print fact($n);print("\n")/*2;};#-]<->
'+<[>-<[-]]>]<<[<<<<]<<<<-[>>+<<-]>>[<<+>+>-]+<[>-+++
-}-- <[-]]>[-<<++++++++++<<<<-[>>+<<-]>>[<<+>+>-++
fact 0 = 1 -- ><><><>< > <><>< ]+<[>-<[-]]>]<<[<<+ +
fact n=n*fact(n-1){-<<]>>>>[[>>+<<-]>>[<<+>+++>+-}
main=do{n<-readLn;print(fact n)}-- +>-]<->+<[>>>>+<<+
{-x<-<[-]]>[-]>>]>]>>>[>>>>]<<<<[>+++++++[<+++++++>-]
<--.<<<<]+written+by+++A+Rex+++2009+.';#+++x-}--x*/;}
``` |
23,931 | <p>Given two different image files (in whatever format I choose), I need to write a program to predict the chance if one being the illegal copy of another. The author of the copy may do stuff like rotating, making negative, or adding trivial details (as well as changing the dimension of the image).</p>
<p>Do you know any algorithm to do this kind of job?</p>
| [
{
"answer_id": 23946,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 5,
"selected": false,
"text": "<p>Read the paper: <a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.81.3347&rep=rep1&type=pdf\" rel=\"... | 2008/08/23 | [
"https://Stackoverflow.com/questions/23931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Given two different image files (in whatever format I choose), I need to write a program to predict the chance if one being the illegal copy of another. The author of the copy may do stuff like rotating, making negative, or adding trivial details (as well as changing the dimension of the image).
Do you know any algorithm to do this kind of job? | These are simply ideas I've had thinking about the problem, never tried it but I like thinking about problems like this!
**Before you begin**
Consider normalising the pictures, if one is a higher resolution than the other, consider the option that one of them is a compressed version of the other, therefore scaling the resolution down might provide more accurate results.
Consider scanning various prospective areas of the image that could represent zoomed portions of the image and various positions and rotations. It starts getting tricky if one of the images are a skewed version of another, these are the sort of limitations you should identify and compromise on.
[Matlab](https://www.mathworks.com/) is an excellent tool for testing and evaluating images.
**Testing the algorithms**
You should test (at the minimum) a large human analysed set of test data where matches are known beforehand. If for example in your test data you have 1,000 images where 5% of them match, you now have a reasonably reliable benchmark. An algorithm that finds 10% positives is not as good as one that finds 4% of positives in our test data. However, one algorithm may find all the matches, but also have a large 20% false positive rate, so there are several ways to rate your algorithms.
The test data should attempt to be designed to cover as many types of dynamics as possible that you would expect to find in the real world.
It is important to note that each algorithm to be useful must perform better than random guessing, otherwise it is useless to us!
You can then apply your software into the real world in a controlled way and start to analyse the results it produces. This is the sort of software project which can go on for infinitum, there are always tweaks and improvements you can make, it is important to bear that in mind when designing it as it is easy to fall into the trap of the never ending project.
**Colour Buckets**
With two pictures, scan each pixel and count the colours. For example you might have the 'buckets':
```
white
red
blue
green
black
```
(Obviously you would have a higher resolution of counters). Every time you find a 'red' pixel, you increment the red counter. Each bucket can be representative of spectrum of colours, the higher resolution the more accurate but you should experiment with an acceptable difference rate.
Once you have your totals, compare it to the totals for a second image. You might find that each image has a fairly unique footprint, enough to identify matches.
**Edge detection**
How about using [Edge Detection](https://en.wikipedia.org/wiki/Edge_detection).
[](https://i.stack.imgur.com/mY9PV.png)
(source: [wikimedia.org](http://upload.wikimedia.org/wikipedia/en/thumb/8/8e/EdgeDetectionMathematica.png/500px-EdgeDetectionMathematica.png))
With two similar pictures edge detection should provide you with a usable and fairly reliable unique footprint.
Take both pictures, and apply edge detection. Maybe measure the average thickness of the edges and then calculate the probability the image could be scaled, and rescale if necessary. Below is an example of an applied [Gabor Filter](https://en.wikipedia.org/wiki/Gabor_filter) (a type of edge detection) in various rotations.

Compare the pictures pixel for pixel, count the matches and the non matches. If they are within a certain threshold of error, you have a match. Otherwise, you could try reducing the resolution up to a certain point and see if the probability of a match improves.
**Regions of Interest**
Some images may have distinctive segments/regions of interest. These regions probably contrast highly with the rest of the image, and are a good item to search for in your other images to find matches. Take this image for example:
[](https://i.stack.imgur.com/Sgg79.jpg)
(source: [meetthegimp.org](http://meetthegimp.org/wp-content/uploads/2009/04/97.jpg))
The construction worker in blue is a region of interest and can be used as a search object. There are probably several ways you could extract properties/data from this region of interest and use them to search your data set.
If you have more than 2 regions of interest, you can measure the distances between them. Take this simplified example:
[](https://i.stack.imgur.com/z7U80.jpg)
(source: [per2000.eu](http://www.per2000.eu/assets/images/3_dots_black_03.jpg))
We have 3 clear regions of interest. The distance between region 1 and 2 may be 200 pixels, between 1 and 3 400 pixels, and 2 and 3 200 pixels.
Search other images for similar regions of interest, normalise the distance values and see if you have potential matches. This technique could work well for rotated and scaled images. The more regions of interest you have, the probability of a match increases as each distance measurement matches.
It is important to think about the context of your data set. If for example your data set is modern art, then regions of interest would work quite well, as regions of interest were probably *designed* to be a fundamental part of the final image. If however you are dealing with images of construction sites, regions of interest may be interpreted by the illegal copier as ugly and may be cropped/edited out liberally. Keep in mind common features of your dataset, and attempt to exploit that knowledge.
**Morphing**
[Morphing](https://en.wikipedia.org/wiki/Morphing) two images is the process of turning one image into the other through a set of steps:

Note, this is different to fading one image into another!
There are many software packages that can morph images. It's traditionaly used as a transitional effect, two images don't morph into something halfway usually, one extreme morphs into the other extreme as the final result.
Why could this be useful? Dependant on the morphing algorithm you use, there may be a relationship between similarity of images, and some parameters of the morphing algorithm.
In a grossly over simplified example, one algorithm might execute faster when there are less changes to be made. We then know there is a higher probability that these two images share properties with each other.
This technique *could* work well for rotated, distorted, skewed, zoomed, all types of copied images. Again this is just an idea I have had, it's not based on any researched academia as far as I am aware (I haven't look hard though), so it may be a lot of work for you with limited/no results.
**Zipping**
Ow's answer in this question is excellent, I remember reading about these sort of techniques studying AI. It is quite effective at comparing corpus lexicons.
One interesting optimisation when comparing corpuses is that you can remove words considered to be too common, for example 'The', 'A', 'And' etc. These words dilute our result, we want to work out how different the two corpus are so these can be removed before processing. Perhaps there are similar common signals in images that could be stripped before compression? It might be worth looking into.
Compression ratio is a very quick and reasonably effective way of determining how similar two sets of data are. Reading up about [how compression works](https://computer.howstuffworks.com/file-compression.htm) will give you a good idea why this could be so effective. For a fast to release algorithm this would probably be a good starting point.
**Transparency**
Again I am unsure how transparency data is stored for certain image types, gif png etc, but this will be extractable and would serve as an effective simplified cut out to compare with your data sets transparency.
**Inverting Signals**
An image is just a signal. If you play a noise from a speaker, and you play the opposite noise in another speaker in perfect sync at the exact same volume, they cancel each other out.
[](https://i.stack.imgur.com/Jq3kQ.gif)
(source: [themotorreport.com.au](http://www.themotorreport.com.au/wp-content/uploads/2008/07/noise-cancellation.gif))
Invert on of the images, and add it onto your other image. Scale it/loop positions repetitively until you find a resulting image where enough of the pixels are white (or black? I'll refer to it as a neutral canvas) to provide you with a positive match, or partial match.
However, consider two images that are equal, except one of them has a brighten effect applied to it:
[](https://i.stack.imgur.com/24hiI.jpg)
(source: [mcburrz.com](https://www.mcburrz.com/images/photo/brighten.jpg))
Inverting one of them, then adding it to the other will not result in a neutral canvas which is what we are aiming for. However, when comparing the pixels from both original images, we can definatly see a clear relationship between the two.
I haven't studied colour for some years now, and am unsure if the colour spectrum is on a linear scale, but if you determined the average factor of colour difference between both pictures, you can use this value to normalise the data before processing with this technique.
**Tree Data structures**
At first these don't seem to fit for the problem, but I think they could work.
You could think about extracting certain properties of an image (for example colour bins) and generate a [huffman tree](https://en.wikipedia.org/wiki/Huffman_coding) or similar data structure. You might be able to compare two trees for similarity. This wouldn't work well for photographic data for example with a large spectrum of colour, but cartoons or other reduced colour set images this might work.
This probably wouldn't work, but it's an idea. The [trie datastructure](https://en.wikipedia.org/wiki/Trie) is great at storing lexicons, for example a dictionarty. It's a prefix tree. Perhaps it's possible to build an image equivalent of a lexicon, (again I can only think of colours) to construct a trie. If you reduced say a 300x300 image into 5x5 squares, then decompose each 5x5 square into a sequence of colours you could construct a trie from the resulting data. If a 2x2 square contains:
```
FFFFFF|000000|FDFD44|FFFFFF
```
We have a fairly unique trie code that extends 24 levels, increasing/decreasing the levels (IE reducing/increasing the size of our sub square) may yield more accurate results.
Comparing trie trees should be reasonably easy, and could possible provide effective results.
**More ideas**
I stumbled accross an interesting paper breif about [classification of satellite imagery](https://ieeexplore.ieee.org/document/387577/?arnumber=387577), it outlines:
>
> Texture measures considered are: cooccurrence matrices, gray-level differences, texture-tone analysis, features derived from the Fourier spectrum, and Gabor filters. Some Fourier features and some Gabor filters were found to be good choices, in particular when a single frequency band was used for classification.
>
>
>
It may be worth investigating those measurements in more detail, although some of them may not be relevant to your data set.
**Other things to consider**
There are probably a lot of papers on this sort of thing, so reading some of them should help although they can be very technical. It is an extremely difficult area in computing, with many fruitless hours of work spent by many people attempting to do similar things. Keeping it simple and building upon those ideas would be the best way to go. It should be a reasonably difficult challenge to create an algorithm with a better than random match rate, and to start improving on that really does start to get quite hard to achieve.
Each method would probably need to be tested and tweaked thoroughly, if you have any information about the type of picture you will be checking as well, this would be useful. For example advertisements, many of them would have text in them, so doing text recognition would be an easy and probably very reliable way of finding matches especially when combined with other solutions. As mentioned earlier, attempt to exploit common properties of your data set.
Combining alternative measurements and techniques each that can have a weighted vote (dependant on their effectiveness) would be one way you could create a system that generates more accurate results.
If employing multiple algorithms, as mentioned at the begining of this answer, one may find all the positives but have a false positive rate of 20%, it would be of interest to study the properties/strengths/weaknesses of other algorithms as another algorithm may be effective in eliminating false positives returned from another.
Be careful to not fall into attempting to complete the never ending project, good luck! |
23,962 | <p>For example,
Look at the code that calculates the n-th Fibonacci number:</p>
<pre><code>fib(int n)
{
if(n==0 || n==1)
return 1;
return fib(n-1) + fib(n-2);
}
</code></pre>
<p>The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers).</p>
<p>Assume that we are calculating fib(10). In this process, say fib(5) is calculated a lot of times. Is there some way to store this in memory for fast retrieval and thereby increase the speed of recursion?</p>
<p>I am looking for a generic technique that can be used in almost all problems.</p>
| [
{
"answer_id": 23964,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 1,
"selected": false,
"text": "<p>Try using a map, n is the key and its corresponding Fibonacci number is the value.</p>\n<p>@Paul</p>\n<p>Thanks for the info. I ... | 2008/08/23 | [
"https://Stackoverflow.com/questions/23962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | For example,
Look at the code that calculates the n-th Fibonacci number:
```
fib(int n)
{
if(n==0 || n==1)
return 1;
return fib(n-1) + fib(n-2);
}
```
The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers).
Assume that we are calculating fib(10). In this process, say fib(5) is calculated a lot of times. Is there some way to store this in memory for fast retrieval and thereby increase the speed of recursion?
I am looking for a generic technique that can be used in almost all problems. | Yes your insight is correct.
This is called [dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming). It is usually a common memory runtime trade-off.
In the case of fibo, you don't even need to cache everything :
[edit]
The author of the question seems to be looking for a general method to cache rather than a method to compute Fibonacci. Search wikipedia or look at the code of the other poster to get this answer. Those answers are linear in time and memory.
\*\*Here is a linear-time algorithm O(n), constant in memory \*\*
```
in OCaml:
let rec fibo n =
let rec aux = fun
| 0 -> (1,1)
| n -> let (cur, prec) = aux (n-1) in (cur+prec, cur)
let (cur,prec) = aux n in prec;;
in C++:
int fibo(int n) {
if (n == 0 ) return 1;
if (n == 1 ) return 1;
int p = fibo(0);
int c = fibo(1);
int buff = 0;
for (int i=1; i < n; ++i) {
buff = c;
c = p+c;
p = buff;
};
return c;
};
```
This perform in linear time. But log is actually possible !!!
Roo's program is linear too, but way slower, and use memory.
**Here is the log algorithm O(log(n))**
Now for the log-time algorithm (way way way faster), here is a method :
If you know u(n), u(n-1), computing u(n+1), u(n) can be done by applying a matrix:
```
| u(n+1) | = | 1 1 | | u(n) |
| u(n) | | 1 0 | | u(n-1) |
```
So that you have :
```
| u(n) | = | 1 1 |^(n-1) | u(1) | = | 1 1 |^(n-1) | 1 |
| u(n-1) | | 1 0 | | u(0) | | 1 0 | | 1 |
```
Computing the exponential of the matrix has a logarithmic complexity.
Just implement recursively the idea :
```
M^(0) = Id
M^(2p+1) = (M^2p) * M
M^(2p) = (M^p) * (M^p) // of course don't compute M^p twice here.
```
You can also just diagonalize it (not to difficult), you will find the gold number and its conjugate in its eigenvalue, and the result will give you an EXACT mathematical formula for u(n). It contains powers of those eigenvalues, so that the complexity will still be logarithmic.
*Fibo is often taken as an example to illustrate Dynamic Programming, but as you see, it is not really pertinent.*
@John:
I don't think it has anything to do with do with hash.
@John2:
A map is a bit general don't you think? For Fibonacci case, all the keys are contiguous so that a vector is appropriate, once again there are much faster ways to compute fibo sequence, see my code sample over there. |
23,970 | <p>Joe Van Dyk <a href="http://www.zenspider.com/pipermail/ruby/2008-August/004223.html" rel="noreferrer">asked the Ruby mailing list</a>:</p>
<blockquote>
<p>Hi,</p>
<p>In Ruby, I guess you can't marshal a lambda/proc object, right? Is
that possible in lisp or other languages?</p>
<p>What I was trying to do:</p>
</blockquote>
<pre><code>l = lamda { ... }
Bj.submit "/path/to/ruby/program", :stdin => Marshal.dump(l)
</code></pre>
<blockquote>
<p>So, I'm sending BackgroundJob a lambda object, which contains the
context/code for what to do. But, guess that wasn't possible. I
ended up marshaling a normal ruby object that contained instructions
for what to do after the program ran.</p>
<p>Joe</p>
</blockquote>
| [
{
"answer_id": 23974,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<p>Try <a href=\"http://seattlerb.rubyforge.org/ruby2ruby/\" rel=\"nofollow noreferrer\">ruby2ruby</a></p>\n"
},
{... | 2008/08/23 | [
"https://Stackoverflow.com/questions/23970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | Joe Van Dyk [asked the Ruby mailing list](http://www.zenspider.com/pipermail/ruby/2008-August/004223.html):
>
> Hi,
>
>
> In Ruby, I guess you can't marshal a lambda/proc object, right? Is
> that possible in lisp or other languages?
>
>
> What I was trying to do:
>
>
>
```
l = lamda { ... }
Bj.submit "/path/to/ruby/program", :stdin => Marshal.dump(l)
```
>
> So, I'm sending BackgroundJob a lambda object, which contains the
> context/code for what to do. But, guess that wasn't possible. I
> ended up marshaling a normal ruby object that contained instructions
> for what to do after the program ran.
>
>
> Joe
>
>
> | You cannot marshal a Lambda or Proc. This is because both of them are considered closures, which means they close around the memory on which they were defined and can reference it. (In order to marshal them you'd have to Marshal all of the memory they could access at the time they were created.)
As Gaius pointed out though, you can use [ruby2ruby](https://github.com/seattlerb/ruby2ruby) to get a hold of the string of the program. That is, you can marshal the string that represents the ruby code and then reevaluate it later. |
23,996 | <p>I'm working with <a href="http://webby.rubyforge.org" rel="nofollow noreferrer" title="Webby">Webby</a> and am looking for some clarification. Can I define attributes like <code>title</code> or <code>author</code> in my layout?</p>
| [
{
"answer_id": 24010,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://webby.rubyforge.org/tutorial/\" rel=\"nofollow noreferrer\">I've never used it but the tutorial here:</a></p... | 2008/08/23 | [
"https://Stackoverflow.com/questions/23996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2165/"
] | I'm working with [Webby](http://webby.rubyforge.org "Webby") and am looking for some clarification. Can I define attributes like `title` or `author` in my layout? | Not really. The layout has access to the page attributes rather than the other way.
The easiest way to do what you want is to populate the SITE.page\_defaults hash in your site's Rakefile (probably build.rake). Add something like the following:
```
SITE.page_defaults['title'] = "My awesome title"
SITE.page_defaults['author'] = "Shazbug"
SITE.page_defaults['is_mando_awesome'] = "very yes"
```
You can now access those hash members in your template:
```
Written by <%= @page.author %>
```
You can find more info about Webby's page default stuff on the Google Group, specifically here:
<http://groups.google.com/group/webby-forum/browse_thread/thread/f3dc1f4187959634/c30d7883705f6218?lnk=gst&q=SITE#c30d7883705f6218> |
24,046 | <p>I do some minor programming and web work for a local community college. Work that includes maintaining a very large and soul destroying website that consists of a hodge podge of VBScript, javascript, Dreamweaver generated cruft and a collection of add-ons that various conmen have convinced them to buy over the years. </p>
<p>A few days ago I got a call "The website is locking up for people using Safari!" Okay, step one download Safari(v3.1.2), step two surf to the site. Everything appears to work fine.</p>
<p>Long story short I finally isolated the problem and it relates to Safari's back button. The website uses a fancy-pants javascript menu that works in every browser I've tried including Safari, the first time around. But in Safari if you follow a link off the page and then hit the back button the menu no longer works.</p>
<p>I made a pared down webpage to illustrate the principle.</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title>Safari Back Button Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body onload="alert('Hello');">
<a href="http://www.codinghorror.com">Coding Horror</a>
</body>
</html>
</code></pre>
<p>Load the page and you see the alert box. Then follow the link off the page and hit the back button. In IE and Firefox you see the alert box again, in Safari you do not.</p>
<p>After a vigorous googling I've discovered others with similar problems but no really satisfactory answers. So my question is how can I make my pages work the same way in Safari after the user hits the back button as they do in other browsers?</p>
<p>If this is a stupid question please be gentle, javascript is somewhat new to me.</p>
| [
{
"answer_id": 24049,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 2,
"selected": false,
"text": "<p>I have no idea what's causing the problem but I know who might be able to help you. Safari is built on <a href=\"htt... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2051/"
] | I do some minor programming and web work for a local community college. Work that includes maintaining a very large and soul destroying website that consists of a hodge podge of VBScript, javascript, Dreamweaver generated cruft and a collection of add-ons that various conmen have convinced them to buy over the years.
A few days ago I got a call "The website is locking up for people using Safari!" Okay, step one download Safari(v3.1.2), step two surf to the site. Everything appears to work fine.
Long story short I finally isolated the problem and it relates to Safari's back button. The website uses a fancy-pants javascript menu that works in every browser I've tried including Safari, the first time around. But in Safari if you follow a link off the page and then hit the back button the menu no longer works.
I made a pared down webpage to illustrate the principle.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title>Safari Back Button Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body onload="alert('Hello');">
<a href="http://www.codinghorror.com">Coding Horror</a>
</body>
</html>
```
Load the page and you see the alert box. Then follow the link off the page and hit the back button. In IE and Firefox you see the alert box again, in Safari you do not.
After a vigorous googling I've discovered others with similar problems but no really satisfactory answers. So my question is how can I make my pages work the same way in Safari after the user hits the back button as they do in other browsers?
If this is a stupid question please be gentle, javascript is somewhat new to me. | Stefan's iframe solution works, but if that's not elegant enough, I find the following JavaScript also solves it:
```
window.onunload = function(){};
```
That is, if your menu is JavaScript, then you might prefer to solve this issue with JavaScript too.
The unload event handler definition idea came from this Firefox 1.5 article: <https://developer.mozilla.org/en/Using_Firefox_1.5_caching>. |
24,113 | <p>We have been developing an Outlook Add-in using Visual Studio 2008. However I am facing a strange behavior while adding a command button to a custom command bar. This behavior is reflected when we add the button in the reply, reply all and forward windows. The issue is that the caption of the command button is not visible though when we debug using VS it shows the caption correctly. But the button is captionless when viewed in Outlook(2003).</p>
<p>I have the code snippet as below. Any help would be appreciated.</p>
<pre><code>private void AddButtonInNewInspector(Microsoft.Office.Interop.Outlook.Inspector inspector)
{
try
{
if (inspector.CurrentItem is Microsoft.Office.Interop.Outlook.MailItem)
{
try
{
foreach (CommandBar c in inspector.CommandBars)
{
if (c.Name == "custom")
{
c.Delete();
}
}
}
catch
{
}
finally
{
//Add Custom Command bar and command button.
CommandBar myCommandBar = inspector.CommandBars.Add("custom", MsoBarPosition.msoBarTop, false, true);
myCommandBar.Visible = true;
CommandBarControl myCommandbarButton = myCommandBar.Controls.Add(MsoControlType.msoControlButton, 1, "Add", System.Reflection.Missing.Value, true);
myCommandbarButton.Caption = "Add Email";
myCommandbarButton.Width = 900;
myCommandbarButton.Visible = true;
myCommandbarButton.DescriptionText = "This is Add Email Button";
CommandBarButton btnclickhandler = (CommandBarButton)myCommandbarButton;
btnclickhandler.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.OnAddEmailButtonClick);
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "AddButtInNewInspector");
}
}
</code></pre>
| [
{
"answer_id": 24258,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know the answer to your question, but I would highly recommend Add-In Express for doing the addin. See <a href... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2528/"
] | We have been developing an Outlook Add-in using Visual Studio 2008. However I am facing a strange behavior while adding a command button to a custom command bar. This behavior is reflected when we add the button in the reply, reply all and forward windows. The issue is that the caption of the command button is not visible though when we debug using VS it shows the caption correctly. But the button is captionless when viewed in Outlook(2003).
I have the code snippet as below. Any help would be appreciated.
```
private void AddButtonInNewInspector(Microsoft.Office.Interop.Outlook.Inspector inspector)
{
try
{
if (inspector.CurrentItem is Microsoft.Office.Interop.Outlook.MailItem)
{
try
{
foreach (CommandBar c in inspector.CommandBars)
{
if (c.Name == "custom")
{
c.Delete();
}
}
}
catch
{
}
finally
{
//Add Custom Command bar and command button.
CommandBar myCommandBar = inspector.CommandBars.Add("custom", MsoBarPosition.msoBarTop, false, true);
myCommandBar.Visible = true;
CommandBarControl myCommandbarButton = myCommandBar.Controls.Add(MsoControlType.msoControlButton, 1, "Add", System.Reflection.Missing.Value, true);
myCommandbarButton.Caption = "Add Email";
myCommandbarButton.Width = 900;
myCommandbarButton.Visible = true;
myCommandbarButton.DescriptionText = "This is Add Email Button";
CommandBarButton btnclickhandler = (CommandBarButton)myCommandbarButton;
btnclickhandler.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.OnAddEmailButtonClick);
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "AddButtInNewInspector");
}
}
``` | I don't know the answer to your question, but I would highly recommend Add-In Express for doing the addin. See <http://www.add-in-express.com/add-in-net/>. I've used this in many projects, including some commercial software and it is completely awesome.
It does all the Outlook (and office) integration for you so you just work with it like any toolbar and just focus on the specifics of what you need it to do. You won't ever have to worry about the Outlook extensibility at all. Highly recommended.
Anyway, just wanted to mention it as something to look in to. It will definitely save some headaches if you're comfortable with using a 3rd party component in the project. |
24,130 | <p>Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this.</p>
<pre><code>// Using a class
class someClass
{
public $name;
public $height;
public $weight;
function __construct($name, $height, $weight)
{
$this -> name = $name;
$this -> height = $height;
$this -> weight = $weight;
}
}
$classArray[1] = new someClass('Bob', 10, 20);
$classArray[2] = new someClass('Fred', 15, 10);
$classArray[3] = new someClass('Ned', 25, 30);
// Using a 2D array
$normalArray[1]['name'] = 'Bob';
$normalArray[1]['height'] = 10;
$normalArray[1]['weight'] = 20;
$normalArray[2]['name'] = 'Fred';
$normalArray[2]['height'] = 15;
$normalArray[2]['weight'] = 10;
$normalArray[3]['name'] = 'Ned';
$normalArray[3]['height'] = 25;
$normalArray[3]['weight'] = 30;
</code></pre>
<hr>
<p>Assuming that somebody doesn't come out and show that classes are too slow, it looks like class wins.</p>
<p>I've not idea which answer I should accept to I've just upvoted all of them.</p>
<hr>
<p>And I have now written two near identical pages, one using the 2D array (written before this question was posted) and now one using a class and I must say that the class produces much nicer code. I have no idea how much overhead is going to be generated but I doubt it will rival the improvement to the code itself.</p>
<p>Thank you for helping to make me a better programmer.</p>
| [
{
"answer_id": 24131,
"author": "robintw",
"author_id": 1912,
"author_profile": "https://Stackoverflow.com/users/1912",
"pm_score": 2,
"selected": false,
"text": "<p>It depends exactly what you mean by 'better'. I'd go for the object oriented way (using classes) because I find it makes f... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this.
```
// Using a class
class someClass
{
public $name;
public $height;
public $weight;
function __construct($name, $height, $weight)
{
$this -> name = $name;
$this -> height = $height;
$this -> weight = $weight;
}
}
$classArray[1] = new someClass('Bob', 10, 20);
$classArray[2] = new someClass('Fred', 15, 10);
$classArray[3] = new someClass('Ned', 25, 30);
// Using a 2D array
$normalArray[1]['name'] = 'Bob';
$normalArray[1]['height'] = 10;
$normalArray[1]['weight'] = 20;
$normalArray[2]['name'] = 'Fred';
$normalArray[2]['height'] = 15;
$normalArray[2]['weight'] = 10;
$normalArray[3]['name'] = 'Ned';
$normalArray[3]['height'] = 25;
$normalArray[3]['weight'] = 30;
```
---
Assuming that somebody doesn't come out and show that classes are too slow, it looks like class wins.
I've not idea which answer I should accept to I've just upvoted all of them.
---
And I have now written two near identical pages, one using the 2D array (written before this question was posted) and now one using a class and I must say that the class produces much nicer code. I have no idea how much overhead is going to be generated but I doubt it will rival the improvement to the code itself.
Thank you for helping to make me a better programmer. | The "class" that you've constructed above is what most people would use a *struct* for in other languages. I'm not sure what the performance implications are in PHP, though I suspect instantiating the objects is probably more costly here, if only by a little bit.
That being said, if the cost is relatively low, it IS a bit easier to manage the objects, in my opinion.
I'm only saying the following based on the title and your question, but:
Bear in mind that classes provide the advantage of methods and access control, as well. So if you wanted to ensure that people weren't changing weights to negative numbers, you could make the `weight` field private and provide some accessor methods, like `getWeight()` and `setWeight()`. Inside `setWeight()`, you could do some value checking, like so:
```
public function setWeight($weight)
{
if($weight >= 0)
{
$this->weight = $weight;
}
else
{
// Handle this scenario however you like
}
}
``` |
24,200 | <p>I am hitting some performance bottlenecks with my C# client inserting bulk data into a SQL Server 2005 database and I'm looking for ways in which to speed up the process.</p>
<p>I am already using the SqlClient.SqlBulkCopy (which is based on TDS) to speed up the data transfer across the wire which helped a lot, but I'm still looking for more.</p>
<p>I have a simple table that looks like this: </p>
<pre><code> CREATE TABLE [BulkData](
[ContainerId] [int] NOT NULL,
[BinId] [smallint] NOT NULL,
[Sequence] [smallint] NOT NULL,
[ItemId] [int] NOT NULL,
[Left] [smallint] NOT NULL,
[Top] [smallint] NOT NULL,
[Right] [smallint] NOT NULL,
[Bottom] [smallint] NOT NULL,
CONSTRAINT [PKBulkData] PRIMARY KEY CLUSTERED
(
[ContainerIdId] ASC,
[BinId] ASC,
[Sequence] ASC
))
</code></pre>
<p>I'm inserting data in chunks that average about 300 rows where ContainerId and BinId are constant in each chunk and the Sequence value is 0-n and the values are pre-sorted based on the primary key. </p>
<p>The %Disk time performance counter spends a lot of time at 100% so it is clear that disk IO is the main issue but the speeds I'm getting are several orders of magnitude below a raw file copy.</p>
<p>Does it help any if I:</p>
<ol>
<li>Drop the Primary key while I am doing the inserting and recreate it later</li>
<li>Do inserts into a temporary table with the same schema and periodically transfer them into the main table to keep the size of the table where insertions are happening small</li>
<li>Anything else?</li>
</ol>
<p>--
Based on the responses I have gotten, let me clarify a little bit:</p>
<p>Portman: I'm using a clustered index because when the data is all imported I will need to access data sequentially in that order. I don't particularly need the index to be there while importing the data. Is there any advantage to having a nonclustered PK index while doing the inserts as opposed to dropping the constraint entirely for import?</p>
<p>Chopeen: The data is being generated remotely on many other machines (my SQL server can only handle about 10 currently, but I would love to be able to add more). It's not practical to run the entire process on the local machine because it would then have to process 50 times as much input data to generate the output.</p>
<p>Jason: I am not doing any concurrent queries against the table during the import process, I will try dropping the primary key and see if that helps.</p>
| [
{
"answer_id": 24204,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": -1,
"selected": false,
"text": "<p>Yes your ideas will help.<br>\nLean on option 1 if there are no reads happening while your loading.<br>\nLean on opti... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1948/"
] | I am hitting some performance bottlenecks with my C# client inserting bulk data into a SQL Server 2005 database and I'm looking for ways in which to speed up the process.
I am already using the SqlClient.SqlBulkCopy (which is based on TDS) to speed up the data transfer across the wire which helped a lot, but I'm still looking for more.
I have a simple table that looks like this:
```
CREATE TABLE [BulkData](
[ContainerId] [int] NOT NULL,
[BinId] [smallint] NOT NULL,
[Sequence] [smallint] NOT NULL,
[ItemId] [int] NOT NULL,
[Left] [smallint] NOT NULL,
[Top] [smallint] NOT NULL,
[Right] [smallint] NOT NULL,
[Bottom] [smallint] NOT NULL,
CONSTRAINT [PKBulkData] PRIMARY KEY CLUSTERED
(
[ContainerIdId] ASC,
[BinId] ASC,
[Sequence] ASC
))
```
I'm inserting data in chunks that average about 300 rows where ContainerId and BinId are constant in each chunk and the Sequence value is 0-n and the values are pre-sorted based on the primary key.
The %Disk time performance counter spends a lot of time at 100% so it is clear that disk IO is the main issue but the speeds I'm getting are several orders of magnitude below a raw file copy.
Does it help any if I:
1. Drop the Primary key while I am doing the inserting and recreate it later
2. Do inserts into a temporary table with the same schema and periodically transfer them into the main table to keep the size of the table where insertions are happening small
3. Anything else?
--
Based on the responses I have gotten, let me clarify a little bit:
Portman: I'm using a clustered index because when the data is all imported I will need to access data sequentially in that order. I don't particularly need the index to be there while importing the data. Is there any advantage to having a nonclustered PK index while doing the inserts as opposed to dropping the constraint entirely for import?
Chopeen: The data is being generated remotely on many other machines (my SQL server can only handle about 10 currently, but I would love to be able to add more). It's not practical to run the entire process on the local machine because it would then have to process 50 times as much input data to generate the output.
Jason: I am not doing any concurrent queries against the table during the import process, I will try dropping the primary key and see if that helps. | Here's how you can disable/enable indexes in SQL Server:
```
--Disable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users DISABLE
GO
--Enable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users REBUILD
```
Here are some resources to help you find a solution:
[Some bulk loading speed comparisons](http://weblogs.sqlteam.com/mladenp/archive/2006/07/17/10634.aspx)
[Use SqlBulkCopy to Quickly Load Data from your Client to SQL Server](http://www.sqlteam.com/article/use-sqlbulkcopy-to-quickly-load-data-from-your-client-to-sql-server)
[Optimizing Bulk Copy Performance](http://msdn.microsoft.com/en-us/library/aa178096(SQL.80).aspx)
Definitely look into NOCHECK and TABLOCK options:
[Table Hints (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms187373.aspx)
[INSERT (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms174335.aspx) |
24,207 | <p>I'm trying to use “rusage” statistics in my program to get data similar to that of the <a href="http://en.wikipedia.org/wiki/Time_%28Unix%29" rel="nofollow noreferrer">time</a> tool. However, I'm pretty sure that I'm doing something wrong. The values seem about right but can be a bit weird at times. I didn't find good resources online. Does somebody know how to do it better?</p>
<p>Sorry for the long code.</p>
<pre><code>class StopWatch {
public:
void start() {
getrusage(RUSAGE_SELF, &m_begin);
gettimeofday(&m_tmbegin, 0);
}
void stop() {
getrusage(RUSAGE_SELF, &m_end);
gettimeofday(&m_tmend, 0);
timeval_sub(m_end.ru_utime, m_begin.ru_utime, m_diff.ru_utime);
timeval_sub(m_end.ru_stime, m_begin.ru_stime, m_diff.ru_stime);
timeval_sub(m_tmend, m_tmbegin, m_tmdiff);
}
void printf(std::ostream& out) const {
using namespace std;
timeval const& utime = m_diff.ru_utime;
timeval const& stime = m_diff.ru_stime;
format_time(out, utime);
out << "u ";
format_time(out, stime);
out << "s ";
format_time(out, m_tmdiff);
}
private:
rusage m_begin;
rusage m_end;
rusage m_diff;
timeval m_tmbegin;
timeval m_tmend;
timeval m_tmdiff;
static void timeval_add(timeval const& a, timeval const& b, timeval& ret) {
ret.tv_usec = a.tv_usec + b.tv_usec;
ret.tv_sec = a.tv_sec + b.tv_sec;
if (ret.tv_usec > 999999) {
ret.tv_usec -= 1000000;
++ret.tv_sec;
}
}
static void timeval_sub(timeval const& a, timeval const& b, timeval& ret) {
ret.tv_usec = a.tv_usec - b.tv_usec;
ret.tv_sec = a.tv_sec - b.tv_sec;
if (a.tv_usec < b.tv_usec) {
ret.tv_usec += 1000000;
--ret.tv_sec;
}
}
static void format_time(std::ostream& out, timeval const& tv) {
using namespace std;
long usec = tv.tv_usec;
while (usec >= 1000)
usec /= 10;
out << tv.tv_sec << '.' << setw(3) << setfill('0') << usec;
}
}; // class StopWatch
</code></pre>
| [
{
"answer_id": 26827,
"author": "Mike Haboustak",
"author_id": 2146,
"author_profile": "https://Stackoverflow.com/users/2146",
"pm_score": 2,
"selected": false,
"text": "<p>I think there's probably a bug somewhere in your composition of sec and usec. I can't really say what exactly witho... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1968/"
] | I'm trying to use “rusage” statistics in my program to get data similar to that of the [time](http://en.wikipedia.org/wiki/Time_%28Unix%29) tool. However, I'm pretty sure that I'm doing something wrong. The values seem about right but can be a bit weird at times. I didn't find good resources online. Does somebody know how to do it better?
Sorry for the long code.
```
class StopWatch {
public:
void start() {
getrusage(RUSAGE_SELF, &m_begin);
gettimeofday(&m_tmbegin, 0);
}
void stop() {
getrusage(RUSAGE_SELF, &m_end);
gettimeofday(&m_tmend, 0);
timeval_sub(m_end.ru_utime, m_begin.ru_utime, m_diff.ru_utime);
timeval_sub(m_end.ru_stime, m_begin.ru_stime, m_diff.ru_stime);
timeval_sub(m_tmend, m_tmbegin, m_tmdiff);
}
void printf(std::ostream& out) const {
using namespace std;
timeval const& utime = m_diff.ru_utime;
timeval const& stime = m_diff.ru_stime;
format_time(out, utime);
out << "u ";
format_time(out, stime);
out << "s ";
format_time(out, m_tmdiff);
}
private:
rusage m_begin;
rusage m_end;
rusage m_diff;
timeval m_tmbegin;
timeval m_tmend;
timeval m_tmdiff;
static void timeval_add(timeval const& a, timeval const& b, timeval& ret) {
ret.tv_usec = a.tv_usec + b.tv_usec;
ret.tv_sec = a.tv_sec + b.tv_sec;
if (ret.tv_usec > 999999) {
ret.tv_usec -= 1000000;
++ret.tv_sec;
}
}
static void timeval_sub(timeval const& a, timeval const& b, timeval& ret) {
ret.tv_usec = a.tv_usec - b.tv_usec;
ret.tv_sec = a.tv_sec - b.tv_sec;
if (a.tv_usec < b.tv_usec) {
ret.tv_usec += 1000000;
--ret.tv_sec;
}
}
static void format_time(std::ostream& out, timeval const& tv) {
using namespace std;
long usec = tv.tv_usec;
while (usec >= 1000)
usec /= 10;
out << tv.tv_sec << '.' << setw(3) << setfill('0') << usec;
}
}; // class StopWatch
``` | What is the purpose of:
```
while (usec >= 1000)
usec /= 10;
```
I gather that you want the most significant three digits of the usec; in that case, the most straightforward way I can think of is to divide usec by 1000, and be done with that.
Test cases:
* 999999 ⇒ 999
* 99999 ⇒ 999 (should be 099)
* 9999 ⇒ 999 (should be 009)
* 999 ⇒ 999 (should be 000) |
24,262 | <p>While creating a file synchronization program in C# I tried to make a method <code>copy</code> in <code>LocalFileItem</code> class that uses <code>System.IO.File.Copy(destination.Path, Path, true)</code> method where <code>Path</code> is a <code>string</code>.<br>
After executing this code with destination. <code>Path = "C:\\Test2"</code> and <code>this.Path = "C:\\Test\\F1.txt"</code> I get an exception saying that I do not have the required file permissions to do this operation on <strong>C:\Test</strong>, but <strong>C:\Test</strong> is owned by myself <em>(the current user)</em>.<br>
Does anybody knows what is going on, or how to get around this?</p>
<p>Here is the original code complete.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Diones.Util.IO
{
/// <summary>
/// An object representation of a file or directory.
/// </summary>
public abstract class FileItem : IComparable
{
protected String path;
public String Path
{
set { this.path = value; }
get { return this.path; }
}
protected bool isDirectory;
public bool IsDirectory
{
set { this.isDirectory = value; }
get { return this.isDirectory; }
}
/// <summary>
/// Delete this fileItem.
/// </summary>
public abstract void delete();
/// <summary>
/// Delete this directory and all of its elements.
/// </summary>
protected abstract void deleteRecursive();
/// <summary>
/// Copy this fileItem to the destination directory.
/// </summary>
public abstract void copy(FileItem fileD);
/// <summary>
/// Copy this directory and all of its elements
/// to the destination directory.
/// </summary>
protected abstract void copyRecursive(FileItem fileD);
/// <summary>
/// Creates a FileItem from a string path.
/// </summary>
/// <param name="path"></param>
public FileItem(String path)
{
Path = path;
if (path.EndsWith("\\") || path.EndsWith("/")) IsDirectory = true;
else IsDirectory = false;
}
/// <summary>
/// Creates a FileItem from a FileSource directory.
/// </summary>
/// <param name="directory"></param>
public FileItem(FileSource directory)
{
Path = directory.Path;
}
public override String ToString()
{
return Path;
}
public abstract int CompareTo(object b);
}
/// <summary>
/// A file or directory on the hard disk
/// </summary>
public class LocalFileItem : FileItem
{
public override void delete()
{
if (!IsDirectory) File.Delete(this.Path);
else deleteRecursive();
}
protected override void deleteRecursive()
{
Directory.Delete(Path, true);
}
public override void copy(FileItem destination)
{
if (!IsDirectory) File.Copy(destination.Path, Path, true);
else copyRecursive(destination);
}
protected override void copyRecursive(FileItem destination)
{
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(
Path, destination.Path, true);
}
/// <summary>
/// Create's a LocalFileItem from a string path
/// </summary>
/// <param name="path"></param>
public LocalFileItem(String path)
: base(path)
{
}
/// <summary>
/// Creates a LocalFileItem from a FileSource path
/// </summary>
/// <param name="path"></param>
public LocalFileItem(FileSource path)
: base(path)
{
}
public override int CompareTo(object obj)
{
if (obj is FileItem)
{
FileItem fi = (FileItem)obj;
if (File.GetCreationTime(this.Path).CompareTo
(File.GetCreationTime(fi.Path)) > 0) return 1;
else if (File.GetCreationTime(this.Path).CompareTo
(File.GetCreationTime(fi.Path)) < 0) return -1;
else
{
if (File.GetLastWriteTime(this.Path).CompareTo
(File.GetLastWriteTime(fi.Path)) < 0) return -1;
else if (File.GetLastWriteTime(this.Path).CompareTo
(File.GetLastWriteTime(fi.Path)) > 0) return 1;
else return 0;
}
}
else
throw new ArgumentException("obj isn't a FileItem");
}
}
}
</code></pre>
| [
{
"answer_id": 24274,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 3,
"selected": true,
"text": "<p>It seems you have misplaced the parameters in File.Copy(), it should be File.Copy(string source, string destinat... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605/"
] | While creating a file synchronization program in C# I tried to make a method `copy` in `LocalFileItem` class that uses `System.IO.File.Copy(destination.Path, Path, true)` method where `Path` is a `string`.
After executing this code with destination. `Path = "C:\\Test2"` and `this.Path = "C:\\Test\\F1.txt"` I get an exception saying that I do not have the required file permissions to do this operation on **C:\Test**, but **C:\Test** is owned by myself *(the current user)*.
Does anybody knows what is going on, or how to get around this?
Here is the original code complete.
```
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Diones.Util.IO
{
/// <summary>
/// An object representation of a file or directory.
/// </summary>
public abstract class FileItem : IComparable
{
protected String path;
public String Path
{
set { this.path = value; }
get { return this.path; }
}
protected bool isDirectory;
public bool IsDirectory
{
set { this.isDirectory = value; }
get { return this.isDirectory; }
}
/// <summary>
/// Delete this fileItem.
/// </summary>
public abstract void delete();
/// <summary>
/// Delete this directory and all of its elements.
/// </summary>
protected abstract void deleteRecursive();
/// <summary>
/// Copy this fileItem to the destination directory.
/// </summary>
public abstract void copy(FileItem fileD);
/// <summary>
/// Copy this directory and all of its elements
/// to the destination directory.
/// </summary>
protected abstract void copyRecursive(FileItem fileD);
/// <summary>
/// Creates a FileItem from a string path.
/// </summary>
/// <param name="path"></param>
public FileItem(String path)
{
Path = path;
if (path.EndsWith("\\") || path.EndsWith("/")) IsDirectory = true;
else IsDirectory = false;
}
/// <summary>
/// Creates a FileItem from a FileSource directory.
/// </summary>
/// <param name="directory"></param>
public FileItem(FileSource directory)
{
Path = directory.Path;
}
public override String ToString()
{
return Path;
}
public abstract int CompareTo(object b);
}
/// <summary>
/// A file or directory on the hard disk
/// </summary>
public class LocalFileItem : FileItem
{
public override void delete()
{
if (!IsDirectory) File.Delete(this.Path);
else deleteRecursive();
}
protected override void deleteRecursive()
{
Directory.Delete(Path, true);
}
public override void copy(FileItem destination)
{
if (!IsDirectory) File.Copy(destination.Path, Path, true);
else copyRecursive(destination);
}
protected override void copyRecursive(FileItem destination)
{
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(
Path, destination.Path, true);
}
/// <summary>
/// Create's a LocalFileItem from a string path
/// </summary>
/// <param name="path"></param>
public LocalFileItem(String path)
: base(path)
{
}
/// <summary>
/// Creates a LocalFileItem from a FileSource path
/// </summary>
/// <param name="path"></param>
public LocalFileItem(FileSource path)
: base(path)
{
}
public override int CompareTo(object obj)
{
if (obj is FileItem)
{
FileItem fi = (FileItem)obj;
if (File.GetCreationTime(this.Path).CompareTo
(File.GetCreationTime(fi.Path)) > 0) return 1;
else if (File.GetCreationTime(this.Path).CompareTo
(File.GetCreationTime(fi.Path)) < 0) return -1;
else
{
if (File.GetLastWriteTime(this.Path).CompareTo
(File.GetLastWriteTime(fi.Path)) < 0) return -1;
else if (File.GetLastWriteTime(this.Path).CompareTo
(File.GetLastWriteTime(fi.Path)) > 0) return 1;
else return 0;
}
}
else
throw new ArgumentException("obj isn't a FileItem");
}
}
}
``` | It seems you have misplaced the parameters in File.Copy(), it should be File.Copy(string source, string destination).
Also is "C:\Test2" a directory? You can't copy file to a directory.
Use something like that instead:
```
File.Copy(
sourceFile,
Path.Combine(destinationDir,Path.GetFileName(sourceFile))
)
```
; |
24,315 | <p>In C# I can use the FileSystemWatcher object to watch for a specific file and raise an event when it is created, modified, etc.</p>
<p>The problem I have with this class is that it raises the event the moment the file becomes created, even if the process which created the file is still in the process of writing. I have found this to be very problematic, especially if I'm trying to read something like an XML document where the file must have some structure to it which won't exist until it is completed being written.</p>
<p>Does .NET (preferably 2.0) have any way to raise an event after the file becomes accessible, or do I have to constantly try reading the file until it doesn't throw an exception to know it is available?</p>
| [
{
"answer_id": 24323,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if there is a way of an event actually being raised by the standard class, but I eas experiencing similar proble... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | In C# I can use the FileSystemWatcher object to watch for a specific file and raise an event when it is created, modified, etc.
The problem I have with this class is that it raises the event the moment the file becomes created, even if the process which created the file is still in the process of writing. I have found this to be very problematic, especially if I'm trying to read something like an XML document where the file must have some structure to it which won't exist until it is completed being written.
Does .NET (preferably 2.0) have any way to raise an event after the file becomes accessible, or do I have to constantly try reading the file until it doesn't throw an exception to know it is available? | You can use a file system watcher to check when the file has been changed. It only becomes "changed" after whichever program had the file previously closes the file. I know you asked for C#, but my VB.Net is much better. Hope you or someone else can translate.
It tries to open the file, if it isn't available, it adds a watcher, and waits for the file to be changed. After the file is changed, it tries to open again. It throws an exception if it waits more than 120 seconds, because you may get caught in a situation where the file is never released. Also, I decided to add a timeout of waiting for the file change of 5 seconds, in case of the small possibility that the file was closed prior to the actual file watcher being created.
```
Public Sub WriteToFile(ByVal FilePath As String, ByVal FileName As String, ByVal Data() As Byte)
Dim FileOpen As Boolean
Dim File As System.IO.FileStream = Nothing
Dim StartTime As DateTime
Dim MaxWaitSeconds As Integer = 120
StartTime = DateTime.Now
FileOpen = False
Do
Try
File = New System.IO.FileStream(FilePath & FileName, IO.FileMode.Append)
FileOpen = True
Catch ex As Exception
If DateTime.Now.Subtract(StartTime).TotalSeconds > MaxWaitSeconds Then
Throw New Exception("Waited more than " & MaxWaitSeconds & " To Open File.")
Else
Dim FileWatch As System.IO.FileSystemWatcher
FileWatch = New System.IO.FileSystemWatcher(FilePath, FileName)
FileWatch.WaitForChanged(IO.WatcherChangeTypes.Changed,5000)
End If
FileOpen = False
End Try
Loop While Not FileOpen
If FileOpen Then
File.Write(Data, 0, Data.Length)
File.Close()
End If
End Sub
``` |
24,468 | <p>When I try to run a .NET assembly (<code>boo.exe</code>) from a network share (mapped to a drive), it fails since it's only partially trusted:</p>
<pre><code>Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers.
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at BooCommandLine..ctor()
at Program..ctor()
at ProgramModule.Main(String[] argv)
The action that failed was:
LinkDemand
The assembly or AppDomain that failed was:
boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67
The Zone of the assembly that failed was:
Intranet
The Url of the assembly that failed was:
file:///H:/boo-svn/bin/boo.exe
</code></pre>
<p>With instructions from <a href="http://www.georgewesolowski.com/blog/PermaLink,guid,4cc5fcdf-cc68-4cf0-a083-b22a8bdc92d6.aspx" rel="nofollow noreferrer">a blog post</a>, I added a policy to the .NET Configuration fully trusting all assemblies with <code>file:///H:/*</code> as their URL. I verified this by entering the URL <code>file:///H:/boo-svn/bin/boo.exe</code> into the <em>Evaluate Assembly</em> tool in the .NET Configuration and noting that boo.exe had the <em>Unrestricted</em> permission (which it didn't have before the policy).</p>
<p>Even with the permission, <code>boo.exe</code> does not run. I still get the same error message.</p>
<p>What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run?</p>
| [
{
"answer_id": 24477,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 4,
"selected": true,
"text": "<p>With .NET 3.5 SP1, .NET assemblies running from UNC shares have full permissions. </p>\n\n<p>See Brad Abrams's ... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616/"
] | When I try to run a .NET assembly (`boo.exe`) from a network share (mapped to a drive), it fails since it's only partially trusted:
```
Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers.
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at BooCommandLine..ctor()
at Program..ctor()
at ProgramModule.Main(String[] argv)
The action that failed was:
LinkDemand
The assembly or AppDomain that failed was:
boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67
The Zone of the assembly that failed was:
Intranet
The Url of the assembly that failed was:
file:///H:/boo-svn/bin/boo.exe
```
With instructions from [a blog post](http://www.georgewesolowski.com/blog/PermaLink,guid,4cc5fcdf-cc68-4cf0-a083-b22a8bdc92d6.aspx), I added a policy to the .NET Configuration fully trusting all assemblies with `file:///H:/*` as their URL. I verified this by entering the URL `file:///H:/boo-svn/bin/boo.exe` into the *Evaluate Assembly* tool in the .NET Configuration and noting that boo.exe had the *Unrestricted* permission (which it didn't have before the policy).
Even with the permission, `boo.exe` does not run. I still get the same error message.
What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run? | With .NET 3.5 SP1, .NET assemblies running from UNC shares have full permissions.
See Brad Abrams's [Allow .exes to be run off a network shares](http://blogs.msdn.com/brada/archive/2007/10/26/adhoc-poll-allowing-net-exes-to-run-off-a-network-share.aspx) for workaround and discussions, and finally the follow up [.NET 3.5 SP1 allows managed code to be launched from a network share](http://blogs.msdn.com/brada/archive/2008/08/13/net-framework-3-5-sp1-allows-managed-code-to-be-launched-from-a-network-share.aspx). |
24,470 | <p>Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following.</p>
<pre><code>Action1 VIEW
Action1 EDIT
Action2 VIEW
Action3 VIEW
Action3 EDIT
</code></pre>
<p>I would like to use PIVOT (if even possible) to make the results like so:</p>
<pre><code>Action1 VIEW EDIT
Action2 VIEW NULL
Action3 VIEW EDIT
</code></pre>
<p>Is this even possible with the PIVOT functionality?</p>
| [
{
"answer_id": 24538,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 3,
"selected": false,
"text": "<p>Well, for your sample and any with a limited number of unique columns, this should do it.</p>\n\n<pre><code>select \n disti... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2626/"
] | Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following.
```
Action1 VIEW
Action1 EDIT
Action2 VIEW
Action3 VIEW
Action3 EDIT
```
I would like to use PIVOT (if even possible) to make the results like so:
```
Action1 VIEW EDIT
Action2 VIEW NULL
Action3 VIEW EDIT
```
Is this even possible with the PIVOT functionality? | Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once.
```
SELECT Action,
MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol,
MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol
FROM t
GROUP BY Action
``` |
24,495 | <p>I have a Struts + Velocity structure like for example, a Person class, whose one property is a Car object (with its own getter/setter methods) and it is mapped to a Velocity form that submits to an Action, using ModelDriven and getModel structure.</p>
<p>I what to put a button on the form that shows "View Car" if car property is not null or car.id != 0 or show another button "Choose Car" if car is null or car.id = 0.</p>
<p>How do I code this. I tried something like that in the template file:</p>
<pre><code>#if($car != null)
#ssubmit("name=view" "value=View Car")
#else
#ssubmit("name=new" "value=Choose Car")
#end
</code></pre>
<p>But I keep getting error about Null value in the <em>#if</em> line. </p>
<p>I also created a boolean method hasCar() in Person to try, but I can't access it and I don't know why.</p>
<p>And Velocity + Struts tutorials are difficult to find or have good information.</p>
<p>Thanks</p>
| [
{
"answer_id": 24510,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 4,
"selected": true,
"text": "<p>You should change the #if line to:</p>\n\n<pre><code>#if($car)\n</code></pre>\n"
},
{
"answer_id": 64065,
... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274/"
] | I have a Struts + Velocity structure like for example, a Person class, whose one property is a Car object (with its own getter/setter methods) and it is mapped to a Velocity form that submits to an Action, using ModelDriven and getModel structure.
I what to put a button on the form that shows "View Car" if car property is not null or car.id != 0 or show another button "Choose Car" if car is null or car.id = 0.
How do I code this. I tried something like that in the template file:
```
#if($car != null)
#ssubmit("name=view" "value=View Car")
#else
#ssubmit("name=new" "value=Choose Car")
#end
```
But I keep getting error about Null value in the *#if* line.
I also created a boolean method hasCar() in Person to try, but I can't access it and I don't know why.
And Velocity + Struts tutorials are difficult to find or have good information.
Thanks | You should change the #if line to:
```
#if($car)
``` |
24,515 | <p>Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I <a href="http://urbanoalvarez.es/blog/2008/04/04/bad-words-list/" rel="noreferrer">found this</a> one, and it's a start, but nothing more.</p>
<p>Yes, I know that this kind of filters are easily escaped... but the client will is the client will !!! :-) </p>
<p>The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce" :-) - an email will do. </p>
<p>Thanks for any help.</p>
| [
{
"answer_id": 24527,
"author": "AgentConundrum",
"author_id": 1588,
"author_profile": "https://Stackoverflow.com/users/1588",
"pm_score": 6,
"selected": false,
"text": "<p>Beware of <a href=\"http://thedailywtf.com/Articles/The-Clbuttic-Mistake-.aspx\" rel=\"noreferrer\">clbuttic mistak... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178/"
] | Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I [found this](http://urbanoalvarez.es/blog/2008/04/04/bad-words-list/) one, and it's a start, but nothing more.
Yes, I know that this kind of filters are easily escaped... but the client will is the client will !!! :-)
The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce" :-) - an email will do.
Thanks for any help. | I didn't see any language specified but you can use this for PHP it will generate a RegEx for each instered work so that even intentional mis-spellings (i.e. @ss, i3itch ) will also be caught.
```
<?php
/**
* @author unkwntech@unkwndesign.com
**/
if($_GET['act'] == 'do')
{
$pattern['a'] = '/[a]/'; $replace['a'] = '[a A @]';
$pattern['b'] = '/[b]/'; $replace['b'] = '[b B I3 l3 i3]';
$pattern['c'] = '/[c]/'; $replace['c'] = '(?:[c C (]|[k K])';
$pattern['d'] = '/[d]/'; $replace['d'] = '[d D]';
$pattern['e'] = '/[e]/'; $replace['e'] = '[e E 3]';
$pattern['f'] = '/[f]/'; $replace['f'] = '(?:[f F]|[ph pH Ph PH])';
$pattern['g'] = '/[g]/'; $replace['g'] = '[g G 6]';
$pattern['h'] = '/[h]/'; $replace['h'] = '[h H]';
$pattern['i'] = '/[i]/'; $replace['i'] = '[i I l ! 1]';
$pattern['j'] = '/[j]/'; $replace['j'] = '[j J]';
$pattern['k'] = '/[k]/'; $replace['k'] = '(?:[c C (]|[k K])';
$pattern['l'] = '/[l]/'; $replace['l'] = '[l L 1 ! i]';
$pattern['m'] = '/[m]/'; $replace['m'] = '[m M]';
$pattern['n'] = '/[n]/'; $replace['n'] = '[n N]';
$pattern['o'] = '/[o]/'; $replace['o'] = '[o O 0]';
$pattern['p'] = '/[p]/'; $replace['p'] = '[p P]';
$pattern['q'] = '/[q]/'; $replace['q'] = '[q Q 9]';
$pattern['r'] = '/[r]/'; $replace['r'] = '[r R]';
$pattern['s'] = '/[s]/'; $replace['s'] = '[s S $ 5]';
$pattern['t'] = '/[t]/'; $replace['t'] = '[t T 7]';
$pattern['u'] = '/[u]/'; $replace['u'] = '[u U v V]';
$pattern['v'] = '/[v]/'; $replace['v'] = '[v V u U]';
$pattern['w'] = '/[w]/'; $replace['w'] = '[w W vv VV]';
$pattern['x'] = '/[x]/'; $replace['x'] = '[x X]';
$pattern['y'] = '/[y]/'; $replace['y'] = '[y Y]';
$pattern['z'] = '/[z]/'; $replace['z'] = '[z Z 2]';
$word = str_split(strtolower($_POST['word']));
$i=0;
while($i < count($word))
{
if(!is_numeric($word[$i]))
{
if($word[$i] != ' ' || count($word[$i]) < '1')
{
$word[$i] = preg_replace($pattern[$word[$i]], $replace[$word[$i]], $word[$i]);
}
}
$i++;
}
//$word = "/" . implode('', $word) . "/";
echo implode('', $word);
}
if($_GET['act'] == 'list')
{
$link = mysql_connect('localhost', 'username', 'password', '1');
mysql_select_db('peoples');
$sql = "SELECT word FROM filters";
$result = mysql_query($sql, $link);
$i=0;
while($i < mysql_num_rows($result))
{
echo mysql_result($result, $i, 'word') . "<br />";
$i++;
}
echo '<hr>';
}
?>
<html>
<head>
<title>RegEx Generator</title>
</head>
<body>
<form action='badword.php?act=do' method='post'>
Word: <input type='text' name='word' /><br />
<input type='submit' value='Generate' />
</form>
<a href="badword.php?act=list">List Words</a>
</body>
</html>
``` |
24,516 | <p>I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using:</p>
<pre><code>%token <int> INT
%token <string> ID
%token MINUS
%start expr
%type <expr> expr
%nonassoc INT ID
%left MINUS
%left APPLY
%%
expr: INT
{ ExprInt $1 }
| ID
{ ExprId $1 }
| expr MINUS expr
{ ExprSub($1, $3) }
| MINUS expr
{ ExprNeg $2 }
| expr expr %prec APPLY
{ ExprApply($1, $2) };
</code></pre>
<p>The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule?</p>
| [
{
"answer_id": 24589,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 4,
"selected": true,
"text": "<p>Unfortunately, the only answer I can come up with means increasing the complexity of the grammar.</p>\n\n<ol>\n<li>s... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1891/"
] | I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using:
```
%token <int> INT
%token <string> ID
%token MINUS
%start expr
%type <expr> expr
%nonassoc INT ID
%left MINUS
%left APPLY
%%
expr: INT
{ ExprInt $1 }
| ID
{ ExprId $1 }
| expr MINUS expr
{ ExprSub($1, $3) }
| MINUS expr
{ ExprNeg $2 }
| expr expr %prec APPLY
{ ExprApply($1, $2) };
```
The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule? | Unfortunately, the only answer I can come up with means increasing the complexity of the grammar.
1. split `expr` into `simple_expr` and `expr_with_prefix`
2. allow only `simple_expr` or `(expr_with_prefix)` in an APPLY
The first step turns your reduce/reduce conflict into a shift/reduce conflict, but the parentheses resolve that.
You're going to have the same problem with 'a b c': is it `a(b(c))` or `(a(b))(c)`? You'll need to also break off `applied_expression` and required `(applied_expression)` in the grammar.
I think this will do it, but I'm not sure:
```
expr := INT
| parenthesized_expr
| expr MINUS expr
parenthesized_expr := ( expr )
| ( applied_expr )
| ( expr_with_prefix )
applied_expr := expr expr
expr_with_prefix := MINUS expr
``` |
24,542 | <p>Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++? </p>
<p>I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use & and |. I also need to accumulate Boolean values sometimes, and &= and |= can be quite useful.</p>
<p>I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this?</p>
| [
{
"answer_id": 24552,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 4,
"selected": false,
"text": "<p>The raised eyebrows should tell you enough to stop doing it. You don't write the code for the compiler, you write it for you... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1891/"
] | Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++?
I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use & and |. I also need to accumulate Boolean values sometimes, and &= and |= can be quite useful.
I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this? | `||` and `&&` are boolean operators and the built-in ones are guaranteed to return either `true` or `false`. Nothing else.
`|`, `&` and `^` are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 – as is the case with the C language – you may end up with some behavior you didn't want. For instance:
```
BOOL two = 2;
BOOL one = 1;
BOOL and = two & one; //and = 0
BOOL cand = two && one; //cand = 1
```
In C++, however, the `bool` type is guaranteed to be only either a `true` or a `false` (which convert implicitly to respectively `1` and `0`), so it's less of a worry from this stance, but the fact that people aren't used to seeing such things in code makes a good argument for not doing it. Just say `b = b && x` and be done with it. |
24,546 | <p>I'm trying to fetch Wikipedia pages using <a href="http://search.cpan.org/dist/libwww-perl" rel="noreferrer">LWP::Simple</a>, but they're not coming back. This code:</p>
<pre><code>#!/usr/bin/perl
use strict;
use LWP::Simple;
print get("http://en.wikipedia.org/wiki/Stack_overflow");
</code></pre>
<p>doesn't print anything. But if I use some other webpage, say <code><a href="http://www.google.com" rel="noreferrer">http://www.google.com</a></code>, it works fine. </p>
<p>Is there some other name that I should be using to refer to Wikipedia pages? </p>
<p>What could be going on here?</p>
| [
{
"answer_id": 24574,
"author": "Jesse Beder",
"author_id": 112,
"author_profile": "https://Stackoverflow.com/users/112",
"pm_score": 5,
"selected": true,
"text": "<p>Apparently Wikipedia blocks LWP::Simple requests: <a href=\"http://www.perlmonks.org/?node_id=695886\" rel=\"noreferrer\"... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112/"
] | I'm trying to fetch Wikipedia pages using [LWP::Simple](http://search.cpan.org/dist/libwww-perl), but they're not coming back. This code:
```
#!/usr/bin/perl
use strict;
use LWP::Simple;
print get("http://en.wikipedia.org/wiki/Stack_overflow");
```
doesn't print anything. But if I use some other webpage, say `<http://www.google.com>`, it works fine.
Is there some other name that I should be using to refer to Wikipedia pages?
What could be going on here? | Apparently Wikipedia blocks LWP::Simple requests: <http://www.perlmonks.org/?node_id=695886>
The following works instead:
```
#!/usr/bin/perl
use strict;
use LWP::UserAgent;
my $url = "http://en.wikipedia.org/wiki/Stack_overflow";
my $ua = LWP::UserAgent->new();
my $res = $ua->get($url);
print $res->content;
``` |
24,551 | <p>I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.</p>
<p>Should I do it at declaration?:</p>
<pre><code>public class Dice
{
private int topFace = 1;
private Random myRand = new Random();
public void Roll()
{
// ......
}
}
</code></pre>
<p>or in a constructor?:</p>
<pre><code>public class Dice
{
private int topFace;
private Random myRand;
public Dice()
{
topFace = 1;
myRand = new Random();
}
public void Roll()
{
// .....
}
}
</code></pre>
<p>I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.</p>
| [
{
"answer_id": 24558,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 9,
"selected": true,
"text": "<p>My rules:</p>\n\n<ol>\n<li>Don't initialize with the default values in declaration (<code>null</code>, <code>false</code>, <c... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635/"
] | I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.
Should I do it at declaration?:
```
public class Dice
{
private int topFace = 1;
private Random myRand = new Random();
public void Roll()
{
// ......
}
}
```
or in a constructor?:
```
public class Dice
{
private int topFace;
private Random myRand;
public Dice()
{
topFace = 1;
myRand = new Random();
}
public void Roll()
{
// .....
}
}
```
I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach. | My rules:
1. Don't initialize with the default values in declaration (`null`, `false`, `0`, `0.0`…).
2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
4. Be consistent in your practice (the most important rule). |
24,556 | <p>In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it?</p>
<p>A little context if it helps...</p>
<p>I have this code in my <code>global.asax</code> as a helper method. Normally, between requests, this isn't a problem. But right after signing in, this is getting called more than once, and the second time I end up trying to attach the <code>Member</code> object in the same unit of work where it was created.</p>
<pre><code>private void CheckCurrentUser()
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
AppHelper.CurrentMember = null;
return;
}
IUserService userService = new UserService();
if (AppHelper.CurrentMember != null)
userService.AttachExisting(AppHelper.CurrentMember);
else
AppHelper.CurrentMember = userService.GetMember(
HttpContext.Current.User.Identity.Name,
AppHelper.CurrentLocation);
}
</code></pre>
| [
{
"answer_id": 24558,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 9,
"selected": true,
"text": "<p>My rules:</p>\n\n<ol>\n<li>Don't initialize with the default values in declaration (<code>null</code>, <code>false</code>, <c... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595/"
] | In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it?
A little context if it helps...
I have this code in my `global.asax` as a helper method. Normally, between requests, this isn't a problem. But right after signing in, this is getting called more than once, and the second time I end up trying to attach the `Member` object in the same unit of work where it was created.
```
private void CheckCurrentUser()
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
AppHelper.CurrentMember = null;
return;
}
IUserService userService = new UserService();
if (AppHelper.CurrentMember != null)
userService.AttachExisting(AppHelper.CurrentMember);
else
AppHelper.CurrentMember = userService.GetMember(
HttpContext.Current.User.Identity.Name,
AppHelper.CurrentLocation);
}
``` | My rules:
1. Don't initialize with the default values in declaration (`null`, `false`, `0`, `0.0`…).
2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
4. Be consistent in your practice (the most important rule). |
24,580 | <p>How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line?</p>
| [
{
"answer_id": 24581,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 2,
"selected": false,
"text": "<p>Look into build tool <a href=\"http://en.wikipedia.org/wiki/NAnt\" rel=\"nofollow noreferrer\">NAnt</a> or <a href=\"http... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2541/"
] | How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line? | With VS2008 you can do this:
```
devenv solution.sln /build configuration
``` |
24,622 | <p>I can set the PHP include path in the <code>php.ini</code>:</p>
<pre><code>include_path = /path/to/site/includes/
</code></pre>
<p>But then other websites are affected so that is no good.</p>
<p>I can set the PHP include in the start of every file:</p>
<pre><code>$path = '/path/to/site/includes/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
</code></pre>
<p>But that seems like bad practice and clutters things up. </p>
<p>So I can make an include of that and then include it into every file:</p>
<pre><code>include 'includes/config.php';
</code></pre>
<p>or</p>
<pre><code>include '../includes/config.php';
</code></pre>
<p>This is what I'm doing right now, but the include path of <code>config.php</code> will change depending on what is including it. </p>
<p>Is there a better way? Does it matter?</p>
| [
{
"answer_id": 24631,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 5,
"selected": true,
"text": "<p>If you're using apache as a webserver you can override (if you allow it) settings using <em>.htaccess</em> files. See... | 2008/08/23 | [
"https://Stackoverflow.com/questions/24622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118/"
] | I can set the PHP include path in the `php.ini`:
```
include_path = /path/to/site/includes/
```
But then other websites are affected so that is no good.
I can set the PHP include in the start of every file:
```
$path = '/path/to/site/includes/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
```
But that seems like bad practice and clutters things up.
So I can make an include of that and then include it into every file:
```
include 'includes/config.php';
```
or
```
include '../includes/config.php';
```
This is what I'm doing right now, but the include path of `config.php` will change depending on what is including it.
Is there a better way? Does it matter? | If you're using apache as a webserver you can override (if you allow it) settings using *.htaccess* files. See [the PHP manual](http://us2.php.net/configuration.changes) for details.
Basically you put a file called *.htaccess* in your website root, which contains some PHP `ini` values. Provided you configured Apache to allow overrides, this site will use all values in your PHP config, + the values you specify in the *.htaccess* file.
>
> Can be used only with `PHP_INI_ALL` and `PHP_INI_PERDIR` type directives
>
>
>
as stated in the page I linked. If you click through to the full listing, you see that the include path is a `PHP_INI_ALL` directive. |
24,715 | <p>I'm implementing a tagging system for a website. There are multiple tags per object and multiple objects per tag. This is accomplished by maintaining a table with two values per record, one for the ids of the object and the tag.</p>
<p>I'm looking to write a query to find the objects that match a given set of tags. Suppose I had the following data (in [object] -> [tags]* format)</p>
<pre><code>apple -> fruit red food
banana -> fruit yellow food
cheese -> yellow food
firetruck -> vehicle red
</code></pre>
<p>If I want to match (red), I should get apple and firetruck. If I want to match (fruit, food) I should get (apple, banana).</p>
<p>How do I write a SQL query do do what I want?</p>
<p>@Jeremy Ruten,</p>
<p>Thanks for your answer. The notation used was used to give some sample data - my database does have a table with 1 object id and 1 tag per record.</p>
<p>Second, my problem is that I need to get all objects that match all tags. Substituting your OR for an AND like so:</p>
<pre><code>SELECT object WHERE tag = 'fruit' AND tag = 'food';
</code></pre>
<p>Yields no results when run.</p>
| [
{
"answer_id": 24720,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": -1,
"selected": false,
"text": "<p>I'd suggest making your table have 1 tag per record, like this:</p>\n\n<pre><code> apple -> fruit\n apple -> red\... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
] | I'm implementing a tagging system for a website. There are multiple tags per object and multiple objects per tag. This is accomplished by maintaining a table with two values per record, one for the ids of the object and the tag.
I'm looking to write a query to find the objects that match a given set of tags. Suppose I had the following data (in [object] -> [tags]\* format)
```
apple -> fruit red food
banana -> fruit yellow food
cheese -> yellow food
firetruck -> vehicle red
```
If I want to match (red), I should get apple and firetruck. If I want to match (fruit, food) I should get (apple, banana).
How do I write a SQL query do do what I want?
@Jeremy Ruten,
Thanks for your answer. The notation used was used to give some sample data - my database does have a table with 1 object id and 1 tag per record.
Second, my problem is that I need to get all objects that match all tags. Substituting your OR for an AND like so:
```
SELECT object WHERE tag = 'fruit' AND tag = 'food';
```
Yields no results when run. | Given:
* object table (primary key id)
* objecttags table (foreign keys objectId, tagid)
* tags table (primary key id)
```
SELECT distinct o.*
from object o join objecttags ot on o.Id = ot.objectid
join tags t on ot.tagid = t.id
where t.Name = 'fruit' or t.name = 'food';
```
This seems backwards, since you want and, but the issue is, 2 tags aren't on the same row, and therefore, an and yields nothing, since 1 single row cannot be both a fruit and a food.
This query will yield duplicates usually, because you will get 1 row of each object, per tag.
If you wish to really do an and in this case, you will need a `group by`, and a `having count = <number of ors>` in your query for example.
```
SELECT distinct o.name, count(*) as count
from object o join objecttags ot on o.Id = ot.objectid
join tags t on ot.tagid = t.id
where t.Name = 'fruit' or t.name = 'food'
group by o.name
having count = 2;
``` |
24,723 | <p>Jeff actually posted about this in <a href="http://refactormycode.com/codes/333-sanitize-html" rel="noreferrer">Sanitize HTML</a>. But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java?</p>
<p>[Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (*). As for anything related to security, the more people look into it, the better it is!</p>
<p>(*) In fact, I think it was still in closed beta</p>
| [
{
"answer_id": 27705,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 0,
"selected": false,
"text": "<p>The biggest problem by using jeffs code is the @ which currently isnt available. </p>\n\n<p>I would probably just take the \"ra... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1406/"
] | Jeff actually posted about this in [Sanitize HTML](http://refactormycode.com/codes/333-sanitize-html). But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java?
[Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (\*). As for anything related to security, the more people look into it, the better it is!
(\*) In fact, I think it was still in closed beta | Don't do this with regular expressions. Remember, you're not protecting just against valid HTML; you're protecting against the DOM that web browsers create. Browsers can be tricked into producing valid DOM from invalid HTML quite easily.
For example, see this list of [obfuscated XSS attacks](http://ha.ckers.org/xss.html). Are you prepared to tailor a regex to prevent this real world attack on [Yahoo and Hotmail](http://www.greymagic.com/security/advisories/gm005-mc/) on IE6/7/8?
```
<HTML><BODY>
<?xml:namespace prefix="t" ns="urn:schemas-microsoft-com:time">
<?import namespace="t" implementation="#default#time2">
<t:set attributeName="innerHTML" to="XSS<SCRIPT DEFER>alert("XSS")</SCRIPT>">
</BODY></HTML>
```
How about this attack that works on IE6?
```
<TABLE BACKGROUND="javascript:alert('XSS')">
```
How about attacks that are not listed on this site? The problem with Jeff's approach is that it's not a whitelist, as claimed. As someone on [that page](http://refactormycode.com/codes/333-sanitize-html#refactor_13642) adeptly notes:
>
> The problem with it, is that the html
> must be clean. There are cases where
> you can pass in hacked html, and it
> won't match it, in which case it'll
> return the hacked html string as it
> won't match anything to replace. This
> isn't strictly whitelisting.
>
>
>
I would suggest a purpose built tool like [AntiSamy](http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project). It works by actually parsing the HTML, and then traversing the DOM and removing anything that's not in the *configurable* whitelist. The major difference is the ability to gracefully handle malformed HTML.
The best part is that it actually unit tests for all the XSS attacks on the above site. Besides, what could be easier than this API call:
```
public String toSafeHtml(String html) throws ScanException, PolicyException {
Policy policy = Policy.getInstance(POLICY_FILE);
AntiSamy antiSamy = new AntiSamy();
CleanResults cleanResults = antiSamy.scan(html, policy);
return cleanResults.getCleanHTML().trim();
}
``` |
24,730 | <p>I'm doing a little bit of work on a horrid piece of software built by Bangalores best.</p>
<p>It's written in mostly classic ASP/VbScript, but "ported" to ASP.NET, though most of the code is classic ASP style in the ASPX pages :(</p>
<p>I'm getting this message when it tries to connect to my local database:</p>
<p><strong>Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.</strong></p>
<pre><code>Line 38: MasterConn = New ADODB.Connection()
Line 39: MasterConn.connectiontimeout = 10000
Line 40: MasterConn.Open(strDB)
</code></pre>
<p>Anybody have a clue what this error means? Its connecting to my local machine (running SQLEXPRESS) using this connection string:</p>
<pre><code>PROVIDER=MSDASQL;DRIVER={SQL Server};Server=JONATHAN-PC\SQLEXPRESS\;DATABASE=NetTraining;Integrated Security=true
</code></pre>
<p>Which is the connection string that it was initially using, I just repointed it at my database.</p>
<p><strong>UPDATE:</strong></p>
<p>The issue was using "Integrated Security" with ADO. I changed to using a user account and it connected just fine.</p>
| [
{
"answer_id": 24744,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 3,
"selected": true,
"text": "<p>I ran into this a long time ago with working in ASP. I found this knowledge base article and it helped me out. I hope ... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I'm doing a little bit of work on a horrid piece of software built by Bangalores best.
It's written in mostly classic ASP/VbScript, but "ported" to ASP.NET, though most of the code is classic ASP style in the ASPX pages :(
I'm getting this message when it tries to connect to my local database:
**Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.**
```
Line 38: MasterConn = New ADODB.Connection()
Line 39: MasterConn.connectiontimeout = 10000
Line 40: MasterConn.Open(strDB)
```
Anybody have a clue what this error means? Its connecting to my local machine (running SQLEXPRESS) using this connection string:
```
PROVIDER=MSDASQL;DRIVER={SQL Server};Server=JONATHAN-PC\SQLEXPRESS\;DATABASE=NetTraining;Integrated Security=true
```
Which is the connection string that it was initially using, I just repointed it at my database.
**UPDATE:**
The issue was using "Integrated Security" with ADO. I changed to using a user account and it connected just fine. | I ran into this a long time ago with working in ASP. I found this knowledge base article and it helped me out. I hope it solves your problem.
<http://support.microsoft.com/kb/269495>
If this doesn't work and everything checks out, then it is probably your connection string. I would try these steps next:
Remove:
```
DRIVER={SQL Server};
```
Edit the Provider to this:
```
Provider=SQLOLEDB;
``` |
24,734 | <p>I'm trying to add support for stackoverflow feeds in my rss reader but <strong>SelectNodes</strong> and <strong>SelectSingleNode</strong> have no effect. This is probably something to do with ATOM and xml namespaces that I just don't understand yet.</p>
<p>I have gotten it to work by removing all attributes from the <strong>feed</strong> tag, but that's a hack and I would like to do it properly. So, how do you use <strong>SelectNodes</strong> with atom feeds?</p>
<p>Here's a snippet of the feed.</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0">
<title type="html">StackOverflow.com - Questions tagged: c</title>
<link rel="self" href="http://stackoverflow.com/feeds/tag/c" type="application/atom+xml" />
<subtitle>Check out the latest from StackOverflow.com</subtitle>
<updated>2008-08-24T12:25:30Z</updated>
<id>http://stackoverflow.com/feeds/tag/c</id>
<creativeCommons:license>http://www.creativecommons.org/licenses/by-nc/2.5/rdf</creativeCommons:license>
<entry>
<id>http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server</id>
<title type="html">What is the best way to communicate with a SQL server?</title>
<category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c++" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="sql" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="mysql" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="database" />
<author><name>Ed</name></author>
<link rel="alternate" href="http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server" />
<published>2008-08-22T05:09:04Z</published>
<updated>2008-08-23T04:52:39Z</updated>
<summary type="html">&lt;p&gt;I am going to be using c/c++, and would like to know the best way to talk to a MySQL server. Should I use the library that comes with the server installation? Are they any good libraries I should consider other than the official one?&lt;/p&gt;</summary>
<link rel="replies" type="application/atom+xml" href="http://stackoverflow.com/feeds/question/22901/answers" thr:count="2"/>
<thr:total>2</thr:total>
</entry>
</feed>
</code></pre>
<p><br/></p>
<h2>The Solution</h2>
<pre><code>XmlDocument doc = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
doc.Load(feed);
// successful
XmlNodeList itemList = doc.DocumentElement.SelectNodes("atom:entry", nsmgr);
</code></pre>
| [
{
"answer_id": 24738,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>You've guessed correctly: you're asking for nodes not in a namespace, but these nodes are in a namespace.</p>\n\n<p>De... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1147/"
] | I'm trying to add support for stackoverflow feeds in my rss reader but **SelectNodes** and **SelectSingleNode** have no effect. This is probably something to do with ATOM and xml namespaces that I just don't understand yet.
I have gotten it to work by removing all attributes from the **feed** tag, but that's a hack and I would like to do it properly. So, how do you use **SelectNodes** with atom feeds?
Here's a snippet of the feed.
```xml
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0">
<title type="html">StackOverflow.com - Questions tagged: c</title>
<link rel="self" href="http://stackoverflow.com/feeds/tag/c" type="application/atom+xml" />
<subtitle>Check out the latest from StackOverflow.com</subtitle>
<updated>2008-08-24T12:25:30Z</updated>
<id>http://stackoverflow.com/feeds/tag/c</id>
<creativeCommons:license>http://www.creativecommons.org/licenses/by-nc/2.5/rdf</creativeCommons:license>
<entry>
<id>http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server</id>
<title type="html">What is the best way to communicate with a SQL server?</title>
<category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c++" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="sql" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="mysql" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="database" />
<author><name>Ed</name></author>
<link rel="alternate" href="http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server" />
<published>2008-08-22T05:09:04Z</published>
<updated>2008-08-23T04:52:39Z</updated>
<summary type="html"><p>I am going to be using c/c++, and would like to know the best way to talk to a MySQL server. Should I use the library that comes with the server installation? Are they any good libraries I should consider other than the official one?</p></summary>
<link rel="replies" type="application/atom+xml" href="http://stackoverflow.com/feeds/question/22901/answers" thr:count="2"/>
<thr:total>2</thr:total>
</entry>
</feed>
```
The Solution
------------
```
XmlDocument doc = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
doc.Load(feed);
// successful
XmlNodeList itemList = doc.DocumentElement.SelectNodes("atom:entry", nsmgr);
``` | Don't confuse the namespace names in the XML file with the namespace names for your namespace manager. They're both shortcuts, and they don't necessarily have to match.
So you can register "<http://www.w3.org/2005/Atom>" as "atom", and then do a SelectNodes for "atom:entry". |
24,797 | <p>What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is.</p>
<p>CLR integration isn't an option for me either.</p>
<p>The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup)</p>
| [
{
"answer_id": 25032,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>Maintain a TimeZone table, or shell out with an extended stored proc (xp_cmdshell or a COM component, or your own) a... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1950/"
] | What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is.
CLR integration isn't an option for me either.
The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup) | Create two tables and then join to them to convert stored GMT dates to local time:
```
TimeZones e.g.
--------- ----
TimeZoneId 19
Name Eastern (GMT -5)
Offset -5
```
Create the daylight savings table and populate it with as much information as you can (local laws change all the time so there's no way to predict what the data will look like years in the future)
```
DaylightSavings
---------------
TimeZoneId 19
BeginDst 3/9/2008 2:00 AM
EndDst 11/2/2008 2:00 AM
```
Join them like this:
```
inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId
left join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone
and x.TheDateToConvert between ds.BeginDst and ds.EndDst
```
Convert dates like this:
```
dateadd(hh, tz.Offset +
case when ds.LocalTimeZone is not null
then 1 else 0 end, TheDateToConvert)
``` |
24,816 | <p>Does anyone know of an easy way to escape HTML from strings in <a href="http://jquery.com/" rel="noreferrer">jQuery</a>? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.</p>
| [
{
"answer_id": 24870,
"author": "tghw",
"author_id": 2363,
"author_profile": "https://Stackoverflow.com/users/2363",
"pm_score": 6,
"selected": false,
"text": "<p>If you're escaping for HTML, there are only three that I can think of that would be really necessary:</p>\n\n<pre><code>html.... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2657/"
] | Does anyone know of an easy way to escape HTML from strings in [jQuery](http://jquery.com/)? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this. | Since you're using [jQuery](https://jquery.com/), you can just set the element's [`text`](http://api.jquery.com/text/) property:
```
// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";
// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after:
// <div class="someClass"><script>alert('hi!');</script></div>
// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value:
// <script>alert('hi!');</script>
``` |
24,821 | <p>This problem started <a href="http://forums.asp.net/t/1304033.aspx" rel="nofollow noreferrer">on a different board</a>, but <a href="https://stackoverflow.com/users/60/dave-ward">Dave Ward</a>, who was very prompt and helpful there is also here, so I'd like to pick up here for hopefully the last remaining piece of the puzzle.</p>
<p>Basically, I was looking for a way to do constant updates to a web page from a long process. I thought AJAX was the way to go, but Dave has <a href="http://encosia.com/2007/10/03/easy-incremental-status-updates-for-long-requests/" rel="nofollow noreferrer">a nice article about using JavaScript</a>. I integrated it into my application and it worked great on my client, but NOT my server WebHost4Life. I have another server @ Brinkster and decided to try it there and it DOES work. All the code is the same on my client, WebHost4Life, and Brinkster, so there's obviously something going on with WebHost4Life.</p>
<p>I'm planning to write an email to them or request technical support, but I'd like to be proactive and try to figure out what could be going on with their end to cause this difference. I did everything I could with my code to turn off Buffering like <code>Page.Response.BufferOutput = False</code>. What server settings could they have implemented to cause this difference? Is there any way I could circumvent it on my own without their help? If not, what would they need to do?</p>
<p>For reference, a link to the working version of a simpler version of my application is located @ <a href="http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx" rel="nofollow noreferrer">http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx</a> and the same version that isn't working is located @ <a href="http://www.tabroom.org/Ajaxfun/Default.aspx" rel="nofollow noreferrer">http://www.tabroom.org/Ajaxfun/Default.aspx</a>. You'll notice in the working version, you get updates with each step, but in the one that doesn't, it sits there for a long time until everything is done and then does all the updates to the client at once ... and that makes me sad.</p>
| [
{
"answer_id": 25031,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know that you can force buffering - but a reverse proxy server between you and the server would affect buffe... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1953/"
] | This problem started [on a different board](http://forums.asp.net/t/1304033.aspx), but [Dave Ward](https://stackoverflow.com/users/60/dave-ward), who was very prompt and helpful there is also here, so I'd like to pick up here for hopefully the last remaining piece of the puzzle.
Basically, I was looking for a way to do constant updates to a web page from a long process. I thought AJAX was the way to go, but Dave has [a nice article about using JavaScript](http://encosia.com/2007/10/03/easy-incremental-status-updates-for-long-requests/). I integrated it into my application and it worked great on my client, but NOT my server WebHost4Life. I have another server @ Brinkster and decided to try it there and it DOES work. All the code is the same on my client, WebHost4Life, and Brinkster, so there's obviously something going on with WebHost4Life.
I'm planning to write an email to them or request technical support, but I'd like to be proactive and try to figure out what could be going on with their end to cause this difference. I did everything I could with my code to turn off Buffering like `Page.Response.BufferOutput = False`. What server settings could they have implemented to cause this difference? Is there any way I could circumvent it on my own without their help? If not, what would they need to do?
For reference, a link to the working version of a simpler version of my application is located @ <http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx> and the same version that isn't working is located @ <http://www.tabroom.org/Ajaxfun/Default.aspx>. You'll notice in the working version, you get updates with each step, but in the one that doesn't, it sits there for a long time until everything is done and then does all the updates to the client at once ... and that makes me sad. | Hey, Jason. Sorry you're still having trouble with this.
What I would do is set up a simple page like:
```
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
Response.Write(i + "<br />");
Response.Flush();
Thread.Sleep(1000);
}
}
```
As we discussed before, make sure the .aspx file is empty of any markup other than the @Page declaration. That can sometimes trigger page buffering when it wouldn't have normally happened.
Then, point the tech support guys to that file and describe the desired behavior (10 updates, 1 per second). I've found that giving them a simple test case goes a long way toward getting these things resolved.
Definitely let us know what it ends up being. I'm guessing some sort of inline caching or reverse proxy, but I'm curious. |
24,829 | <pre><code>public class MyClass
{
public int Age;
public int ID;
}
public void MyMethod()
{
MyClass m = new MyClass();
int newID;
}
</code></pre>
<p>To my understanding, the following is true:</p>
<ol>
<li>The reference m lives on the stack and goes out of scope when MyMethod() exits.</li>
<li>The value type newID lives on the stack and goes out of scope when MyMethod() exits.</li>
<li>The object created by the new operator lives in the heap and becomes reclaimable by the GC when MyMethod() exits, assuming no other reference to the object exists. </li>
</ol>
<p>Here is my question:</p>
<ol>
<li>Do value types within objects live on the stack or the heap?</li>
<li>Is boxing/unboxing value types in an object a concern?</li>
<li>Are there any detailed, yet understandable, resources on this topic?</li>
</ol>
<p>Logically, I'd think value types inside classes would be in the heap, but I'm not sure if they have to be boxed to get there.</p>
<p>Edit:</p>
<p>Suggested reading for this topic:</p>
<ol>
<li><a href="http://www.microsoft.com/MSPress/books/6522.aspx" rel="nofollow noreferrer">CLR Via C# by Jeffrey Richter</a></li>
<li><a href="http://books.google.com/books?id=Kl1DVZ8wTqcC&dq=essential+.net&pg=PP1&ots=5a-UEHSLVJ&sig=D2_xn2kzMnP8zLXDVIV6AJtfbCY&hl=en&sa=X&oi=book_result&resnum=1&ct=result#PPP1,M1" rel="nofollow noreferrer">Essential .NET by Don Box</a></li>
</ol>
| [
{
"answer_id": 24832,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Any references or value types that an object own live in the heap.</li>\n<li>Only if you're casting ints to Objects.<... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1880/"
] | ```
public class MyClass
{
public int Age;
public int ID;
}
public void MyMethod()
{
MyClass m = new MyClass();
int newID;
}
```
To my understanding, the following is true:
1. The reference m lives on the stack and goes out of scope when MyMethod() exits.
2. The value type newID lives on the stack and goes out of scope when MyMethod() exits.
3. The object created by the new operator lives in the heap and becomes reclaimable by the GC when MyMethod() exits, assuming no other reference to the object exists.
Here is my question:
1. Do value types within objects live on the stack or the heap?
2. Is boxing/unboxing value types in an object a concern?
3. Are there any detailed, yet understandable, resources on this topic?
Logically, I'd think value types inside classes would be in the heap, but I'm not sure if they have to be boxed to get there.
Edit:
Suggested reading for this topic:
1. [CLR Via C# by Jeffrey Richter](http://www.microsoft.com/MSPress/books/6522.aspx)
2. [Essential .NET by Don Box](http://books.google.com/books?id=Kl1DVZ8wTqcC&dq=essential+.net&pg=PP1&ots=5a-UEHSLVJ&sig=D2_xn2kzMnP8zLXDVIV6AJtfbCY&hl=en&sa=X&oi=book_result&resnum=1&ct=result#PPP1,M1) | Value-type values for a class *have* to live together with the object instance in the managed heap. The thread's stack for a method only lives for the duration of a method; how can the value persist if it only exists within that stack?
A class' object size in the managed heap is the sum of its value-type fields, reference-type pointers, and additional CLR overhead variables like the Sync block index. When one assigns a value to an object's value-type field, the CLR copies the value to the space allocated within the object for that particluar field.
Take for example, a simple class with a single field.
```
public class EmbeddedValues
{
public int NumberField;
}
```
And with it, a simple testing class.
```
public class EmbeddedTest
{
public void TestEmbeddedValues()
{
EmbeddedValues valueContainer = new EmbeddedValues();
valueContainer.NumberField = 20;
int publicField = valueContainer.NumberField;
}
}
```
If you use the MSIL Disassembler provided by the .NET Framework SDK to peek at the IL code for EmbeddedTest.TestEmbeddedValues()
```
.method public hidebysig instance void TestEmbeddedValues() cil managed
{
// Code size 23 (0x17)
.maxstack 2
.locals init ([0] class soapextensions.EmbeddedValues valueContainer,
[1] int32 publicField)
IL_0000: nop
IL_0001: newobj instance void soapextensions.EmbeddedValues::.ctor()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.s 20
IL_000a: stfld int32 soapextensions.EmbeddedValues::NumberField
IL_000f: ldloc.0
IL_0010: ldfld int32 soapextensions.EmbeddedValues::NumberField
IL_0015: stloc.1
IL_0016: ret
} // end of method EmbeddedTest::TestEmbeddedValues
```
Notice the CLR is being told to **stfld** the loaded value of "20" in the stack to the loaded EmbeddValues' NumberField field location, directly into the managed heap. Similarly, when retrieving the value, it uses **ldfld** instruction to directly copy the value out of that managed heap location into the thread stack. No box/unboxing happens with these types of operations. |
24,849 | <p>Is there any JavaScript method similar to the jQuery <code>delay()</code> or <code>wait()</code> (to delay the execution of a script for a specific amount of time)?</p>
| [
{
"answer_id": 24850,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 4,
"selected": false,
"text": "<p>You need to use <a href=\"http://www.w3schools.com/jsref/met_win_settimeout.asp\" rel=\"noreferrer\">setTimeout</a> and pass... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | Is there any JavaScript method similar to the jQuery `delay()` or `wait()` (to delay the execution of a script for a specific amount of time)? | There is the following:
```
setTimeout(function, milliseconds);
```
function which can be passed the time after which the function will be executed.
See: [Window `setTimeout()` Method](https://www.w3schools.com/jsref/met_win_settimeout.asp). |
24,853 | <p>In C, what is the difference between using <code>++i</code> and <code>i++</code>, and which should be used in the incrementation block of a <code>for</code> loop?</p>
| [
{
"answer_id": 24856,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 6,
"selected": false,
"text": "<p><code>++i</code> increments the value, then returns it.</p>\n\n<p><code>i++</code> returns the value, and then increments it.... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] | In C, what is the difference between using `++i` and `i++`, and which should be used in the incrementation block of a `for` loop? | * `++i` will increment the value of `i`, and then return the incremented value.
```
i = 1;
j = ++i;
(i is 2, j is 2)
```
* `i++` will increment the value of `i`, but return the original value that `i` held before being incremented.
```
i = 1;
j = i++;
(i is 2, j is 1)
```
For a `for` loop, either works. `++i` seems more common, perhaps because that is what is used in [K&R](https://en.wikipedia.org/wiki/The_C_Programming_Language).
In any case, follow the guideline "prefer `++i` over `i++`" and you won't go wrong.
There's a couple of comments regarding the efficiency of `++i` and `i++`. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.
The efficiency question is interesting... here's my attempt at an answer:
[Is there a performance difference between i++ and ++i in C?](https://stackoverflow.com/questions/24886/is-there-a-performance-difference-between-i-and-i)
As [@OnFreund](https://stackoverflow.com/users/2150/on-freund) notes, it's different for a C++ object, since `operator++()` is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value. |
24,881 | <p>I'm trying to solve <a href="http://uva.onlinejudge.org/external/1/100.pdf" rel="noreferrer">the 3n+1 problem</a> and I have a <code>for</code> loop that looks like this: </p>
<pre><code>for(int i = low; i <= high; ++i)
{
res = runalg(i);
if (res > highestres)
{
highestres = res;
}
}
</code></pre>
<p>Unfortunately I'm getting this error when I try to compile with GCC:</p>
<blockquote>
<p>3np1.c:15: error: 'for' loop initial
declaration used outside C99 mode</p>
</blockquote>
<p>I don't know what C99 mode is. Any ideas?</p>
| [
{
"answer_id": 24882,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 8,
"selected": true,
"text": "<p>I'd try to declare <code>i</code> outside of the loop!</p>\n\n<p>Good luck on solving 3n+1 :-)</p>\n\n<p>Here's an example:... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] | I'm trying to solve [the 3n+1 problem](http://uva.onlinejudge.org/external/1/100.pdf) and I have a `for` loop that looks like this:
```
for(int i = low; i <= high; ++i)
{
res = runalg(i);
if (res > highestres)
{
highestres = res;
}
}
```
Unfortunately I'm getting this error when I try to compile with GCC:
>
> 3np1.c:15: error: 'for' loop initial
> declaration used outside C99 mode
>
>
>
I don't know what C99 mode is. Any ideas? | I'd try to declare `i` outside of the loop!
Good luck on solving 3n+1 :-)
Here's an example:
```c
#include <stdio.h>
int main() {
int i;
/* for loop execution */
for (i = 10; i < 20; i++) {
printf("i: %d\n", i);
}
return 0;
}
```
Read more on for loops in C [here](https://www.tutorialspoint.com/cprogramming/c_for_loop.htm). |
24,886 | <p>Is there a performance difference between <code>i++</code> and <code>++i</code> if the resulting value is not used?</p>
| [
{
"answer_id": 24887,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 10,
"selected": true,
"text": "<p>Executive summary: No.</p>\n\n<p><code>i++</code> could potentially be slower than <code>++i</code>, since the old va... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | Is there a performance difference between `i++` and `++i` if the resulting value is not used? | Executive summary: No.
`i++` could potentially be slower than `++i`, since the old value of `i`
might need to be saved for later use, but in practice all modern
compilers will optimize this away.
We can demonstrate this by looking at the code for this function,
both with `++i` and `i++`.
```
$ cat i++.c
extern void g(int i);
void f()
{
int i;
for (i = 0; i < 100; i++)
g(i);
}
```
The files are the same, except for `++i` and `i++`:
```
$ diff i++.c ++i.c
6c6
< for (i = 0; i < 100; i++)
---
> for (i = 0; i < 100; ++i)
```
We'll compile them, and also get the generated assembler:
```
$ gcc -c i++.c ++i.c
$ gcc -S i++.c ++i.c
```
And we can see that both the generated object and assembler files are the same.
```
$ md5 i++.s ++i.s
MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e
MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e
$ md5 *.o
MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22
MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22
``` |
24,891 | <p>I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case.</p>
<p>Can someone show me (with code examples) an example of when you would have to do some "memory management" ?</p>
| [
{
"answer_id": 24893,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>You have to do \"memory management\" when you want to use memory on the heap rather than the stack. If you don't know ho... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] | I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case.
Can someone show me (with code examples) an example of when you would have to do some "memory management" ? | There are two places where variables can be put in memory. When you create a variable like this:
```
int a;
char c;
char d[16];
```
The variables are created in the "**stack**". Stack variables are automatically freed when they go out of scope (that is, when the code can't reach them anymore). You might hear them called "automatic" variables, but that has fallen out of fashion.
Many beginner examples will use only stack variables.
The stack is nice because it's automatic, but it also has two drawbacks: (1) The compiler needs to know in advance how big the variables are, and (2) the stack space is somewhat limited. For example: in Windows, under default settings for the Microsoft linker, the stack is set to 1 MB, and not all of it is available for your variables.
If you don't know at compile time how big your array is, or if you need a big array or struct, you need "plan B".
Plan B is called the "**heap**". You can usually create variables as big as the Operating System will let you, but you have to do it yourself. Earlier postings showed you one way you can do it, although there are other ways:
```
int size;
// ...
// Set size to some value, based on information available at run-time. Then:
// ...
char *p = (char *)malloc(size);
```
(Note that variables in the heap are not manipulated directly, but via pointers)
Once you create a heap variable, the problem is that the compiler can't tell when you're done with it, so you lose the automatic releasing. That's where the "manual releasing" you were referring to comes in. Your code is now responsible to decide when the variable is not needed anymore, and release it so the memory can be taken for other purposes. For the case above, with:
```
free(p);
```
What makes this second option "nasty business" is that it's not always easy to know when the variable is not needed anymore. Forgetting to release a variable when you don't need it will cause your program to consume more memory that it needs to. This situation is called a "leak". The "leaked" memory cannot be used for anything until your program ends and the OS recovers all of its resources. Even nastier problems are possible if you release a heap variable by mistake *before* you are actually done with it.
In C and C++, you are responsible to clean up your heap variables like shown above. However, there are languages and environments such as Java and .NET languages like C# that use a different approach, where the heap gets cleaned up on its own. This second method, called "garbage collection", is much easier on the developer but you pay a penalty in overhead and performance. It's a balance.
*(I have glossed over many details to give a simpler, but hopefully more leveled answer)* |
24,901 | <p>We have the question <a href="/q/24886">is there a performance difference between <code>i++</code> and <code>++i</code> <strong>in C</strong>?</a></p>
<p>What's the answer for C++?</p>
| [
{
"answer_id": 24904,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 10,
"selected": true,
"text": "<p>[Executive Summary: Use <code>++i</code> if you don't have a specific reason to use <code>i++</code>.]</p>\n\n<p>For C... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | We have the question [is there a performance difference between `i++` and `++i` **in C**?](/q/24886)
What's the answer for C++? | [Executive Summary: Use `++i` if you don't have a specific reason to use `i++`.]
For C++, the answer is a bit more complicated.
If `i` is a simple type (not an instance of a C++ class), [then the answer given for C ("No there is no performance difference")](https://stackoverflow.com/a/24887/194894) holds, since the compiler is generating the code.
However, if `i` is an instance of a C++ class, then `i++` and `++i` are making calls to one of the `operator++` functions. Here's a standard pair of these functions:
```
Foo& Foo::operator++() // called for ++i
{
this->data += 1;
return *this;
}
Foo Foo::operator++(int ignored_dummy_value) // called for i++
{
Foo tmp(*this); // variable "tmp" cannot be optimized away by the compiler
++(*this);
return tmp;
}
```
Since the compiler isn't generating code, but just calling an `operator++` function, there is no way to optimize away the `tmp` variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact. |
24,915 | <p>My colleagues are attempting to connect BizTalk 2006 R2 via DB2/MVS adapter to a database hosted on z/OS mainframe. When testing the connecting settings, they are getting the following error</p>
<pre><code>Could not connect to data source 'New Data Source':
The network connection was terminated because the host failed to send any data.
SQLSTATE: 08S01, SQLCODE: -605
</code></pre>
<p>When putting the settings in a regular connection string and opening with .NET code, that is fine. I am new to BizTalk and DB2. Can anybody suggest what to look out for when this error surfaces?</p>
<p><strong>24 Aug 08:</strong></p>
<p>Well, if normal .NET code with a regular DB2 connection string is used, the connection can be made and queries submitted. What this DB2 adapter is reporting is it cannot even make a proper connection handshake, let alone submitting queries. I am unsure of what are the actual mechanisms involved to make a DB2 connection happen.</p>
<p><strong>25 Aug 08:</strong></p>
<blockquote>
<p>According to <a href="http://forums.microsoft.com/msdn/showpost.aspx?postid=1155829&siteid=1&sb=0&d=1&at=7&ft=11&tf=0&pageid=0" rel="nofollow noreferrer">this MSDN forums posting</a>, it seems to be a login issue.</p>
</blockquote>
<p>I have seen that and that is not the case here. If we put the user name as the Package Collection it still hits the same problem.</p>
<p><strong>26 Aug 08:</strong></p>
<p>Because of the scarcity of information regarding connecting to mainframe DB2 databases from Microsoft products, I undertook the task of inspecting raw network packets to get a clue what is going on between the .NET DB2 provider's connection (which works) and the BizTalk 2006 DB2 adapter (which bombs). I observed DB2 traffic is done using the DRDA protocol. And ultimately concluded the BizTalk adapter method fails because of what's recorded in the server's reply SECCHKRM packet</p>
<pre><code>DRDA (Security Check)
DDM (SECCHKRM)
Length: 55
Magic: 0xd0
Format: 0x02
0... = Reserved: Not set
.0.. = Chained: Not set
..0. = Continue: Not set
...0 = Same correlation: Not set
DSS type: RPYDSS (2)
CorrelId: 0
Length2: 49
Code point: SECCHKRM (0x1219)
Parameter (Severity Code)
Length: 6
Code point: SVRCOD (0x1149)
Data (ASCII):
Data (EBCDIC):
Parameter (Security Check Code)
Length: 5
Code point: SECCHKCD (0x11a4)
Data (ASCII):
Data (EBCDIC):
Parameter (Server Diagnostic Information)
Length: 34
Code point: SRVDGN (0x1153)
Data (ASCII): \304\331\304\301@\301\331z@\301\344\343\310\305\325\343\311\303\301\343\311\326\325@\206\201\211\223\205\204
Data (EBCDIC): DRDA AR: AUTHENTICATION failed
</code></pre>
<p>Why the same credentials fails here while succeeding in the .NET provider is beyond me. Right now, what I can observe is a marked difference between each method when it comes to the sequence of packets transferred.</p>
<p>.NET DB2 provider</p>
<pre><code>No. Time Source Destination Protocol Info
1 0.000000 [client IP] [DB2 server IP] TCP kpop > 50000 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=1
2 0.000399 [DB2 server IP] [client IP] TCP 50000 > kpop [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0
3 0.000414 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1 Ack=1 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
4 0.000532 [client IP] [DB2 server IP] DRDA EXCSAT | ACCSEC
5 0.038162 [DB2 server IP] [client IP] DRDA EXCSATRD | ACCSECRD
6 0.041829 [client IP] [DB2 server IP] DRDA ACCSEC | SECCHK | ACCRDB
7 0.083626 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=108 Ack=542 Win=65535 Len=0
8 0.190534 [DB2 server IP] [client IP] DRDA ACCSECRD | SECCHKRM | ACCRDBRM | SQLCARD
9 0.199776 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
10 0.293307 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
11 0.293359 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
12 0.293377 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=1444 Win=64092 [TCP CHECKSUM INCORRECT] Len=0
13 0.293404 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
14 0.293452 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
15 0.293461 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=2516 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
16 0.293855 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
17 0.293908 [DB2 server IP] [client IP] DRDA SQLDARD
18 0.293918 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=3588 Win=64464 [TCP CHECKSUM INCORRECT] Len=0
19 0.293957 [DB2 server IP] [client IP] DRDA QRYDSC
20 0.294008 [DB2 server IP] [client IP] DRDA QRYDTA
21 0.294017 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=4660 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
22 0.294023 [DB2 server IP] [client IP] DRDA SQLCARD
23 0.295346 [client IP] [DB2 server IP] DRDA RDBCMM
24 0.297868 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
25 0.421392 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
26 0.456504 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD
27 0.456756 [client IP] [DB2 server IP] DRDA RDBCMM
28 0.488311 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
29 0.498806 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
30 0.630477 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=5157 Ack=1579 Win=65171 Len=0
31 0.788165 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA
32 0.788203 [DB2 server IP] [client IP] DRDA ENDQRYRM
33 0.788225 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1579 Ack=5815 Win=64380 [TCP CHECKSUM INCORRECT] Len=0
34 0.788648 [client IP] [DB2 server IP] DRDA RDBCMM
35 0.795951 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
36 0.807365 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
37 0.838046 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD
38 0.838328 [client IP] [DB2 server IP] DRDA RDBCMM
39 0.841866 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
40 0.973506 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1906 Ack=6304 Win=65482 [TCP CHECKSUM INCORRECT] Len=0
</code></pre>
<p>BizTalk DB2 adapter</p>
<pre><code>No. Time Source Destination Protocol Info
1 0.000000 [client IP] [DB2 server IP] TCP 28165 > 50000 [SYN] Seq=0 Win=8192 Len=0 MSS=1460 WS=8
2 0.002587 [DB2 server IP] [client IP] TCP 50000 > 28165 [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0
3 0.010146 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=1 Ack=1 Win=65536 Len=0
4 0.019698 [client IP] [DB2 server IP] DRDA EXCSAT
5 0.020849 [DB2 server IP] [client IP] DRDA EXCSATRD
6 0.034699 [client IP] [DB2 server IP] DRDA ACCSEC
7 0.036584 [DB2 server IP] [client IP] DRDA ACCSECRD
8 0.042031 [client IP] [DB2 server IP] DRDA SECCHK
9 0.046350 [DB2 server IP] [client IP] DRDA SECCHKRM
10 0.046642 [DB2 server IP] [client IP] TCP 50000 > 28165 [FIN, ACK] Seq=160 Ack=200 Win=65336 Len=0
11 0.053787 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=200 Ack=161 Win=65536 Len=0
12 0.056891 [client IP] [DB2 server IP] DRDA ACCRDB
13 0.058084 [DB2 server IP] [client IP] TCP 50000 > 28165 [RST, ACK] Seq=161 Ack=295 Win=0 Len=0
</code></pre>
<p>It is interesting to witness the .NET provider issue out various DRDA protocol packets within in a single TCP segment. The BizTalk adapter on the other hand, places only one protocol packet per TCP segment. I do not know why this is so. However, I at the moment think that is a red herring and the true difference causing the failure in authentication is in the DRDA data exchange. I do not know the DRDA protocol so will have to study it before I can make more sense of it.</p>
<p><strong>18 Sep 08:</strong></p>
<p>At this stage the problem is still not solved, as getting cooperation from the DB2 DBA team and help from Microsoft have been met with many obstacles.</p>
<p>What I do want to report is, I have observed perhaps one crucial difference between all the cases of successful connection versus the failed attempt:</p>
<p>The BizTalk DB2 adapter is underlyingly using <strong>Microsoft ODBC Driver for DB2</strong>. The other software tests that succeed make use of <strong>IBM DB2 ODBC DRIVER</strong> or <strong>IBM DB2 ODBC DRIVER – IBMCL1</strong>. The IBM driver's parameter configuration is different from Microsoft's driver. But we do not see any obviously critical difference that may lead to a failed authentication for the Microsoft driver.</p>
| [
{
"answer_id": 24925,
"author": "Sean Kearon",
"author_id": 2608,
"author_profile": "https://Stackoverflow.com/users/2608",
"pm_score": 0,
"selected": false,
"text": "<p>I've never used this adapter but myself, so I'm guessing, but maybe it's to do with the account that BizTalk is using ... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2663/"
] | My colleagues are attempting to connect BizTalk 2006 R2 via DB2/MVS adapter to a database hosted on z/OS mainframe. When testing the connecting settings, they are getting the following error
```
Could not connect to data source 'New Data Source':
The network connection was terminated because the host failed to send any data.
SQLSTATE: 08S01, SQLCODE: -605
```
When putting the settings in a regular connection string and opening with .NET code, that is fine. I am new to BizTalk and DB2. Can anybody suggest what to look out for when this error surfaces?
**24 Aug 08:**
Well, if normal .NET code with a regular DB2 connection string is used, the connection can be made and queries submitted. What this DB2 adapter is reporting is it cannot even make a proper connection handshake, let alone submitting queries. I am unsure of what are the actual mechanisms involved to make a DB2 connection happen.
**25 Aug 08:**
>
> According to [this MSDN forums posting](http://forums.microsoft.com/msdn/showpost.aspx?postid=1155829&siteid=1&sb=0&d=1&at=7&ft=11&tf=0&pageid=0), it seems to be a login issue.
>
>
>
I have seen that and that is not the case here. If we put the user name as the Package Collection it still hits the same problem.
**26 Aug 08:**
Because of the scarcity of information regarding connecting to mainframe DB2 databases from Microsoft products, I undertook the task of inspecting raw network packets to get a clue what is going on between the .NET DB2 provider's connection (which works) and the BizTalk 2006 DB2 adapter (which bombs). I observed DB2 traffic is done using the DRDA protocol. And ultimately concluded the BizTalk adapter method fails because of what's recorded in the server's reply SECCHKRM packet
```
DRDA (Security Check)
DDM (SECCHKRM)
Length: 55
Magic: 0xd0
Format: 0x02
0... = Reserved: Not set
.0.. = Chained: Not set
..0. = Continue: Not set
...0 = Same correlation: Not set
DSS type: RPYDSS (2)
CorrelId: 0
Length2: 49
Code point: SECCHKRM (0x1219)
Parameter (Severity Code)
Length: 6
Code point: SVRCOD (0x1149)
Data (ASCII):
Data (EBCDIC):
Parameter (Security Check Code)
Length: 5
Code point: SECCHKCD (0x11a4)
Data (ASCII):
Data (EBCDIC):
Parameter (Server Diagnostic Information)
Length: 34
Code point: SRVDGN (0x1153)
Data (ASCII): \304\331\304\301@\301\331z@\301\344\343\310\305\325\343\311\303\301\343\311\326\325@\206\201\211\223\205\204
Data (EBCDIC): DRDA AR: AUTHENTICATION failed
```
Why the same credentials fails here while succeeding in the .NET provider is beyond me. Right now, what I can observe is a marked difference between each method when it comes to the sequence of packets transferred.
.NET DB2 provider
```
No. Time Source Destination Protocol Info
1 0.000000 [client IP] [DB2 server IP] TCP kpop > 50000 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=1
2 0.000399 [DB2 server IP] [client IP] TCP 50000 > kpop [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0
3 0.000414 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1 Ack=1 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
4 0.000532 [client IP] [DB2 server IP] DRDA EXCSAT | ACCSEC
5 0.038162 [DB2 server IP] [client IP] DRDA EXCSATRD | ACCSECRD
6 0.041829 [client IP] [DB2 server IP] DRDA ACCSEC | SECCHK | ACCRDB
7 0.083626 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=108 Ack=542 Win=65535 Len=0
8 0.190534 [DB2 server IP] [client IP] DRDA ACCSECRD | SECCHKRM | ACCRDBRM | SQLCARD
9 0.199776 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
10 0.293307 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
11 0.293359 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
12 0.293377 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=1444 Win=64092 [TCP CHECKSUM INCORRECT] Len=0
13 0.293404 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
14 0.293452 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
15 0.293461 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=2516 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
16 0.293855 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
17 0.293908 [DB2 server IP] [client IP] DRDA SQLDARD
18 0.293918 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=3588 Win=64464 [TCP CHECKSUM INCORRECT] Len=0
19 0.293957 [DB2 server IP] [client IP] DRDA QRYDSC
20 0.294008 [DB2 server IP] [client IP] DRDA QRYDTA
21 0.294017 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=4660 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
22 0.294023 [DB2 server IP] [client IP] DRDA SQLCARD
23 0.295346 [client IP] [DB2 server IP] DRDA RDBCMM
24 0.297868 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
25 0.421392 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
26 0.456504 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD
27 0.456756 [client IP] [DB2 server IP] DRDA RDBCMM
28 0.488311 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
29 0.498806 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
30 0.630477 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=5157 Ack=1579 Win=65171 Len=0
31 0.788165 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA
32 0.788203 [DB2 server IP] [client IP] DRDA ENDQRYRM
33 0.788225 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1579 Ack=5815 Win=64380 [TCP CHECKSUM INCORRECT] Len=0
34 0.788648 [client IP] [DB2 server IP] DRDA RDBCMM
35 0.795951 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
36 0.807365 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
37 0.838046 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD
38 0.838328 [client IP] [DB2 server IP] DRDA RDBCMM
39 0.841866 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
40 0.973506 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1906 Ack=6304 Win=65482 [TCP CHECKSUM INCORRECT] Len=0
```
BizTalk DB2 adapter
```
No. Time Source Destination Protocol Info
1 0.000000 [client IP] [DB2 server IP] TCP 28165 > 50000 [SYN] Seq=0 Win=8192 Len=0 MSS=1460 WS=8
2 0.002587 [DB2 server IP] [client IP] TCP 50000 > 28165 [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0
3 0.010146 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=1 Ack=1 Win=65536 Len=0
4 0.019698 [client IP] [DB2 server IP] DRDA EXCSAT
5 0.020849 [DB2 server IP] [client IP] DRDA EXCSATRD
6 0.034699 [client IP] [DB2 server IP] DRDA ACCSEC
7 0.036584 [DB2 server IP] [client IP] DRDA ACCSECRD
8 0.042031 [client IP] [DB2 server IP] DRDA SECCHK
9 0.046350 [DB2 server IP] [client IP] DRDA SECCHKRM
10 0.046642 [DB2 server IP] [client IP] TCP 50000 > 28165 [FIN, ACK] Seq=160 Ack=200 Win=65336 Len=0
11 0.053787 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=200 Ack=161 Win=65536 Len=0
12 0.056891 [client IP] [DB2 server IP] DRDA ACCRDB
13 0.058084 [DB2 server IP] [client IP] TCP 50000 > 28165 [RST, ACK] Seq=161 Ack=295 Win=0 Len=0
```
It is interesting to witness the .NET provider issue out various DRDA protocol packets within in a single TCP segment. The BizTalk adapter on the other hand, places only one protocol packet per TCP segment. I do not know why this is so. However, I at the moment think that is a red herring and the true difference causing the failure in authentication is in the DRDA data exchange. I do not know the DRDA protocol so will have to study it before I can make more sense of it.
**18 Sep 08:**
At this stage the problem is still not solved, as getting cooperation from the DB2 DBA team and help from Microsoft have been met with many obstacles.
What I do want to report is, I have observed perhaps one crucial difference between all the cases of successful connection versus the failed attempt:
The BizTalk DB2 adapter is underlyingly using **Microsoft ODBC Driver for DB2**. The other software tests that succeed make use of **IBM DB2 ODBC DRIVER** or **IBM DB2 ODBC DRIVER – IBMCL1**. The IBM driver's parameter configuration is different from Microsoft's driver. But we do not see any obviously critical difference that may lead to a failed authentication for the Microsoft driver. | Why, it certainly took Microsoft long enough to explicitly confirm this:
**proxy connections via DB2Connect is not supported by BizTalk DB2 Adapter**
Since our customer's policy is to only access DB2 databases via DB2Connect, the adapter is out of the question.
**MORE BACKGROUND INFO**
The reason why the DB2 Adapter only works for a direct connection to a z/OS mainframe host, is due to legal restrictions. Technically it is possible to work a connection with DB2Connect, but IBM has made it a priorietary node and prevented other parties from legally establishing the correct DRDA sequence to connect to it. |
24,929 | <p>What is the difference between the <code>EXISTS</code> and <code>IN</code> clause in SQL?</p>
<p>When should we use <code>EXISTS</code>, and when should we use <code>IN</code>?</p>
| [
{
"answer_id": 24930,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 6,
"selected": false,
"text": "<p>I'm assuming you know what they do, and thus are used differently, so I'm going to understand your question as: Whe... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2528/"
] | What is the difference between the `EXISTS` and `IN` clause in SQL?
When should we use `EXISTS`, and when should we use `IN`? | The `exists` keyword can be used in that way, but really it's intended as a way to avoid counting:
```sql
--this statement needs to check the entire table
select count(*) from [table] where ...
--this statement is true as soon as one match is found
exists ( select * from [table] where ... )
```
This is most useful where you have `if` conditional statements, as `exists` can be a lot quicker than `count`.
The `in` is best used where you have a static list to pass:
```sql
select * from [table]
where [field] in (1, 2, 3)
```
When you have a table in an `in` statement it makes more sense to use a `join`, but mostly it shouldn't matter. The query optimiser should return the same plan either way. In some implementations (mostly older, such as Microsoft SQL Server 2000) `in` queries will always get a [nested join](https://technet.microsoft.com/en-us/library/ms191318(v=sql.105).aspx) plan, while `join` queries will use nested, [merge](https://technet.microsoft.com/en-us/library/ms190967(v=sql.105).aspx) or [hash](https://technet.microsoft.com/en-us/library/ms189313(v=sql.105).aspx) as appropriate. More modern implementations are smarter and can adjust the plan even when `in` is used. |
24,931 | <ol>
<li>Is it possible to capture Python interpreter's output from a Python script?</li>
<li>Is it possible to capture Windows CMD's output from a Python script?</li>
</ol>
<p>If so, which librar(y|ies) should I look into?</p>
| [
{
"answer_id": 24939,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>In which context are you asking?</p>\n\n<p>Are you trying to capture the output from a program you start on the com... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1670/"
] | 1. Is it possible to capture Python interpreter's output from a Python script?
2. Is it possible to capture Windows CMD's output from a Python script?
If so, which librar(y|ies) should I look into? | If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:
```
python script_a.py | python script_b.py
```
This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on [standard streams](http://en.wikipedia.org/wiki/Standard_streams) on Wikipedia.
If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):
```
import subprocess
# Of course you can open things other than python here :)
process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
x = process.stderr.readline()
y = process.stdout.readline()
process.wait()
```
See the Python [subprocess](http://docs.python.org/lib/module-subprocess.html) module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard [file objects](http://docs.python.org/lib/bltin-file-objects.html).
For use with pipes, reading from standard input as [lassevk](https://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939) suggested you'd do something like this:
```
import sys
x = sys.stderr.readline()
y = sys.stdin.readline()
```
sys.stdin and sys.stdout are standard file objects as noted above, defined in the [sys](http://docs.python.org/lib/module-sys.html) module. You might also want to take a look at the [pipes](http://docs.python.org/lib/module-pipes.html) module.
Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into [polling](http://docs.python.org/lib/poll-objects.html) which unfortunately does not work in windows, but I'm sure there's some alternative out there. |
24,941 | <p>I am using <a href="http://www.simpletest.org/" rel="nofollow noreferrer">Simpletest</a> as my unit test framework for the PHP site I am currently working on. I like the fact that it is shipped with a simple HTML reporter, but I would like a bit more advanced reporter.</p>
<p>I have read the reporter API documentation, but it would be nice to be able to use an existing reporter, instead of having to do it yourself.</p>
<p>Are there any good extended HTML reporters or GUI's out there for Simpletest?</p>
<p>Tips on GUI's for PHPUnit would also be appreciated, but my main focus is Simpletest, for this project. I have tried <a href="http://cool.sourceforge.net/" rel="nofollow noreferrer">Cool PHPUnit Test Runner</a>, but was not convinced.</p>
| [
{
"answer_id": 24939,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>In which context are you asking?</p>\n\n<p>Are you trying to capture the output from a program you start on the com... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276/"
] | I am using [Simpletest](http://www.simpletest.org/) as my unit test framework for the PHP site I am currently working on. I like the fact that it is shipped with a simple HTML reporter, but I would like a bit more advanced reporter.
I have read the reporter API documentation, but it would be nice to be able to use an existing reporter, instead of having to do it yourself.
Are there any good extended HTML reporters or GUI's out there for Simpletest?
Tips on GUI's for PHPUnit would also be appreciated, but my main focus is Simpletest, for this project. I have tried [Cool PHPUnit Test Runner](http://cool.sourceforge.net/), but was not convinced. | If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:
```
python script_a.py | python script_b.py
```
This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on [standard streams](http://en.wikipedia.org/wiki/Standard_streams) on Wikipedia.
If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):
```
import subprocess
# Of course you can open things other than python here :)
process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
x = process.stderr.readline()
y = process.stdout.readline()
process.wait()
```
See the Python [subprocess](http://docs.python.org/lib/module-subprocess.html) module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard [file objects](http://docs.python.org/lib/bltin-file-objects.html).
For use with pipes, reading from standard input as [lassevk](https://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939) suggested you'd do something like this:
```
import sys
x = sys.stderr.readline()
y = sys.stdin.readline()
```
sys.stdin and sys.stdout are standard file objects as noted above, defined in the [sys](http://docs.python.org/lib/module-sys.html) module. You might also want to take a look at the [pipes](http://docs.python.org/lib/module-pipes.html) module.
Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into [polling](http://docs.python.org/lib/poll-objects.html) which unfortunately does not work in windows, but I'm sure there's some alternative out there. |
24,954 | <p>How to determine the applications associated with a particular extension (e.g. .JPG) and then determine where the executable to that application is located so that it can be launched via a call to say System.Diagnostics.Process.Start(...).</p>
<p>I already know how to read and write to the registry. It is the layout of the registry that makes it harder to determine in a standard way what applications are associated with an extension, what are there display names, and where their executables are located.</p>
| [
{
"answer_id": 24956,
"author": "Erik Öjebo",
"author_id": 276,
"author_profile": "https://Stackoverflow.com/users/276",
"pm_score": -1,
"selected": false,
"text": "<p>The file type associations are stored in the Windows registry, so you should be able to use the <a href=\"http://msdn.mi... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2669/"
] | How to determine the applications associated with a particular extension (e.g. .JPG) and then determine where the executable to that application is located so that it can be launched via a call to say System.Diagnostics.Process.Start(...).
I already know how to read and write to the registry. It is the layout of the registry that makes it harder to determine in a standard way what applications are associated with an extension, what are there display names, and where their executables are located. | Sample code:
```
using System;
using Microsoft.Win32;
namespace GetAssociatedApp
{
class Program
{
static void Main(string[] args)
{
const string extPathTemplate = @"HKEY_CLASSES_ROOT\{0}";
const string cmdPathTemplate = @"HKEY_CLASSES_ROOT\{0}\shell\open\command";
// 1. Find out document type name for .jpeg files
const string ext = ".jpeg";
var extPath = string.Format(extPathTemplate, ext);
var docName = Registry.GetValue(extPath, string.Empty, string.Empty) as string;
if (!string.IsNullOrEmpty(docName))
{
// 2. Find out which command is associated with our extension
var associatedCmdPath = string.Format(cmdPathTemplate, docName);
var associatedCmd =
Registry.GetValue(associatedCmdPath, string.Empty, string.Empty) as string;
if (!string.IsNullOrEmpty(associatedCmd))
{
Console.WriteLine("\"{0}\" command is associated with {1} extension", associatedCmd, ext);
}
}
}
}
}
``` |
24,991 | <p>I have defined a Java function:</p>
<pre><code>static <T> List<T> createEmptyList() {
return new ArrayList<T>();
}
</code></pre>
<p>One way to call it is like so:</p>
<pre><code>List<Integer> myList = createEmptyList(); // Compiles
</code></pre>
<p>Why can't I call it by explicitly passing the generic type argument? :</p>
<pre><code>Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why?
</code></pre>
<p>I get the error <code>Illegal start of expression</code> from the compiler.</p>
| [
{
"answer_id": 24997,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 5,
"selected": false,
"text": "<p>You can, if you pass in the type as a method parameter.</p>\n\n<pre><code>static <T> List<T> createEmptyLis... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
] | I have defined a Java function:
```
static <T> List<T> createEmptyList() {
return new ArrayList<T>();
}
```
One way to call it is like so:
```
List<Integer> myList = createEmptyList(); // Compiles
```
Why can't I call it by explicitly passing the generic type argument? :
```
Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why?
```
I get the error `Illegal start of expression` from the compiler. | When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . < Type > method();
```
Object list = Collections.<String> emptyList();
``` |
24,993 | <p>I have a WCF Web Service which is referenced from a class library. After the project is run, when creating the service client object from inside a class library, I receive an InvalidOperationException with message:</p>
<blockquote>
<p>Could not find default endpoint element that references contract
'MyServiceReference.IMyService' in the ServiceModel client
configuration section. This might be because no configuration file was
found for your application, or because no endpoint element matching
this contract could be found in the client element.</p>
</blockquote>
<p>The code I am using to create the instance is:</p>
<pre><code>myServiceClient = new MyServiceClient();
</code></pre>
<p>where MyServiceClient inherits from</p>
<p>System.ServiceModel.ClientBase</p>
<p>How do I solve this?</p>
<p>Note: I have a seperate console application which simply creates the same service object and makes calls to it and it works without no problems.</p>
| [
{
"answer_id": 25004,
"author": "Richard Morgan",
"author_id": 2258,
"author_profile": "https://Stackoverflow.com/users/2258",
"pm_score": 0,
"selected": false,
"text": "<p>It would probably help if you posted your app.config file, since this kind of error tends to point to a problem in ... | 2008/08/24 | [
"https://Stackoverflow.com/questions/24993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | I have a WCF Web Service which is referenced from a class library. After the project is run, when creating the service client object from inside a class library, I receive an InvalidOperationException with message:
>
> Could not find default endpoint element that references contract
> 'MyServiceReference.IMyService' in the ServiceModel client
> configuration section. This might be because no configuration file was
> found for your application, or because no endpoint element matching
> this contract could be found in the client element.
>
>
>
The code I am using to create the instance is:
```
myServiceClient = new MyServiceClient();
```
where MyServiceClient inherits from
System.ServiceModel.ClientBase
How do I solve this?
Note: I have a seperate console application which simply creates the same service object and makes calls to it and it works without no problems. | >
> Here is my app.config file of the class library:
>
>
>
You should put this configuration settings to main app's config file. .NET application (which is calling your class library) uses data from it's own config file not from your library config file. |
25,007 | <p>What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%?</p>
<p>I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much.</p>
<p>Based on Marius and Andy's answers I'm using the following solution:</p>
<pre><code>double red = (percent < 50) ? 255 : 256 - (percent - 50) * 5.12;
double green = (percent > 50) ? 255 : percent * 5.12;
var color = Color.FromArgb(255, (byte)red, (byte)green, 0);
</code></pre>
<p>Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ...</p>
| [
{
"answer_id": 25012,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>As yellow is a mix of red and green, you can probably start with <code>#F00</code> and then slide green up until yo... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
] | What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%?
I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much.
Based on Marius and Andy's answers I'm using the following solution:
```
double red = (percent < 50) ? 255 : 256 - (percent - 50) * 5.12;
double green = (percent > 50) ? 255 : percent * 5.12;
var color = Color.FromArgb(255, (byte)red, (byte)green, 0);
```
Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) \* 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ... | I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language:
```
function setColor(p){
var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12);
var green = p>50 ? 255 : Math.round((p)*5.12);
return "rgb(" + red + "," + green + ",0)";
}
``` |
25,033 | <p>I am using the code snippet below, however it's not working quite as I understand it should. </p>
<pre><code>public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
try {
line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
</code></pre>
<p>From reading the Javadoc about <code>readLine()</code> it says: </p>
<p>Reads a line of text. A line is considered to be terminated by any one of a line feed (<code>\n</code>), a carriage return (<code>\r</code>), or a carriage return followed immediately by a linefeed. </p>
<p><strong>Returns</strong>:
A <code>String</code> containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached </p>
<p><strong>Throws</strong>:
<code>IOException</code> - If an I/O error occurs</p>
<p>From my understanding of this, <code>readLine</code> should return null the first time no input is entered other than a line termination, like <code>\r</code>. However, this code just ends up looping infinitely. After debugging, I have found that instead of null being returned when just a termination character is entered, it actually returns an empty string (""). This doesn't make sense to me. What am I not understanding correctly?</p>
| [
{
"answer_id": 25036,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>No input is not the same as the end of the stream. You can usually simulate the end of the stream in a console by p... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
] | I am using the code snippet below, however it's not working quite as I understand it should.
```
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
try {
line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
```
From reading the Javadoc about `readLine()` it says:
Reads a line of text. A line is considered to be terminated by any one of a line feed (`\n`), a carriage return (`\r`), or a carriage return followed immediately by a linefeed.
**Returns**:
A `String` containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
**Throws**:
`IOException` - If an I/O error occurs
From my understanding of this, `readLine` should return null the first time no input is entered other than a line termination, like `\r`. However, this code just ends up looping infinitely. After debugging, I have found that instead of null being returned when just a termination character is entered, it actually returns an empty string (""). This doesn't make sense to me. What am I not understanding correctly? | >
> From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like '\r'.
>
>
>
That is not correct. `readLine` will return `null` if the end of the stream is reached. That is, for example, if you are reading a file, and the file ends, or if you're reading from a socket and the socket closses.
But if you're simply reading the console input, hitting the return key on your keyboard does not constitute an end of stream. It's simply a character that is returned (`\n` or `\r\n` depending on your OS).
So, if you want to break on both the empty string and the end of line, you should do:
```
while (line != null && !line.equals(""))
```
Also, your current program should work as expected if you pipe some file directly into it, like so:
```
java -cp . Echo < test.txt
``` |
25,041 | <p>Using CSS,</p>
<p>I'm trying to specify the height of a <code>span</code> tag in Firefox, but it's just not accepting it (IE does).</p>
<p>Firefox accepts the <code>height</code> if I use a <code>div</code>, but the problem with using a <code>div</code> is the annoying line break after it, which I can't have in this particular instance. </p>
<p>I tried setting the CSS style attribute of: <pre>display: inline</pre> for the <code>div</code>, but Firefox seems to revert that to <code>span</code> behavior anyway and ignores the <code>height</code> attribute once again.</p>
| [
{
"answer_id": 25045,
"author": "Cade",
"author_id": 565,
"author_profile": "https://Stackoverflow.com/users/565",
"pm_score": 2,
"selected": false,
"text": "<p>Since you're displaying it inline, the height should be set at the height of your line-height attribute.</p>\n\n<p>Depending on... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
] | Using CSS,
I'm trying to specify the height of a `span` tag in Firefox, but it's just not accepting it (IE does).
Firefox accepts the `height` if I use a `div`, but the problem with using a `div` is the annoying line break after it, which I can't have in this particular instance.
I tried setting the CSS style attribute of:
```
display: inline
```
for the `div`, but Firefox seems to revert that to `span` behavior anyway and ignores the `height` attribute once again. | ```
<style>
#div1 { float:left; height:20px; width:20px; }
#div2 { float:left; height:30px; width:30px }
</style>
<div id="div1">FirstDiv</div>
<div id="div2">SecondDiv</div>
```
As long as the container for whatever is holding `div's` 1 and 2 is wide enough for them to fit, this should be fine. |
25,046 | <p>I've just started learning Lisp and I can't figure out how to compile and link lisp code to an executable.</p>
<p>I'm using <code>clisp</code> and <code>clisp -c</code> produces two files:</p>
<ul>
<li>.fas</li>
<li>.lib</li>
</ul>
<p>What do I do next to get an executable?</p>
| [
{
"answer_id": 25057,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 4,
"selected": false,
"text": "<p>Take a look at the the official clisp homepage. There is a FAQ that answers this question.</p>\n\n<p><a href=\"http:... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | I've just started learning Lisp and I can't figure out how to compile and link lisp code to an executable.
I'm using `clisp` and `clisp -c` produces two files:
* .fas
* .lib
What do I do next to get an executable? | I was actually trying to do this today, and I found typing this into the CLisp REPL worked:
```
(EXT:SAVEINITMEM "executable.exe"
:QUIET t
:INIT-FUNCTION 'main
:EXECUTABLE t
:NORC t)
```
where main is the name of the function you want to call when the program launches, `:QUIET t` suppresses the startup banner, and `:EXECUTABLE t` makes a native executable.
It can also be useful to call
```
(EXT:EXIT)
```
at the end of your main function in order to stop the user from getting an interactive lisp prompt when the program is done.
EDIT: Reading the documentation, you may also want to add `:NORC t`
(read [link](http://clisp.cons.org/impnotes/image.html)). This suppresses loading the RC file (for example, `~/.clisprc.lisp`). |
25,116 | <p>In Python you can use <a href="https://docs.python.org/library/struct.html" rel="noreferrer">StringIO</a> for a file-like buffer for character data. <a href="https://docs.python.org/library/mmap.html" rel="noreferrer">Memory-mapped file</a> basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's <a href="http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html" rel="noreferrer">ByteArrayOutputStream</a>?</p>
<p>The use-case I have is I want to create a ZIP file in memory, and <a href="https://docs.python.org/library/zipfile.html" rel="noreferrer">ZipFile</a> requires a file-like object.</p>
| [
{
"answer_id": 25123,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 2,
"selected": false,
"text": "<p>Look at the struct package: <a href=\"https://docs.python.org/library/struct.html\" rel=\"nofollow noreferrer\">https://do... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679/"
] | In Python you can use [StringIO](https://docs.python.org/library/struct.html) for a file-like buffer for character data. [Memory-mapped file](https://docs.python.org/library/mmap.html) basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's [ByteArrayOutputStream](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html)?
The use-case I have is I want to create a ZIP file in memory, and [ZipFile](https://docs.python.org/library/zipfile.html) requires a file-like object. | You are probably looking for [io.BytesIO](http://docs.python.org/release/3.1.3/library/io.html#binary-i-o) class. It works exactly like StringIO except that it supports binary data:
```
from io import BytesIO
bio = BytesIO(b"some initial binary data: \x00\x01")
```
StringIO will throw TypeError:
```
from io import StringIO
sio = StringIO(b"some initial binary data: \x00\x01")
``` |
25,128 | <p>Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing?</p>
| [
{
"answer_id": 25131,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>Yes this is possible. I believe there are multiple libraries to accomplish this. The most widely used is probably <... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing? | I prefer the [GD library](http://www.php.net/gd) - check out [the Examples](http://www.php.net/manual/en/image.examples.php), and this example:
```
<?php
header ("Content-type: image/png");
$im = @imagecreatetruecolor(120, 20)
or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>
```
Outputs:
[](https://i.stack.imgur.com/kBN75.png)
(source: [php.net](http://uk2.php.net/manual/en/figures/image.imagecreatetruecolor.png))
See [imagecreatetruecolor](http://www.php.net/manual/en/function.imagecreatetruecolor.php). |
25,147 | <p>I have two arrays of animals (for example).</p>
<pre><code>$array = array(
array(
'id' => 1,
'name' => 'Cat',
),
array(
'id' => 2,
'name' => 'Mouse',
)
);
$array2 = array(
array(
'id' => 2,
'age' => 321,
),
array(
'id' => 1,
'age' => 123,
)
);
</code></pre>
<p>How can I merge the two arrays into one by the ID?</p>
| [
{
"answer_id": 25155,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 2,
"selected": false,
"text": "<p>First off, why don't you use the ID as the index (or key, in the mapping-style array that php arrays are imo)?</p>\n... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118/"
] | I have two arrays of animals (for example).
```
$array = array(
array(
'id' => 1,
'name' => 'Cat',
),
array(
'id' => 2,
'name' => 'Mouse',
)
);
$array2 = array(
array(
'id' => 2,
'age' => 321,
),
array(
'id' => 1,
'age' => 123,
)
);
```
How can I merge the two arrays into one by the ID? | This does what Erik suggested (id no. as array key) and merges vlaues in `$array2` to `$results`.
```
$results = array();
foreach($array as $subarray)
{
$results[$subarray['id']] = array('name' => $subarray['name']);
}
foreach($array2 as $subarray)
{
if(array_key_exists($subarray['id'], $results))
{
// Loop through $subarray would go here if you have extra
$results[$subarray['id']]['age'] = $subarray['age'];
}
}
``` |
25,158 | <p>I'm rewriting an old application and use this as a good opportunity to try out C# and .NET development (I usually do a lot of plug-in stuff in C).</p>
<p>The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see.</p>
<p>What is the best practice to switch between the views?
From start to running?
Between the running views?</p>
<p>Ideas:</p>
<ul>
<li>Use one form and hide and show controls</li>
<li>Use one start form and then a form with a TabControl</li>
<li>Use six separate forms</li>
</ul>
| [
{
"answer_id": 25170,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 2,
"selected": false,
"text": "<p>Tabbed forms are usually good... but only if you want the user to be able to see any view at any time... and it sounds li... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2703/"
] | I'm rewriting an old application and use this as a good opportunity to try out C# and .NET development (I usually do a lot of plug-in stuff in C).
The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see.
What is the best practice to switch between the views?
From start to running?
Between the running views?
Ideas:
* Use one form and hide and show controls
* Use one start form and then a form with a TabControl
* Use six separate forms | Creating a bunch of overlaid panels is a design-time nightmare.
I would suggest using a tab control with each "view" on a separate tab, and then picking the correct tab at runtime. You can avoid showing the tab headers by putting something like this in your form's Load event:
```
tabControl1.Top = tabControl1.Top - tabControl1.ItemSize.Height;
tabControl1.Height = tabControl1.Height + tabControl1.ItemSize.Height;
tabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height + tabControl1.ItemSize.Height));
``` |
25,161 | <p>I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo.</p>
<p>Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing?</p>
| [
{
"answer_id": 25165,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 3,
"selected": false,
"text": "<p>A single image alone doesn't give the browser the semantic information on the logos within. You could use an <a href=... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo.
Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing? | Yes, you can do this without Javascript. Use an HTML image map, with title attributes, like this:
```
<img usemap="#logo" src="http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png">
<map name="logo">
<area shape="rect" href="" coords="52,42,121,65" title="Stack">
<area shape="rect" href="" coords="122,42,245,65" title="Overflow">
</map>
```
The Stack Overflow logo refers to the [image map](http://www.w3.org/TR/html4/struct/objects.html#edef-MAP), which defines a rectangle for each of the two words using an `area` tag. Each `area` tag's `title` element specifies the text that browsers generally show as a tooltip. The `shape` attribute can also specify a circle or polygon. |
25,182 | <p>I'm writing a program that sends an email out at a client's specific local time. I have a .NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then select every client out of the database with that timezone(s). </p>
<p>The query will look like one of these. Keep in mind the order of the result set does not matter, so a union would be fine. Which runs faster, or do they really do the same thing?</p>
<pre><code>SELECT email FROM tClient WHERE timezoneID in (1, 4, 9)
</code></pre>
<p>or</p>
<pre><code>SELECT email FROM tClient WHERE timezoneID = 1
UNION ALL SELECT email FROM tClient WHERE timezoneID = 4
UNION ALL SELECT email FROM tCLIENT WHERE timezoneID = 9
</code></pre>
<p><em>Edit: <strong>timezoneID is a foreign key to tTimezone, a table with primary key timezoneID and varchar(20) field timezoneName.</strong></em>
<em>Also, I went with <code>WHERE IN</code> since I didn't feel like opening up the analyzer.</em></p>
<p><em>Edit 2: <strong>Query processes 200k rows in under 100 ms, so at this point I'm done.</strong></em></p>
| [
{
"answer_id": 25186,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 1,
"selected": false,
"text": "<p>My first guess would be that <pre>SELECT email FROM tClient WHERE timezoneID in (1, 4, 9)</pre> will be faster a... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | I'm writing a program that sends an email out at a client's specific local time. I have a .NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then select every client out of the database with that timezone(s).
The query will look like one of these. Keep in mind the order of the result set does not matter, so a union would be fine. Which runs faster, or do they really do the same thing?
```
SELECT email FROM tClient WHERE timezoneID in (1, 4, 9)
```
or
```
SELECT email FROM tClient WHERE timezoneID = 1
UNION ALL SELECT email FROM tClient WHERE timezoneID = 4
UNION ALL SELECT email FROM tCLIENT WHERE timezoneID = 9
```
*Edit: **timezoneID is a foreign key to tTimezone, a table with primary key timezoneID and varchar(20) field timezoneName.***
*Also, I went with `WHERE IN` since I didn't feel like opening up the analyzer.*
*Edit 2: **Query processes 200k rows in under 100 ms, so at this point I'm done.*** | Hey! These queries are not equivalent.
======================================
Results will be same only if assuming that one email belongs only to the one time zone. Of course it does however SQL engine doesn't know that and tries to remove duplicities. So the first query should be faster.
Always use UNION ALL, unless you know why you want to use UNION.
If you are not sure what is difference see [this](https://stackoverflow.com/questions/49925/what-is-the-difference-between-union-and-union-all-in-oracle) SO question.
*Note: that yell belongs to [previous version](https://stackoverflow.com/revisions/viewmarkup/31874) of question.* |
25,200 | <p>I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a <code>AutoSize = false</code> in my constructor, however, when I place it in design mode, the property always is True. </p>
<p>I have overridden other properties with success but this one is happily ignoring me. Does anybody has a clue if this is "by MS design"?</p>
<p>Here's the full source code of my Label in case anyone is interested.</p>
<pre><code>using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Dentactil.UI.WinControls
{
[DefaultProperty("TextString")]
[DefaultEvent("TextClick")]
public partial class RoundedLabel : UserControl
{
private static readonly Color DEFAULT_BORDER_COLOR = Color.FromArgb( 132, 100, 161 );
private const float DEFAULT_BORDER_WIDTH = 2.0F;
private const int DEFAULT_ROUNDED_WIDTH = 16;
private const int DEFAULT_ROUNDED_HEIGHT = 12;
private Color mBorderColor = DEFAULT_BORDER_COLOR;
private float mBorderWidth = DEFAULT_BORDER_WIDTH;
private int mRoundedWidth = DEFAULT_ROUNDED_WIDTH;
private int mRoundedHeight = DEFAULT_ROUNDED_HEIGHT;
public event EventHandler TextClick;
private Padding mPadding = new Padding(8);
public RoundedLabel()
{
InitializeComponent();
}
public Cursor TextCursor
{
get { return lblText.Cursor; }
set { lblText.Cursor = value; }
}
public Padding TextPadding
{
get { return mPadding; }
set
{
mPadding = value;
UpdateInternalBounds();
}
}
public ContentAlignment TextAlign
{
get { return lblText.TextAlign; }
set { lblText.TextAlign = value; }
}
public string TextString
{
get { return lblText.Text; }
set { lblText.Text = value; }
}
public override Font Font
{
get { return base.Font; }
set
{
base.Font = value;
lblText.Font = value;
}
}
public override Color ForeColor
{
get { return base.ForeColor; }
set
{
base.ForeColor = value;
lblText.ForeColor = value;
}
}
public Color BorderColor
{
get { return mBorderColor; }
set
{
mBorderColor = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_BORDER_WIDTH)]
public float BorderWidth
{
get { return mBorderWidth; }
set
{
mBorderWidth = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_ROUNDED_WIDTH)]
public int RoundedWidth
{
get { return mRoundedWidth; }
set
{
mRoundedWidth = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_ROUNDED_HEIGHT)]
public int RoundedHeight
{
get { return mRoundedHeight; }
set
{
mRoundedHeight = value;
Invalidate();
}
}
private void UpdateInternalBounds()
{
lblText.Left = mPadding.Left;
lblText.Top = mPadding.Top;
int width = Width - mPadding.Right - mPadding.Left;
lblText.Width = width > 0 ? width : 0;
int heigth = Height - mPadding.Bottom - mPadding.Top;
lblText.Height = heigth > 0 ? heigth : 0;
}
protected override void OnLoad(EventArgs e)
{
UpdateInternalBounds();
base.OnLoad(e);
}
protected override void OnPaint(PaintEventArgs e)
{
SmoothingMode smoothingMode = e.Graphics.SmoothingMode;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
int roundedWidth = RoundedWidth > (Width - 1)/2 ? (Width - 1)/2 : RoundedWidth;
int roundedHeight = RoundedHeight > (Height - 1)/2 ? (Height - 1)/2 : RoundedHeight;
GraphicsPath path = new GraphicsPath();
path.AddLine(0, roundedHeight, 0, Height - 1 - roundedHeight);
path.AddArc(new RectangleF(0, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 180, -90);
path.AddLine(roundedWidth, Height - 1, Width - 1 - 2*roundedWidth, Height - 1);
path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 90, -90);
path.AddLine(Width - 1, Height - 1 - roundedHeight, Width - 1, roundedHeight);
path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, 0, 2*roundedWidth, 2*roundedHeight), 0, -90);
path.AddLine(Width - 1 - roundedWidth, 0, roundedWidth, 0);
path.AddArc(new RectangleF(0, 0, 2*roundedWidth, 2*roundedHeight), -90, -90);
e.Graphics.DrawPath(new Pen(new SolidBrush(BorderColor), BorderWidth), path);
e.Graphics.SmoothingMode = smoothingMode;
base.OnPaint(e);
}
protected override void OnResize(EventArgs e)
{
UpdateInternalBounds();
base.OnResize(e);
}
private void lblText_Click(object sender, EventArgs e)
{
if (TextClick != null)
{
TextClick(this, e);
}
}
}
}
</code></pre>
<p>(there are some issues with Stack Overflow's markup and the Underscore, but it's easy to follow the code).</p>
<hr>
<p>I have actually removed that override some time ago when I saw that it wasn't working. I'll add it again now and test. Basically I want to replace the Label with some new label called: IWillNotAutoSizeLabel ;)</p>
<p>I basically hate the autosize property "on by default".</p>
| [
{
"answer_id": 25219,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 2,
"selected": false,
"text": "<p>Your problem could be that you're not actually overriding Autosize in your code (ie, in the same way that you're ov... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684/"
] | I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a `AutoSize = false` in my constructor, however, when I place it in design mode, the property always is True.
I have overridden other properties with success but this one is happily ignoring me. Does anybody has a clue if this is "by MS design"?
Here's the full source code of my Label in case anyone is interested.
```
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Dentactil.UI.WinControls
{
[DefaultProperty("TextString")]
[DefaultEvent("TextClick")]
public partial class RoundedLabel : UserControl
{
private static readonly Color DEFAULT_BORDER_COLOR = Color.FromArgb( 132, 100, 161 );
private const float DEFAULT_BORDER_WIDTH = 2.0F;
private const int DEFAULT_ROUNDED_WIDTH = 16;
private const int DEFAULT_ROUNDED_HEIGHT = 12;
private Color mBorderColor = DEFAULT_BORDER_COLOR;
private float mBorderWidth = DEFAULT_BORDER_WIDTH;
private int mRoundedWidth = DEFAULT_ROUNDED_WIDTH;
private int mRoundedHeight = DEFAULT_ROUNDED_HEIGHT;
public event EventHandler TextClick;
private Padding mPadding = new Padding(8);
public RoundedLabel()
{
InitializeComponent();
}
public Cursor TextCursor
{
get { return lblText.Cursor; }
set { lblText.Cursor = value; }
}
public Padding TextPadding
{
get { return mPadding; }
set
{
mPadding = value;
UpdateInternalBounds();
}
}
public ContentAlignment TextAlign
{
get { return lblText.TextAlign; }
set { lblText.TextAlign = value; }
}
public string TextString
{
get { return lblText.Text; }
set { lblText.Text = value; }
}
public override Font Font
{
get { return base.Font; }
set
{
base.Font = value;
lblText.Font = value;
}
}
public override Color ForeColor
{
get { return base.ForeColor; }
set
{
base.ForeColor = value;
lblText.ForeColor = value;
}
}
public Color BorderColor
{
get { return mBorderColor; }
set
{
mBorderColor = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_BORDER_WIDTH)]
public float BorderWidth
{
get { return mBorderWidth; }
set
{
mBorderWidth = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_ROUNDED_WIDTH)]
public int RoundedWidth
{
get { return mRoundedWidth; }
set
{
mRoundedWidth = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_ROUNDED_HEIGHT)]
public int RoundedHeight
{
get { return mRoundedHeight; }
set
{
mRoundedHeight = value;
Invalidate();
}
}
private void UpdateInternalBounds()
{
lblText.Left = mPadding.Left;
lblText.Top = mPadding.Top;
int width = Width - mPadding.Right - mPadding.Left;
lblText.Width = width > 0 ? width : 0;
int heigth = Height - mPadding.Bottom - mPadding.Top;
lblText.Height = heigth > 0 ? heigth : 0;
}
protected override void OnLoad(EventArgs e)
{
UpdateInternalBounds();
base.OnLoad(e);
}
protected override void OnPaint(PaintEventArgs e)
{
SmoothingMode smoothingMode = e.Graphics.SmoothingMode;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
int roundedWidth = RoundedWidth > (Width - 1)/2 ? (Width - 1)/2 : RoundedWidth;
int roundedHeight = RoundedHeight > (Height - 1)/2 ? (Height - 1)/2 : RoundedHeight;
GraphicsPath path = new GraphicsPath();
path.AddLine(0, roundedHeight, 0, Height - 1 - roundedHeight);
path.AddArc(new RectangleF(0, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 180, -90);
path.AddLine(roundedWidth, Height - 1, Width - 1 - 2*roundedWidth, Height - 1);
path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 90, -90);
path.AddLine(Width - 1, Height - 1 - roundedHeight, Width - 1, roundedHeight);
path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, 0, 2*roundedWidth, 2*roundedHeight), 0, -90);
path.AddLine(Width - 1 - roundedWidth, 0, roundedWidth, 0);
path.AddArc(new RectangleF(0, 0, 2*roundedWidth, 2*roundedHeight), -90, -90);
e.Graphics.DrawPath(new Pen(new SolidBrush(BorderColor), BorderWidth), path);
e.Graphics.SmoothingMode = smoothingMode;
base.OnPaint(e);
}
protected override void OnResize(EventArgs e)
{
UpdateInternalBounds();
base.OnResize(e);
}
private void lblText_Click(object sender, EventArgs e)
{
if (TextClick != null)
{
TextClick(this, e);
}
}
}
}
```
(there are some issues with Stack Overflow's markup and the Underscore, but it's easy to follow the code).
---
I have actually removed that override some time ago when I saw that it wasn't working. I'll add it again now and test. Basically I want to replace the Label with some new label called: IWillNotAutoSizeLabel ;)
I basically hate the autosize property "on by default". | I've seen similar behaviour when setting certain properties of controls in the constructor of the form itself. They seem to revert back to their design-time defaults.
I notice you're already overriding the OnLoad method. Have you tried setting AutoSize = false there? Or are you mainly concerned with providing a *default* value of false? |
25,224 | <p>I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata:</p>
<pre><code>15, 'QHS', '20', '2008-08-24 13:36:33.465567-04'
15, 'QHE', '8', '2008-08-24 12:07:08.660519-04'
15, 'QHS', '21', '2008-08-24 09:44:44.39354-04'
15, 'QHE', '10', '2008-08-24 08:47:57.672058-04'
</code></pre>
<p>I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code.</p>
| [
{
"answer_id": 25248,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 2,
"selected": true,
"text": "<p>I suppose you're not willing to modify your schema, so I'm afraid my answe might not be of much help, but here go... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2462/"
] | I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata:
```
15, 'QHS', '20', '2008-08-24 13:36:33.465567-04'
15, 'QHE', '8', '2008-08-24 12:07:08.660519-04'
15, 'QHS', '21', '2008-08-24 09:44:44.39354-04'
15, 'QHE', '10', '2008-08-24 08:47:57.672058-04'
```
I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code. | I suppose you're not willing to modify your schema, so I'm afraid my answe might not be of much help, but here goes...
One possible solution would be to have the time field empty until it was replaced by a newer value, when you insert the 'deprecation date' instead. Another way is to expand the table with an 'active' column, but that would introduce some redundancy.
The classic solution would be to have both 'Valid-From' and 'Valid-To' fields where the 'Valid-To' fields are blank until some other entry becomes valid. This can be handled easily by using triggers or similar. Using constraints to make sure there is only one item of each type that is valid will ensure data integrity.
Common to these is that there is a single way of determining the set of current fields. You'd simply select all entries with the active user and a NULL 'Valid-To' or 'deprecation date' or a true 'active'.
You might be interested in taking a look at the Wikipedia entry on [temporal databases](http://en.wikipedia.org/wiki/Temporal_database) and the article [A consensus glossary of temporal database concepts](http://www.cs.arizona.edu/~rts/pubs/SIGMODRecordMarch94p52.pdf). |
25,225 | <p>I have a couple of files containing a value in each line.</p>
<p><strong>EDIT :</strong></p>
<p>I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state.</p>
<p>I was trying to do:</p>
<pre><code>paste -d ',' file1 file2 file 3 file 4 > file5.csv
</code></pre>
<p>and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things.
</p>
| [
{
"answer_id": 25229,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 0,
"selected": false,
"text": "<p>you probably need to clarify or retag your question but as it stands the answer is below.</p>\n\n<p>joining two files under ... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1582/"
] | I have a couple of files containing a value in each line.
**EDIT :**
I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state.
I was trying to do:
```
paste -d ',' file1 file2 file 3 file 4 > file5.csv
```
and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things.
| file 1:
```
1
2
3
```
file2:
```
2
4
6
```
```
paste --delimiters=\; file1 file2
```
Will yield:
```
1;2
3;4
5;6
``` |
25,238 | <blockquote>
<p>What's the best way to make an element of 100% minimum height across a
wide range of browsers ?</p>
</blockquote>
<p>In particular if you have a layout with a <code>header</code> and <code>footer</code> of fixed <code>height</code>,</p>
<p>how do you make the middle content part fill <code>100%</code> of the space in between with the <code>footer</code> fixed to the bottom ?</p>
| [
{
"answer_id": 25249,
"author": "ollifant",
"author_id": 2078,
"author_profile": "https://Stackoverflow.com/users/2078",
"pm_score": 7,
"selected": false,
"text": "<p>I am using the following one: <a href=\"http://www.xs4all.nl/~peterned/examples/csslayout1.html\" rel=\"noreferrer\">CSS ... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725/"
] | >
> What's the best way to make an element of 100% minimum height across a
> wide range of browsers ?
>
>
>
In particular if you have a layout with a `header` and `footer` of fixed `height`,
how do you make the middle content part fill `100%` of the space in between with the `footer` fixed to the bottom ? | I am using the following one: [CSS Layout - 100 % height](http://www.xs4all.nl/~peterned/examples/csslayout1.html)
>
> **Min-height**
>
>
> The #container element of this page has a min-height of 100%. That
> way, if the content requires more height than the viewport provides,
> the height of #content forces #container to become longer as well.
> Possible columns in #content can then be visualised with a background
> image on #container; divs are not table cells, and you don't need (or
> want) the physical elements to create such a visual effect. If you're
> not yet convinced; think wobbly lines and gradients instead of
> straight lines and simple color schemes.
>
>
> **Relative positioning**
>
>
> Because #container has a relative position, #footer will always remain
> at its bottom; since the min-height mentioned above does not prevent
> #container from scaling, this will work even if (or rather especially when) #content forces #container to become longer.
>
>
> **Padding-bottom**
>
>
> Since it is no longer in the normal flow, padding-bottom of #content
> now provides the space for the absolute #footer. This padding is
> included in the scrolled height by default, so that the footer will
> never overlap the above content.
>
>
> Scale the text size a bit or resize your browser window to test this
> layout.
>
>
>
```css
html,body {
margin:0;
padding:0;
height:100%; /* needed for container min-height */
background:gray;
font-family:arial,sans-serif;
font-size:small;
color:#666;
}
h1 {
font:1.5em georgia,serif;
margin:0.5em 0;
}
h2 {
font:1.25em georgia,serif;
margin:0 0 0.5em;
}
h1, h2, a {
color:orange;
}
p {
line-height:1.5;
margin:0 0 1em;
}
div#container {
position:relative; /* needed for footer positioning*/
margin:0 auto; /* center, not in IE5 */
width:750px;
background:#f0f0f0;
height:auto !important; /* real browsers */
height:100%; /* IE6: treaded as min-height*/
min-height:100%; /* real browsers */
}
div#header {
padding:1em;
background:#ddd url("../csslayout.gif") 98% 10px no-repeat;
border-bottom:6px double gray;
}
div#header p {
font-style:italic;
font-size:1.1em;
margin:0;
}
div#content {
padding:1em 1em 5em; /* bottom padding for footer */
}
div#content p {
text-align:justify;
padding:0 1em;
}
div#footer {
position:absolute;
width:100%;
bottom:0; /* stick to bottom */
background:#ddd;
border-top:6px double gray;
}
div#footer p {
padding:1em;
margin:0;
}
```
Works fine for me. |
25,240 | <p>FCKeditor has InsertHtml API (<a href="http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/JavaScript_API" rel="nofollow noreferrer">JavaScript API document</a>) that inserts HTML in the current cursor position. How do I insert at the very end of the document?</p>
<p>Do I need to start browser sniffing with something like this</p>
<pre><code>if ( element.insertAdjacentHTML ) // IE
element.insertAdjacentHTML( 'beforeBegin', html ) ;
else // Gecko
{
var oRange = document.createRange() ;
oRange.setStartBefore( element ) ;
var oFragment = oRange.createContextualFragment( html );
element.parentNode.insertBefore( oFragment, element ) ;
}
</code></pre>
<p>or is there a blessed way that I missed?</p>
<p>Edit: Of course, I can rewrite the whole HTML, as answers suggest, but I cannot believe that is the "blessed" way. That means that the browser should destroy whatever it has and re-parse the document from scratch. That cannot be good. For example, I expect that to break the undo stack.</p>
| [
{
"answer_id": 25291,
"author": "Ryan Doherty",
"author_id": 956,
"author_profile": "https://Stackoverflow.com/users/956",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you could use a combination of GetHTML and SetHTML to get the current contents, append your html and rein... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2515/"
] | FCKeditor has InsertHtml API ([JavaScript API document](http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/JavaScript_API)) that inserts HTML in the current cursor position. How do I insert at the very end of the document?
Do I need to start browser sniffing with something like this
```
if ( element.insertAdjacentHTML ) // IE
element.insertAdjacentHTML( 'beforeBegin', html ) ;
else // Gecko
{
var oRange = document.createRange() ;
oRange.setStartBefore( element ) ;
var oFragment = oRange.createContextualFragment( html );
element.parentNode.insertBefore( oFragment, element ) ;
}
```
or is there a blessed way that I missed?
Edit: Of course, I can rewrite the whole HTML, as answers suggest, but I cannot believe that is the "blessed" way. That means that the browser should destroy whatever it has and re-parse the document from scratch. That cannot be good. For example, I expect that to break the undo stack. | It looks like you could use a combination of GetHTML and SetHTML to get the current contents, append your html and reinsert everything into the editor. Although it does say
>
> Note that when using this method, you will lose any listener that you may have previously registered on the editor.EditorDocument.
>
>
>
Hope that helps! |
25,259 | <p>What is a good complete <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a> or some other process that would take the title:</p>
<blockquote>
<p>How do you change a title to be part of the URL like Stack Overflow?</p>
</blockquote>
<p>and turn it into </p>
<pre class="lang-none prettyprint-override"><code>how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow
</code></pre>
<p>that is used in the SEO-friendly URLs on Stack Overflow?</p>
<p>The development environment I am using is <a href="http://en.wikipedia.org/wiki/Ruby_on_Rails" rel="noreferrer">Ruby on Rails</a>, but if there are some other platform-specific solutions (.NET, PHP, <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="noreferrer">Django</a>), I would love to see those too. </p>
<p>I am sure I (or another reader) will come across the same problem on a different platform down the line. </p>
<p>I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced.</p>
| [
{
"answer_id": 25263,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 4,
"selected": false,
"text": "<p>You will want to setup a custom route to point the <a href=\"http://en.wikipedia.org/wiki/Uniform_Resource_Locator\" re... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] | What is a good complete [regular expression](http://en.wikipedia.org/wiki/Regular_expression) or some other process that would take the title:
>
> How do you change a title to be part of the URL like Stack Overflow?
>
>
>
and turn it into
```none
how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow
```
that is used in the SEO-friendly URLs on Stack Overflow?
The development environment I am using is [Ruby on Rails](http://en.wikipedia.org/wiki/Ruby_on_Rails), but if there are some other platform-specific solutions (.NET, PHP, [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29)), I would love to see those too.
I am sure I (or another reader) will come across the same problem on a different platform down the line.
I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced. | Here's how we do it. Note that there are probably more edge conditions than you realize at first glance.
This is the second version, unrolled for 5x more performance (and yes, I benchmarked it). I figured I'd optimize it because this function can be called hundreds of times per page.
```
/// <summary>
/// Produces optional, URL-friendly version of a title, "like-this-one".
/// hand-tuned for speed, reflects performance refactoring contributed
/// by John Gietzen (user otac0n)
/// </summary>
public static string URLFriendly(string title)
{
if (title == null) return "";
const int maxlen = 80;
int len = title.Length;
bool prevdash = false;
var sb = new StringBuilder(len);
char c;
for (int i = 0; i < len; i++)
{
c = title[i];
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
{
sb.Append(c);
prevdash = false;
}
else if (c >= 'A' && c <= 'Z')
{
// tricky way to convert to lowercase
sb.Append((char)(c | 32));
prevdash = false;
}
else if (c == ' ' || c == ',' || c == '.' || c == '/' ||
c == '\\' || c == '-' || c == '_' || c == '=')
{
if (!prevdash && sb.Length > 0)
{
sb.Append('-');
prevdash = true;
}
}
else if ((int)c >= 128)
{
int prevlen = sb.Length;
sb.Append(RemapInternationalCharToAscii(c));
if (prevlen != sb.Length) prevdash = false;
}
if (i == maxlen) break;
}
if (prevdash)
return sb.ToString().Substring(0, sb.Length - 1);
else
return sb.ToString();
}
```
To see the previous version of the code this replaced (but is functionally equivalent to, and 5x faster), view revision history of this post (click the date link).
Also, the `RemapInternationalCharToAscii` method source code can be found [here](https://meta.stackexchange.com/a/7696). |
25,282 | <p>The point of this question is to collect a list of examples of hashtable implementations using arrays in different languages. It would also be nice if someone could throw in a pretty detailed overview of how they work, and what is happening with each example. </p>
<p><strong>Edit:</strong> </p>
<p>Why not just use the built in hash functions in your specific language? </p>
<p>Because we should know how hash tables work and be able to implement them. This may not seem like a super important topic, but knowing how one of the most used data structures works seems pretty important to me. If this is to become the wikipedia of programming, then these are some of the types of questions that I will come here for. I'm not looking for a CS book to be written here. I could go pull Intro to Algorithms off the shelf and read up on the chapter on hash tables and get that type of info. More specifically what I am looking for are <strong>code examples</strong>. Not only for me in particular, but also for others who would maybe one day be searching for similar info and stumble across this page. </p>
<p>To be more specific: If you <strong>had</strong> to implement them, and could not use built-in functions, how would you do it? </p>
<p>You don't need to put the code here. Put it in pastebin and just link it. </p>
| [
{
"answer_id": 25298,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 0,
"selected": false,
"text": "<p>I think you need to be a little more specific. There are several variations on hashtables with regards to the following o... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797/"
] | The point of this question is to collect a list of examples of hashtable implementations using arrays in different languages. It would also be nice if someone could throw in a pretty detailed overview of how they work, and what is happening with each example.
**Edit:**
Why not just use the built in hash functions in your specific language?
Because we should know how hash tables work and be able to implement them. This may not seem like a super important topic, but knowing how one of the most used data structures works seems pretty important to me. If this is to become the wikipedia of programming, then these are some of the types of questions that I will come here for. I'm not looking for a CS book to be written here. I could go pull Intro to Algorithms off the shelf and read up on the chapter on hash tables and get that type of info. More specifically what I am looking for are **code examples**. Not only for me in particular, but also for others who would maybe one day be searching for similar info and stumble across this page.
To be more specific: If you **had** to implement them, and could not use built-in functions, how would you do it?
You don't need to put the code here. Put it in pastebin and just link it. | A hash table a data structure that allows lookup of items in constant time. It works by hashing a value and converting that value to an offset in an array. The concept of a hash table is fairly easy to understand, but implementing is obviously harder. I'm not pasting the whole hash table here, but here are some snippets of a hash table I made in C a few weeks ago...
One of the basics of creating a hash table is having a good hash function. I used the djb2 hash function in my hash table:
```
int ComputeHash(char* key)
{
int hash = 5381;
while (*key)
hash = ((hash << 5) + hash) + *(key++);
return hash % hashTable.totalBuckets;
}
```
Then comes the actual code itself for creating and managing the buckets in the table
```
typedef struct HashTable{
HashTable* nextEntry;
char* key;
char* value;
}HashBucket;
typedef struct HashTableEntry{
int totalBuckets; // Total number of buckets allocated for the hash table
HashTable** hashBucketArray; // Pointer to array of buckets
}HashTableEntry;
HashTableEntry hashTable;
bool InitHashTable(int totalBuckets)
{
if(totalBuckets > 0)
{
hashTable.totalBuckets = totalBuckets;
hashTable.hashBucketArray = (HashTable**)malloc(totalBuckets * sizeof(HashTable));
if(hashTable.hashBucketArray != NULL)
{
memset(hashTable.hashBucketArray, 0, sizeof(HashTable) * totalBuckets);
return true;
}
}
return false;
}
bool AddNode(char* key, char* value)
{
int offset = ComputeHash(key);
if(hashTable.hashBucketArray[offset] == NULL)
{
hashTable.hashBucketArray[offset] = NewNode(key, value);
if(hashTable.hashBucketArray[offset] != NULL)
return true;
}
else
{
if(AppendLinkedNode(hashTable.hashBucketArray[offset], key, value) != NULL)
return true;
}
return false;
}
HashTable* NewNode(char* key, char* value)
{
HashTable* tmpNode = (HashTable*)malloc(sizeof(HashTable));
if(tmpNode != NULL)
{
tmpNode->nextEntry = NULL;
tmpNode->key = (char*)malloc(strlen(key));
tmpNode->value = (char*)malloc(strlen(value));
strcpy(tmpNode->key, key);
strcpy(tmpNode->value, value);
}
return tmpNode;
}
```
AppendLinkedNode finds the last node in the linked list and appends a new node to it.
The code would be used like this:
```
if(InitHashTable(100) == false) return -1;
AddNode("10", "TEN");
```
Finding a node is a simple as:
```
HashTable* FindNode(char* key)
{
int offset = ComputeHash(key);
HashTable* tmpNode = hashTable.hashBucketArray[offset];
while(tmpNode != NULL)
{
if(strcmp(tmpNode->key, key) == 0)
return tmpNode;
tmpNode = tmpNode->nextEntry;
}
return NULL;
}
```
And is used as follows:
```
char* value = FindNode("10");
``` |
25,297 | <p>I would like to use <code>as</code> and <code>is</code> as members of an enumeration. I know that this is possible in VB.NET to write it like this:</p>
<pre><code>Public Enum Test
[as] = 1
[is] = 2
End Enum
</code></pre>
<p>How do I write the equivalent statement in C#?
The following code does not compile:</p>
<pre><code>public enum Test
{
as = 1,
is = 2
}
</code></pre>
| [
{
"answer_id": 25300,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 6,
"selected": true,
"text": "<p>Prefixing reserved words in C# is done with @.</p>\n\n<pre><code>public enum Test\n{\n @as = 1,\n @is = 2\n}\n</c... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717/"
] | I would like to use `as` and `is` as members of an enumeration. I know that this is possible in VB.NET to write it like this:
```
Public Enum Test
[as] = 1
[is] = 2
End Enum
```
How do I write the equivalent statement in C#?
The following code does not compile:
```
public enum Test
{
as = 1,
is = 2
}
``` | Prefixing reserved words in C# is done with @.
```
public enum Test
{
@as = 1,
@is = 2
}
``` |
25,349 | <p>I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma. </p>
<p>What would be, in your opinion, the best way to do this using C#.NET 2.0?</p>
| [
{
"answer_id": 25350,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>The best way is the builtin way: Use <code>string.Replace</code>. Why do you need alternatives?</p>\n"
},
{
... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684/"
] | I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma.
What would be, in your opinion, the best way to do this using C#.NET 2.0? | Why not:
```
string s = "foobar\ngork";
string v = s.Replace(Environment.NewLine,",");
System.Console.WriteLine(v);
``` |
25,449 | <p>I want to create a Java program that can be extended with plugins. How can I do that and where should I look for?</p>
<p>I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow.</p>
<hr>
<p>Although I do like Eclipse RCP, I think it's too much for my simple needs.</p>
<p>Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it.</p>
<p>But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible.</p>
| [
{
"answer_id": 25454,
"author": "John with waffle",
"author_id": 279,
"author_profile": "https://Stackoverflow.com/users/279",
"pm_score": 1,
"selected": false,
"text": "<p>Have you considered building on top of Eclipse's Rich Client Platform, and then exposing the Eclipse extension fram... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] | I want to create a Java program that can be extended with plugins. How can I do that and where should I look for?
I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow.
---
Although I do like Eclipse RCP, I think it's too much for my simple needs.
Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it.
But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible. | I've done this for software I've written in the past, it's very handy. I did it by first creating an Interface that all my 'plugin' classes needed to implement. I then used the Java [ClassLoader](http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html) to load those classes and create instances of them.
One way you can go about it is this:
```
File dir = new File("put path to classes you want to load here");
URL loadPath = dir.toURI().toURL();
URL[] classUrl = new URL[]{loadPath};
ClassLoader cl = new URLClassLoader(classUrl);
Class loadedClass = cl.loadClass("classname"); // must be in package.class name format
```
That has loaded the class, now you need to create an instance of it, assuming the interface name is MyModule:
```
MyModule modInstance = (MyModule)loadedClass.newInstance();
``` |
25,461 | <p>In a project I am interfacing between C++ and a C library that uses stdbool.h defined as such.</p>
<pre><code>#ifndef _STDBOOL_H
#define _STDBOOL_H
/* C99 Boolean types for compilers without C99 support */
/* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */
#if !defined(__cplusplus)
#if !defined(__GNUC__)
/* _Bool builtin type is included in GCC */
typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool;
#endif
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif
#endif
</code></pre>
<p>Some structures have <code>bool</code> members. So if I have one of these structures defined as local variables within a C++ function and pass it to a C function the sizes are inconsistent between C++ and C as bool is one bye in C++ and 4 in C.</p>
<p>Does anyone have any advice to how to overcome this without resorting to my current solution which is</p>
<pre><code>//#define bool _Bool
#define bool unsigned char
</code></pre>
<p>Which is against the C99 standard for <a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/stdbool.h.html" rel="noreferrer">stdbool.h</a></p>
| [
{
"answer_id": 25482,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 2,
"selected": false,
"text": "<p>Size is not the only thing that will be inconsistent here. In C++ bool is a keyword, and C++ guarantees that a bool can... | 2008/08/24 | [
"https://Stackoverflow.com/questions/25461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1675/"
] | In a project I am interfacing between C++ and a C library that uses stdbool.h defined as such.
```
#ifndef _STDBOOL_H
#define _STDBOOL_H
/* C99 Boolean types for compilers without C99 support */
/* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */
#if !defined(__cplusplus)
#if !defined(__GNUC__)
/* _Bool builtin type is included in GCC */
typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool;
#endif
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif
#endif
```
Some structures have `bool` members. So if I have one of these structures defined as local variables within a C++ function and pass it to a C function the sizes are inconsistent between C++ and C as bool is one bye in C++ and 4 in C.
Does anyone have any advice to how to overcome this without resorting to my current solution which is
```
//#define bool _Bool
#define bool unsigned char
```
Which is against the C99 standard for [stdbool.h](http://www.opengroup.org/onlinepubs/000095399/basedefs/stdbool.h.html) | I found the answer to my own question by finding a more compatible implementation of `stdbool.h` that is compliant with the C99 standard.
```
#ifndef _STDBOOL_H
#define _STDBOOL_H
#include <stdint.h>
/* C99 Boolean types for compilers without C99 support */
/* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */
#if !defined(__cplusplus)
#if !defined(__GNUC__)
/* _Bool builtin type is included in GCC */
/* ISO C Standard: 5.2.5 An object declared as
type _Bool is large enough to store
the values 0 and 1. */
/* We choose 8 bit to match C++ */
/* It must also promote to integer */
typedef int8_t _Bool;
#endif
/* ISO C Standard: 7.16 Boolean type */
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif
#endif
```
This is taken from the [Ada Class Library](http://sourceforge.net/projects/adacl) project. |
25,481 | <p>I'm trying to call an Antlr task in my Ant build.xml as follows:</p>
<pre><code><path id="classpath.build">
<fileset dir="${dir.lib.build}" includes="**/*.jar" />
</path>
...
<target name="generate-lexer" depends="init">
<antlr target="${file.antlr.lexer}">
<classpath refid="classpath.build"/>
</antlr>
</target>
</code></pre>
<p>But Ant can't find the task definition. I've put all of the following in that <code>dir.lib.build</code>:</p>
<ul>
<li>antlr-3.1.jar</li>
<li>antlr-2.7.7.jar</li>
<li>antlr-runtime-3.1.jar</li>
<li>stringtemplate-3.2.jar</li>
</ul>
<p>But none of those seems to have the task definition. (I've also tried putting those jars in my Ant classpath; same problem.)</p>
| [
{
"answer_id": 25484,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 3,
"selected": true,
"text": "<p>The current Antlr-task jar is available at <a href=\"http://www.antlr.org/share/1169924912745/antlr3-task.zip\" rel=... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | I'm trying to call an Antlr task in my Ant build.xml as follows:
```
<path id="classpath.build">
<fileset dir="${dir.lib.build}" includes="**/*.jar" />
</path>
...
<target name="generate-lexer" depends="init">
<antlr target="${file.antlr.lexer}">
<classpath refid="classpath.build"/>
</antlr>
</target>
```
But Ant can't find the task definition. I've put all of the following in that `dir.lib.build`:
* antlr-3.1.jar
* antlr-2.7.7.jar
* antlr-runtime-3.1.jar
* stringtemplate-3.2.jar
But none of those seems to have the task definition. (I've also tried putting those jars in my Ant classpath; same problem.) | The current Antlr-task jar is available at <http://www.antlr.org/share/1169924912745/antlr3-task.zip>
It can be found on the [antlr.org](http://antlr.org) website under the "File Sharing" heading. |
25,499 | <p>I'm using Visual C++ 2005 and would like to know the simplest way to connect to a MS SQL Server and execute a query.</p>
<p>I'm looking for something as simple as ADO.NET's SqlCommand class with it's ExecuteNonQuery(), ExecuteScalar() and ExecuteReader().</p>
<p>Sigh offered an answer using CDatabase and ODBC.</p>
<p>Can anybody demonstrate how it would be done using ATL consumer templates for OleDb?</p>
<p>Also what about returning a scalar value from the query?</p>
| [
{
"answer_id": 25542,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 0,
"selected": false,
"text": "<p>Try the Microsoft Enterprise Library. A version should be available <a href=\"http://www.codeplex.com/entlib\" rel=\"nofol... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2768/"
] | I'm using Visual C++ 2005 and would like to know the simplest way to connect to a MS SQL Server and execute a query.
I'm looking for something as simple as ADO.NET's SqlCommand class with it's ExecuteNonQuery(), ExecuteScalar() and ExecuteReader().
Sigh offered an answer using CDatabase and ODBC.
Can anybody demonstrate how it would be done using ATL consumer templates for OleDb?
Also what about returning a scalar value from the query? | With MFC use CDatabase and ExecuteSQL if going via a ODBC connection.
```
CDatabase db(ODBCConnectionString);
db.Open();
db.ExecuteSQL(blah);
db.Close();
``` |
25,550 | <p>We get a large amount of data from our clients in pdf files in varying formats [layout-wise], these files are typically report output, and are typically properly annotated [they don't usually need OCR], but not formatted well enough that simply copying several hundred pages of text out of acrobat is not going to work.</p>
<p>The best approach I've found so far is to write a script to parse the nearly-valid xml output (the comments are invalid and many characters are escaped in varying ways, é becomes [[[e9]]]é, $ becomes \$, % becomes \%...) of the command-line pdftoipe utility (to convert pdf files for a program called <a href="http://tclab.kaist.ac.kr/ipe/" rel="nofollow noreferrer">ipe</a>), which gives me text elements with their positions on each page [see sample below], which works well enough for reports where the same values are on the same place on every page I care about, but would require extra scripting effort for importing matrix [cross-tab] pdf files. pdftoipe is not at all intended for this, and at best can be compiled manually using cygwin for windows.</p>
<p>Are there libraries that make this easy from some scripting language I can tolerate? A graphical tool would be awesome too. And a pony. </p>
<p>pdftoipe output of <a href="http://brunndahl.navarro.se/sida_002/?CoMeT_function=get_file&id=9_1" rel="nofollow noreferrer" title="sample pdf file">this sample</a> looks like this:</p>
<pre><code><ipe creator="pdftoipe 2006/10/09"><info media="0 0 612 792"/>
<-- Page: 1 1 -->
<page gridsize="8">
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 181.8 707.88">This is a sample PDF fil</text>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 356.28 707.88">e.</text>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 368.76 707.88"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 692.4"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 677.88"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 663.36"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 648.84"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 634.32"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 619.8"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 605.28"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 590.76"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 576.24"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 561.72"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 547.2"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 532.68"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 518.16"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 503.64"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 489.12"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 474.6"> </text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 67.32 456.24">If you can read this</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 214.92 456.24">,</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 219.48 456.24"> you already have A</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 370.8 456.24">dobe Acrobat </text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 67.32 437.64">Reader i</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 131.28 437.64">n</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 141.12 437.64">stalled on your computer.</text>
<text stroke="0 0 0" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 337.92 437.64"> </text>
<text stroke="0 0.502 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 342.48 437.64"> </text>
<image width="800" height="600" rect="-92.04 800.64 374.4 449.76" ColorSpace="DeviceRGB" BitsPerComponent="8" Filter="DCTDecode" length="369925">
feedcafebabe...
</image>
</page>
</ipe>
</code></pre>
| [
{
"answer_id": 25565,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Have you looked at Aspose? We're using it for an ASP.net app and I've seen some examples of vbscript using it as well. It's ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2775/"
] | We get a large amount of data from our clients in pdf files in varying formats [layout-wise], these files are typically report output, and are typically properly annotated [they don't usually need OCR], but not formatted well enough that simply copying several hundred pages of text out of acrobat is not going to work.
The best approach I've found so far is to write a script to parse the nearly-valid xml output (the comments are invalid and many characters are escaped in varying ways, é becomes [[[e9]]]é, $ becomes \$, % becomes \%...) of the command-line pdftoipe utility (to convert pdf files for a program called [ipe](http://tclab.kaist.ac.kr/ipe/)), which gives me text elements with their positions on each page [see sample below], which works well enough for reports where the same values are on the same place on every page I care about, but would require extra scripting effort for importing matrix [cross-tab] pdf files. pdftoipe is not at all intended for this, and at best can be compiled manually using cygwin for windows.
Are there libraries that make this easy from some scripting language I can tolerate? A graphical tool would be awesome too. And a pony.
pdftoipe output of [this sample](http://brunndahl.navarro.se/sida_002/?CoMeT_function=get_file&id=9_1 "sample pdf file") looks like this:
```
<ipe creator="pdftoipe 2006/10/09"><info media="0 0 612 792"/>
<-- Page: 1 1 -->
<page gridsize="8">
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 181.8 707.88">This is a sample PDF fil</text>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 356.28 707.88">e.</text>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 368.76 707.88"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 692.4"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 677.88"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 663.36"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 648.84"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 634.32"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 619.8"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 605.28"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 590.76"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 576.24"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 561.72"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 547.2"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 532.68"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 518.16"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 503.64"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 489.12"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 474.6"> </text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 67.32 456.24">If you can read this</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 214.92 456.24">,</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 219.48 456.24"> you already have A</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 370.8 456.24">dobe Acrobat </text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 67.32 437.64">Reader i</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 131.28 437.64">n</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 141.12 437.64">stalled on your computer.</text>
<text stroke="0 0 0" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 337.92 437.64"> </text>
<text stroke="0 0.502 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 342.48 437.64"> </text>
<image width="800" height="600" rect="-92.04 800.64 374.4 449.76" ColorSpace="DeviceRGB" BitsPerComponent="8" Filter="DCTDecode" length="369925">
feedcafebabe...
</image>
</page>
</ipe>
``` | We use [Xpdf](http://www.foolabs.com/xpdf/about.html) in one of our applications. Its a c++ library which is primarily used for pdf rendering, although it does have a text extractor which could be useful for this project. |
25,552 | <p>I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows.</p>
<p>Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the Java app itself is consuming?</p>
<p>Preferrably I'd like to get this information without using JNI.</p>
| [
{
"answer_id": 25583,
"author": "Matt Cummings",
"author_id": 828,
"author_profile": "https://Stackoverflow.com/users/828",
"pm_score": 5,
"selected": false,
"text": "<p>I think the best method out there is to implement the <a href=\"https://github.com/hyperic/sigar\" rel=\"nofollow nore... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
] | I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows.
Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the Java app itself is consuming?
Preferrably I'd like to get this information without using JNI. | You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher.
```
public class Main {
public static void main(String[] args) {
/* Total number of processors or cores available to the JVM */
System.out.println("Available processors (cores): " +
Runtime.getRuntime().availableProcessors());
/* Total amount of free memory available to the JVM */
System.out.println("Free memory (bytes): " +
Runtime.getRuntime().freeMemory());
/* This will return Long.MAX_VALUE if there is no preset limit */
long maxMemory = Runtime.getRuntime().maxMemory();
/* Maximum amount of memory the JVM will attempt to use */
System.out.println("Maximum memory (bytes): " +
(maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));
/* Total memory currently available to the JVM */
System.out.println("Total memory available to JVM (bytes): " +
Runtime.getRuntime().totalMemory());
/* Get a list of all filesystem roots on this system */
File[] roots = File.listRoots();
/* For each filesystem root, print some info */
for (File root : roots) {
System.out.println("File system root: " + root.getAbsolutePath());
System.out.println("Total space (bytes): " + root.getTotalSpace());
System.out.println("Free space (bytes): " + root.getFreeSpace());
System.out.println("Usable space (bytes): " + root.getUsableSpace());
}
}
}
``` |
25,561 | <p>I am attempting to parse a string like the following using a .NET regular expression:</p>
<pre><code>H3Y5NC8E-TGA5B6SB-2NVAQ4E0
</code></pre>
<p>and return the following using Split:
H3Y5NC8E
TGA5B6SB
2NVAQ4E0</p>
<p>I validate each character against a specific character set (note that the letters 'I', 'O', 'U' & 'W' are absent), so using string.Split is not an option. The number of characters in each group can vary and the number of groups can also vary. I am using the following expression:</p>
<pre><code>([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}-?){3}
</code></pre>
<p>This will match exactly 3 groups of 8 characters each. Any more or less will fail the match.
This works insofar as it correctly matches the input. However, when I use the Split method to extract each character group, I just get the final group. RegexBuddy complains that I have repeated the capturing group itself and that I should put a capture group around the repeated group. However, none of my attempts to do this achieve the desired result. I have been trying expressions like this:</p>
<pre><code>(([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){4}
</code></pre>
<p>But this does not work.</p>
<p>Since I generate the regex in code, I could just expand it out by the number of groups, but I was hoping for a more elegant solution. </p>
<hr>
<p>Please note that the character set does not include the entire alphabet. It is part of a product activation system. As such, any characters that can be accidentally interpreted as numbers or other characters are removed. e.g. The letters 'I', 'O', 'U' & 'W' are not in the character set.</p>
<p>The hyphens are optional since a user does not need top type them in, but they can be there if the user as done a copy & paste.</p>
| [
{
"answer_id": 25567,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 0,
"selected": false,
"text": "<p>Why use Regex? If the groups are always split by a -, can't you use Split()?</p>\n"
},
{
"answer_id": 25569,
"... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2754/"
] | I am attempting to parse a string like the following using a .NET regular expression:
```
H3Y5NC8E-TGA5B6SB-2NVAQ4E0
```
and return the following using Split:
H3Y5NC8E
TGA5B6SB
2NVAQ4E0
I validate each character against a specific character set (note that the letters 'I', 'O', 'U' & 'W' are absent), so using string.Split is not an option. The number of characters in each group can vary and the number of groups can also vary. I am using the following expression:
```
([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}-?){3}
```
This will match exactly 3 groups of 8 characters each. Any more or less will fail the match.
This works insofar as it correctly matches the input. However, when I use the Split method to extract each character group, I just get the final group. RegexBuddy complains that I have repeated the capturing group itself and that I should put a capture group around the repeated group. However, none of my attempts to do this achieve the desired result. I have been trying expressions like this:
```
(([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){4}
```
But this does not work.
Since I generate the regex in code, I could just expand it out by the number of groups, but I was hoping for a more elegant solution.
---
Please note that the character set does not include the entire alphabet. It is part of a product activation system. As such, any characters that can be accidentally interpreted as numbers or other characters are removed. e.g. The letters 'I', 'O', 'U' & 'W' are not in the character set.
The hyphens are optional since a user does not need top type them in, but they can be there if the user as done a copy & paste. | I have discovered the answer I was after. Here is my working code:
```
static void Main(string[] args)
{
string pattern = @"^\s*((?<group>[ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){3}\s*$";
string input = "H3Y5NC8E-TGA5B6SB-2NVAQ4E0";
Regex re = new Regex(pattern);
Match m = re.Match(input);
if (m.Success)
foreach (Capture c in m.Groups["group"].Captures)
Console.WriteLine(c.Value);
}
``` |
25,566 | <p>I wrote an O(n!) sort for my amusement that can't be trivially optimized to run faster without replacing it entirely. [And no, I didn't just randomize the items until they were sorted]. </p>
<p>How might I write an even worse Big-O sort, without just adding extraneous junk that could be pulled out to reduce the time complexity?</p>
<p><a href="http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Big_O_notation</a> has various time complexities sorted in growing order.</p>
<p>Edit: I found the code, here is my O(n!) deterministic sort with amusing hack to generate list of all combinations of a list. I have a slightly longer version of get_all_combinations that returns an iterable of combinations, but unfortunately I couldn't make it a single statement. [Hopefully I haven't introduced bugs by fixing typos and removing underscores in the below code]</p>
<pre><code>def mysort(somelist):
for permutation in get_all_permutations(somelist):
if is_sorted(permutation):
return permutation
def is_sorted(somelist):
# note: this could be merged into return... something like return len(foo) <= 1 or reduce(barf)
if (len(somelist) <= 1): return True
return 1 > reduce(lambda x,y: max(x,y),map(cmp, somelist[:-1], somelist[1:]))
def get_all_permutations(lst):
return [[itm] + cbo for idx, itm in enumerate(lst) for cbo in get_all_permutations(lst[:idx] + lst[idx+1:])] or [lst]
</code></pre>
| [
{
"answer_id": 25572,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/13/chris-jester-young\">Chris</a> and I mentioned <a href=\"https://stackoverflow.c... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2775/"
] | I wrote an O(n!) sort for my amusement that can't be trivially optimized to run faster without replacing it entirely. [And no, I didn't just randomize the items until they were sorted].
How might I write an even worse Big-O sort, without just adding extraneous junk that could be pulled out to reduce the time complexity?
[http://en.wikipedia.org/wiki/Big\_O\_notation](http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions) has various time complexities sorted in growing order.
Edit: I found the code, here is my O(n!) deterministic sort with amusing hack to generate list of all combinations of a list. I have a slightly longer version of get\_all\_combinations that returns an iterable of combinations, but unfortunately I couldn't make it a single statement. [Hopefully I haven't introduced bugs by fixing typos and removing underscores in the below code]
```
def mysort(somelist):
for permutation in get_all_permutations(somelist):
if is_sorted(permutation):
return permutation
def is_sorted(somelist):
# note: this could be merged into return... something like return len(foo) <= 1 or reduce(barf)
if (len(somelist) <= 1): return True
return 1 > reduce(lambda x,y: max(x,y),map(cmp, somelist[:-1], somelist[1:]))
def get_all_permutations(lst):
return [[itm] + cbo for idx, itm in enumerate(lst) for cbo in get_all_permutations(lst[:idx] + lst[idx+1:])] or [lst]
``` | There's a (proven!) worst sorting algorithm called [slow sort](http://c2.com/cgi/wiki?SlowSort) that uses the “multiply and surrender” paradigm and runs in exponential time.
While your algorithm is slower, it doesn't progress steadily but instead performs random jumps. Additionally, slow sort's best case is still exponential while yours is constant. |
25,637 | <p>Is there a way to shutdown a computer using a built-in Java method?</p>
| [
{
"answer_id": 25644,
"author": "David McGraw",
"author_id": 568,
"author_profile": "https://Stackoverflow.com/users/568",
"pm_score": 8,
"selected": true,
"text": "<p>Create your own function to execute an OS command through the <a href=\"http://www.computerhope.com/shutdown.htm\" rel=\... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] | Is there a way to shutdown a computer using a built-in Java method? | Create your own function to execute an OS command through the [command line](http://www.computerhope.com/shutdown.htm)?
For the sake of an example. But know where and why you'd want to use this as others note.
```
public static void main(String arg[]) throws IOException{
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("shutdown -s -t 0");
System.exit(0);
}
``` |
25,642 | <p>I want to catch the NavigationService.Navigating event from my Page, to prevent the user from navigating forward. I have an event handler defined thusly:</p>
<pre><code>void PreventForwardNavigation(object sender, NavigatingCancelEventArgs e)
{
if (e.NavigationMode == NavigationMode.Forward)
{
e.Cancel = true;
}
}
</code></pre>
<p>... and that works fine. However, I am unsure exactly where to place this code:</p>
<pre><code>NavigationService.Navigating += PreventForwardNavigation;
</code></pre>
<p>If I place it in the constructor of the page, or the Initialized event handler, then NavigationService is still null and I get a NullReferenceException. However, if I place it in the Loaded event handler for the Page, then it is called every time the page is navigated to. If I understand right, that means I'm handling the same event multiple times. </p>
<p>Am I ok to add the same handler to the event multiple times (as would happen were I to use the page's Loaded event to hook it up)? If not, is there some place in between Initialized and Loaded where I can do this wiring?</p>
| [
{
"answer_id": 25644,
"author": "David McGraw",
"author_id": 568,
"author_profile": "https://Stackoverflow.com/users/568",
"pm_score": 8,
"selected": true,
"text": "<p>Create your own function to execute an OS command through the <a href=\"http://www.computerhope.com/shutdown.htm\" rel=\... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
] | I want to catch the NavigationService.Navigating event from my Page, to prevent the user from navigating forward. I have an event handler defined thusly:
```
void PreventForwardNavigation(object sender, NavigatingCancelEventArgs e)
{
if (e.NavigationMode == NavigationMode.Forward)
{
e.Cancel = true;
}
}
```
... and that works fine. However, I am unsure exactly where to place this code:
```
NavigationService.Navigating += PreventForwardNavigation;
```
If I place it in the constructor of the page, or the Initialized event handler, then NavigationService is still null and I get a NullReferenceException. However, if I place it in the Loaded event handler for the Page, then it is called every time the page is navigated to. If I understand right, that means I'm handling the same event multiple times.
Am I ok to add the same handler to the event multiple times (as would happen were I to use the page's Loaded event to hook it up)? If not, is there some place in between Initialized and Loaded where I can do this wiring? | Create your own function to execute an OS command through the [command line](http://www.computerhope.com/shutdown.htm)?
For the sake of an example. But know where and why you'd want to use this as others note.
```
public static void main(String arg[]) throws IOException{
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("shutdown -s -t 0");
System.exit(0);
}
``` |
25,646 | <p>The following code writes no data to the back buffer on Intel integrated video cards,for example, on a MacBook. On ATI cards, such as in the iMac, it draws to the back buffer. The width and height are correct (and 800x600 buffer) and m_PixelBuffer is correctly filled with 0xAA00AA00.</p>
<p>My best guess so far is that there is something amiss with needing glWindowPos set. I do not currently set it (or the raster position), and when I get GL_CURRENT_RASTER_POSITION I noticed that the default on the ATI card is 0,0,0,0 and the Intel it's 0,0,0,1. When I set the raster pos on the ATI card to 0,0,0,1 I get the same result as the Intel card, nothing drawn to the back buffer. Is there some transform state I'm missing? This is a 2D application so the view transform is a very simple glOrtho.</p>
<pre><code>glDrawPixels(GetBufferWidth(), GetBufferHeight(), GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, m_PixelBuffer);
</code></pre>
<p>Any more info I can provide, please ask. I'm pretty much an OpenGL and Mac newb so I don't know if I'm providing enough information.</p>
| [
{
"answer_id": 25864,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 2,
"selected": false,
"text": "<p>I've always had problems with OpenGL implementations from Intel, though I'm not sure that's your problem this time. I think... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1329401/"
] | The following code writes no data to the back buffer on Intel integrated video cards,for example, on a MacBook. On ATI cards, such as in the iMac, it draws to the back buffer. The width and height are correct (and 800x600 buffer) and m\_PixelBuffer is correctly filled with 0xAA00AA00.
My best guess so far is that there is something amiss with needing glWindowPos set. I do not currently set it (or the raster position), and when I get GL\_CURRENT\_RASTER\_POSITION I noticed that the default on the ATI card is 0,0,0,0 and the Intel it's 0,0,0,1. When I set the raster pos on the ATI card to 0,0,0,1 I get the same result as the Intel card, nothing drawn to the back buffer. Is there some transform state I'm missing? This is a 2D application so the view transform is a very simple glOrtho.
```
glDrawPixels(GetBufferWidth(), GetBufferHeight(), GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, m_PixelBuffer);
```
Any more info I can provide, please ask. I'm pretty much an OpenGL and Mac newb so I don't know if I'm providing enough information. | I've always had problems with OpenGL implementations from Intel, though I'm not sure that's your problem this time. I think you're running into some byte-order issues. Give this a read and feel free to experiment with different constants for packing and color order.
<http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_25.html>
I know it's OSX guide, you can probably find similar OpenGL articles on other sites for other platforms. This should be applicable. |
25,653 | <p>Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column?</p>
<p>For instance, I can currently set the display name of a column like this:</p>
<pre><code>[DisplayName("Last name")]
public object Last_name { get; set; }
</code></pre>
<p>Is there a similar way to hide a column?</p>
<p><strong>Edit</strong>: Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer :-)</p>
| [
{
"answer_id": 25667,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 5,
"selected": true,
"text": "<p>Had no idea what ASP.NET Dynamic Data was so you promted me to so some research :)</p>\n\n<p>Looks like the propert... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column?
For instance, I can currently set the display name of a column like this:
```
[DisplayName("Last name")]
public object Last_name { get; set; }
```
Is there a similar way to hide a column?
**Edit**: Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer :-) | Had no idea what ASP.NET Dynamic Data was so you promted me to so some research :)
Looks like the property you are looking for is
```
[ScaffoldColumn(false)]
```
There is also a similar property for tables
```
[ScaffoldTable(false)]
```
[source](http://davidhayden.com/blog/dave/archive/2008/05/15/DynamicDataWebsitesScaffoldTableScaffoldColumnAttributes.aspx) |
25,672 | <p>Been going over my predecessor's code and see usage of the "request" scope frequently. What is the appropriate usage of this scope?</p>
| [
{
"answer_id": 26725,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 5,
"selected": true,
"text": "<p>There are several scopes that are available to any portion of your code: Session, Client, Cookie, Application, and Reques... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Been going over my predecessor's code and see usage of the "request" scope frequently. What is the appropriate usage of this scope? | There are several scopes that are available to any portion of your code: Session, Client, Cookie, Application, and Request. Some are inadvisable to use in certain ways (i.e. using Request or Application scope inside your Custom Tags or CFC's; this is [coupling](http://en.wikipedia.org/wiki/Coupling_%28computer_science%29), violates encapsulation principles, and is considered a bad practice), and some have special purposes: Cookie is persisted on the client machine as physical cookies, and Session scoped variables are user-specific and expire with the user's session on the website.
If a variable is extremely unlikely to change (constant for all intents and purposes) and can simply be initialized on application startup and never written again, generally you should put it into Application scope because this persists it between every user and every session. When properly implemented it is written once and read N times.
A proper implementation of Application variables in Application.cfm might look like this:
```
<cfif not structKeyExists(application, "dsn")>
<cflock scope="application" type="exclusive" timeout="30">
<cfif not structKeyExists(application, "dsn")>
<cfset application.dsn = "MyDSN" />
<cfset foo = "bar" />
<cfset x = 5 />
</cfif>
</cflock>
</cfif>
```
Note that the existence of the variable in the application scope is checked before and after the lock, so that if two users create a race condition at application startup, only one of them will end up setting the application variables.
The benefit of this approach is that it won't constantly refresh these stored variables on every request, wasting the user's time and the server's processing cycles. The trade-off is that it is a little verbose and complex.
This was greatly simplified with the addition of Application.cfc. Now, you can specify which variables are created on application startup and don't have to worry about locking and checking for existence and all of that fun stuff:
```
<cfcomponent>
<cfset this.name = "myApplicationName" />
<cffunction name="onApplicationStart" returnType="boolean" output="false">
<cfset application.dsn = "MyDSN" />
<cfset foo = "bar" />
<cfset x = 5 />
<cfreturn true />
</cffunction>
</cfcomponent>
```
For more information on Application.cfc including all of the various special functions available and every little detail about what and how to use it, [I recommend this post on Raymond Camden's blog](http://www.raymondcamden.com/2007/11/09/Applicationcfc-Methods-and-Example-Uses).
To summarize, request scope is available everywhere in your code, but that doesn't necessarily make it "right" to use it everywhere. Chances are that your predecessor was using it to break encapsulation, and that can be cumbersome to refactor out. You may be best off leaving it as-is, but understanding which scope is the best tool for the job will definitely make your future code better. |
25,746 | <p>I'm learning objective-C and Cocoa and have come across this statement:</p>
<blockquote>
<p>The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings.</p>
</blockquote>
<p>I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal?</p>
| [
{
"answer_id": 25750,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>Let's use C++, since my Objective C is totally non-existent.</p>\n\n<p>If you stash a string into a constant variable:... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2799/"
] | I'm learning objective-C and Cocoa and have come across this statement:
>
> The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings.
>
>
>
I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal? | In Objective-C, the syntax `@"foo"` is an **immutable**, **literal** instance of `NSString`. It does not make a constant string from a string literal as Mike assume.
Objective-C compilers typically *do* intern literal strings within compilation units — that is, they coalesce multiple uses of the same literal string — and it's possible for the linker to do additional interning across the compilation units that are directly linked into a single binary. (Since Cocoa distinguishes between mutable and immutable strings, and literal strings are always also immutable, this can be straightforward and safe.)
**Constant** strings on the other hand are typically declared and defined using syntax like this:
```
// MyExample.h - declaration, other code references this
extern NSString * const MyExampleNotification;
// MyExample.m - definition, compiled for other code to reference
NSString * const MyExampleNotification = @"MyExampleNotification";
```
The point of the syntactic exercise here is that you can make *uses of* the string efficient by ensuring that there's only one instance of that string in use *even across multiple frameworks* (shared libraries) in the same address space. (The placement of the `const` keyword matters; it guarantees that the pointer itself is guaranteed to be constant.)
While burning memory isn't as big a deal as it may have been in the days of 25MHz 68030 workstations with 8MB of RAM, comparing strings for equality can take time. Ensuring that most of the time strings that are equal will also be pointer-equal helps.
Say, for example, you want to subscribe to notifications from an object by name. If you use non-constant strings for the names, the `NSNotificationCenter` posting the notification could wind up doing a lot of byte-by-byte string comparisons when determining who is interested in it. If most of these comparisons are short-circuited because the strings being compared have the same pointer, that can be a big win. |
25,752 | <p>In a drop down list, I need to add spaces in front of the options in the list. I am trying</p>
<pre><code><select>
<option>&#32;&#32;Sample</option>
</select>
</code></pre>
<p>for adding two spaces but it displays no spaces. How can I add spaces before option texts?</p>
| [
{
"answer_id": 25754,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "<pre><code>&nbsp;\n</code></pre>\n\n<p>Can you try that? Or is it the same?</p>\n"
},
{
"answer_id": 25758,
"au... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | In a drop down list, I need to add spaces in front of the options in the list. I am trying
```
<select>
<option>  Sample</option>
</select>
```
for adding two spaces but it displays no spaces. How can I add spaces before option texts? | Isn't ` ` the entity for space?
```
<select>
<option> option 1</option>
<option> option 2</option>
</select>
```
Works for me...
### EDIT:
Just checked this out, there *may* be compatibility issues with this in older browsers, but all seems to work fine for me here. Just thought I should let you know as you may want to replace with ` ` |
25,767 | <p>What is the quickest way to get a large amount of data (think golf) and the most efficient (think performance) to get a large amount of data from a MySQL database to a session without having to continue doing what I already have:</p>
<pre><code>$sql = "SELECT * FROM users WHERE username='" . mysql_escape_string($_POST['username']) . "' AND password='" . mysql_escape_string(md5($_POST['password'])) . "'";
$result = mysql_query($sql, $link) or die("There was an error while trying to get your information.\n<!--\n" . mysql_error($link) . "\n-->");
if(mysql_num_rows($result) < 1)
{
$_SESSION['username'] = $_POST['username'];
redirect('index.php?p=signup');
}
$_SESSION['id'] = mysql_result($result, '0', 'id');
$_SESSION['fName'] = mysql_result($result, '0', 'fName');
$_SESSION['lName'] = mysql_result($result, '0', 'lName');
...
</code></pre>
<p>And before anyone asks yes I do really need to 'SELECT </p>
<p>Edit: Yes, I am sanitizing the data, so that there can be no SQL injection, that is further up in the code.</p>
| [
{
"answer_id": 25770,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>OK, this doesn't answer your question, but doesn't your current code leave you open to SQL Injection?</p>\n<p>I could be ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | What is the quickest way to get a large amount of data (think golf) and the most efficient (think performance) to get a large amount of data from a MySQL database to a session without having to continue doing what I already have:
```
$sql = "SELECT * FROM users WHERE username='" . mysql_escape_string($_POST['username']) . "' AND password='" . mysql_escape_string(md5($_POST['password'])) . "'";
$result = mysql_query($sql, $link) or die("There was an error while trying to get your information.\n<!--\n" . mysql_error($link) . "\n-->");
if(mysql_num_rows($result) < 1)
{
$_SESSION['username'] = $_POST['username'];
redirect('index.php?p=signup');
}
$_SESSION['id'] = mysql_result($result, '0', 'id');
$_SESSION['fName'] = mysql_result($result, '0', 'fName');
$_SESSION['lName'] = mysql_result($result, '0', 'lName');
...
```
And before anyone asks yes I do really need to 'SELECT
Edit: Yes, I am sanitizing the data, so that there can be no SQL injection, that is further up in the code. | I came up with this and it appears to work.
```
while($row = mysql_fetch_assoc($result))
{
$_SESSION = array_merge_recursive($_SESSION, $row);
}
``` |
25,771 | <p>How can I insert compilation timestamp information into an executable I build with Visual C++ 2005? I want to be able to output something like this when I execute the program:</p>
<blockquote>
<p>This build XXXX was compiled at dd-mm-yy, hh:mm.</p>
</blockquote>
<p>where date and time reflect the time when the project was built. They should not change with each successive call of the program, unless it's recompiled.</p>
| [
{
"answer_id": 25780,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 3,
"selected": false,
"text": "<pre><code>__DATE__ \n__TIME__\n</code></pre>\n\n<p>are predefined as part of the standards for C99 so should be available to y... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How can I insert compilation timestamp information into an executable I build with Visual C++ 2005? I want to be able to output something like this when I execute the program:
>
> This build XXXX was compiled at dd-mm-yy, hh:mm.
>
>
>
where date and time reflect the time when the project was built. They should not change with each successive call of the program, unless it's recompiled. | Though not your exact format, **DATE** will be of the format Mmm dd yyyy, while **TIME** will be of the format hh:mm:ss. You can create a string like this and use it in whatever print routine makes sense for you:
```
const char *buildString = "This build XXXX was compiled at " __DATE__ ", " __TIME__ ".";
```
(Note on another answer: **TIMESTAMP** only spits out the modification date/time of the source file, not the build date/time.) |
25,785 | <p>Is there a simple way, in a pretty standard UNIX environment with bash, to run a command to delete all but the most recent X files from a directory?</p>
<p>To give a bit more of a concrete example, imagine some cron job writing out a file (say, a log file or a tar-ed up backup) to a directory every hour. I'd like a way to have another cron job running which would remove the oldest files in that directory until there are less than, say, 5.</p>
<p>And just to be clear, there's only one file present, it should never be deleted.</p>
| [
{
"answer_id": 25789,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 7,
"selected": false,
"text": "<p>Remove all but 5 (or whatever number) of the most recent files in a directory.</p>\n\n<pre><code>rm `ls -t | awk 'NR>5'`\n... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | Is there a simple way, in a pretty standard UNIX environment with bash, to run a command to delete all but the most recent X files from a directory?
To give a bit more of a concrete example, imagine some cron job writing out a file (say, a log file or a tar-ed up backup) to a directory every hour. I'd like a way to have another cron job running which would remove the oldest files in that directory until there are less than, say, 5.
And just to be clear, there's only one file present, it should never be deleted. | **For Linux** (GNU tools), an efficient & robust way to keep the `n` newest files in the current directory while removing the rest:
```bash
n=5
find . -maxdepth 1 -type f -printf '%T@ %p\0' |
sort -z -nrt ' ' -k1,1 |
sed -z -e "1,${n}d" -e 's/[^ ]* //' |
xargs -0r rm -f
```
---
**For BSD**, `find` doesn't have the `-printf` predicate, `stat` can't output NULL bytes, and `sed` + `awk` can't handle `NULL`-delimited records.
Here's a solution that **doesn't support newlines in paths** but that safeguards against them by filtering them out:
```bash
#!/bin/bash
n=5
find . -maxdepth 1 -type f ! -path $'*\n*' -exec stat -f '%.9Fm %N' {} + |
sort -nrt ' ' -k1,1 |
awk -v n="$n" -F'^[^ ]* ' 'NR > n {printf "%s%c", $2, 0}' |
xargs -0 rm -f
```
**note:** I'm using `bash` because of the `$'\n'` notation. For `sh` you can define a variable containing a literal newline and use it instead.
---
Solution for **UNIX & Linux** (inspired from AIX/HP-UX/SunOS/BSD/Linux `ls -b`):
Some platforms don't provide `find -printf`, nor `stat`, nor support `NULL`-delimited records with `stat`/`sort`/`awk`/`sed`/`xargs`. That's why using `perl` is probably the most portable way to tackle the problem, because it is available by default in almost every OS.
I could have written the whole thing in `perl` but I didn't. I only use it for substituting `stat` and for encoding-decoding-escaping the filenames. The core logic is the same as the previous solutions and is implemented with POSIX tools.
**note:** `perl`'s default `stat` has a resolution of a second, but starting from `perl-5.8.9` you can get sub-second resolution with the `stat` function of the module `Time::HiRes` (when both the OS and the filesystem support it). That's what I'm using here; if your `perl` doesn't provide it then you can remove the `‑MTime::HiRes=stat` from the command line.
```bash
n=5
find . '(' -name '.' -o -prune ')' -type f -exec \
perl -MTime::HiRes=stat -le '
foreach (@ARGV) {
@st = stat($_);
if ( @st > 0 ) {
s/([\\\n])/sprintf( "\\%03o", ord($1) )/ge;
print sprintf( "%.9f %s", $st[9], $_ );
}
else { print STDERR "stat: $_: $!"; }
}
' {} + |
sort -nrt ' ' -k1,1 |
sed -e "1,${n}d" -e 's/[^ ]* //' |
perl -l -ne '
s/\\([0-7]{3})/chr(oct($1))/ge;
s/(["\n])/"\\$1"/g;
print "\"$_\"";
' |
xargs -E '' sh -c '[ "$#" -gt 0 ] && rm -f "$@"' sh
```
**Explanations:**
* For each file found, the first `perl` gets the modification time and outputs it along the encoded filename (each `newline` and `backslash` characters are replaced with the literals `\n` and `\\` respectively).
* Now each `time filename` is guaranteed to be single-line, so POSIX `sort` and `sed` can safely work with this stream.
* The second `perl` decodes the filenames and escapes them for POSIX `xargs`.
* Lastly, `xargs` calls `rm` for deleting the files. The `sh` command is a trick that prevents `xargs` from running `rm` when there's no files to delete. |
25,803 | <p>For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature). </p>
<p>How do I accomplish this assuming that: </p>
<ul>
<li>I don't want to use any 3rd party
AOP libraries for C#,</li>
<li>I don't want to add duplicate code to all the methods that I want to trace, </li>
<li>I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way. </li>
</ul>
<p>To make the question more concrete let's assume there are 3 classes: </p>
<pre><code> public class Caller
{
public static void Call()
{
Traced traced = new Traced();
traced.Method1();
traced.Method2();
}
}
public class Traced
{
public void Method1(String name, Int32 value) { }
public void Method2(Object object) { }
}
public class Logger
{
public static void LogStart(MethodInfo method, Object[] parameterValues);
public static void LogEnd(MethodInfo method);
}
</code></pre>
<p>How do I invoke <em>Logger.LogStart</em> and <em>Logger.LogEnd</em> for every call to <em>Method1</em> and <em>Method2</em> without modifying the <em>Caller.Call</em> method and without adding the calls explicitly to <em>Traced.Method1</em> and <em>Traced.Method2</em>?</p>
<p>Edit: What would be the solution if I'm allowed to slightly change the Call method?</p>
| [
{
"answer_id": 25806,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": -1,
"selected": false,
"text": "<ol>\n<li>Write your own AOP library.</li>\n<li>Use reflection to generate a logging proxy over your instances (not sure if yo... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2800/"
] | For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature).
How do I accomplish this assuming that:
* I don't want to use any 3rd party
AOP libraries for C#,
* I don't want to add duplicate code to all the methods that I want to trace,
* I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way.
To make the question more concrete let's assume there are 3 classes:
```
public class Caller
{
public static void Call()
{
Traced traced = new Traced();
traced.Method1();
traced.Method2();
}
}
public class Traced
{
public void Method1(String name, Int32 value) { }
public void Method2(Object object) { }
}
public class Logger
{
public static void LogStart(MethodInfo method, Object[] parameterValues);
public static void LogEnd(MethodInfo method);
}
```
How do I invoke *Logger.LogStart* and *Logger.LogEnd* for every call to *Method1* and *Method2* without modifying the *Caller.Call* method and without adding the calls explicitly to *Traced.Method1* and *Traced.Method2*?
Edit: What would be the solution if I'm allowed to slightly change the Call method? | C# is not an AOP oriented language. It has some AOP features and you can emulate some others but making AOP with C# is painful.
I looked up for ways to do exactly what you wanted to do and I found no easy way to do it.
As I understand it, this is what you want to do:
```
[Log()]
public void Method1(String name, Int32 value);
```
and in order to do that you have two main options
1. Inherit your class from MarshalByRefObject or ContextBoundObject and define an attribute which inherits from IMessageSink. [This article](http://www.developerfusion.co.uk/show/5307/3/) has a good example. You have to consider nontheless that using a MarshalByRefObject the performance will go down like hell, and I mean it, I'm talking about a 10x performance lost so think carefully before trying that.
2. The other option is to inject code directly. In runtime, meaning you'll have to use reflection to "read" every class, get its attributes and inject the appropiate call (and for that matter I think you couldn't use the Reflection.Emit method as I think Reflection.Emit wouldn't allow you to insert new code inside an already existing method). At design time this will mean creating an extension to the CLR compiler which I have honestly no idea on how it's done.
The final option is using an [IoC framework](http://en.wikipedia.org/wiki/Inversion_of_control). Maybe it's not the perfect solution as most IoC frameworks works by defining entry points which allow methods to be hooked but, depending on what you want to achive, that might be a fair aproximation. |
25,807 | <p>If I have Python code</p>
<pre><code>class A():
pass
class B():
pass
class C(A, B):
pass
</code></pre>
<p>and I have class <code>C</code>, is there a way to iterate through it's super classed (<code>A</code> and <code>B</code>)? Something like pseudocode:</p>
<pre><code>>>> magicGetSuperClasses(C)
(<type 'A'>, <type 'B'>)
</code></pre>
<p>One solution seems to be <a href="http://docs.python.org/lib/module-inspect.html" rel="noreferrer">inspect module</a> and <code>getclasstree</code> function.</p>
<pre><code>def magicGetSuperClasses(cls):
return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type]
</code></pre>
<p>but is this a "Pythonian" way to achieve the goal?</p>
| [
{
"answer_id": 25815,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 6,
"selected": true,
"text": "<p><code>C.__bases__</code> is an array of the super classes, so you could implement your hypothetical function like so:</p>\n\n<... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679/"
] | If I have Python code
```
class A():
pass
class B():
pass
class C(A, B):
pass
```
and I have class `C`, is there a way to iterate through it's super classed (`A` and `B`)? Something like pseudocode:
```
>>> magicGetSuperClasses(C)
(<type 'A'>, <type 'B'>)
```
One solution seems to be [inspect module](http://docs.python.org/lib/module-inspect.html) and `getclasstree` function.
```
def magicGetSuperClasses(cls):
return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type]
```
but is this a "Pythonian" way to achieve the goal? | `C.__bases__` is an array of the super classes, so you could implement your hypothetical function like so:
```
def magicGetSuperClasses(cls):
return cls.__bases__
```
But I imagine it would be easier to just reference `cls.__bases__` directly in most cases. |
25,841 | <p>How do you get the maximum number of bytes that can be passed to a <code>sendto(..)</code> call for a socket opened as a UDP port?</p>
| [
{
"answer_id": 25853,
"author": "Kristof Provost",
"author_id": 1466,
"author_profile": "https://Stackoverflow.com/users/1466",
"pm_score": 2,
"selected": false,
"text": "<p>As UDP is not connection oriented there's no way to indicate that two packets belong together. As a result you're ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/842/"
] | How do you get the maximum number of bytes that can be passed to a `sendto(..)` call for a socket opened as a UDP port? | Use getsockopt(). [This site](http://www.mkssoftware.com/docs/man3/getsockopt.3.asp) has a good breakdown of the usage and options you can retrieve.
In Windows, you can do:
```
int optlen = sizeof(int);
int optval;
getsockopt(socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (int *)&optval, &optlen);
```
For Linux, according to the UDP man page, the kernel will use MTU discovery (it will check what the maximum UDP packet size is between here and the destination, and pick that), or if MTU discovery is off, it'll set the maximum size to the interface MTU and fragment anything larger. If you're sending over Ethernet, the typical MTU is 1500 bytes. |
25,846 | <p>I know that MAC OS X 10.5 comes with Apache installed but I would like to install the latest Apache without touching the OS Defaults incase it causes problems in the future with other udpates. So I have used the details located at: <a href="http://diymacserver.com/installing-apache/compiling-apache-on-leopard/" rel="nofollow noreferrer">http://diymacserver.com/installing-apache/compiling-apache-on-leopard/</a> But I'm unsure how to make this the 64 Bit version of Apache as it seems to still install the 32 bit version.</p>
<p>Any help is appreciated</p>
<p>Cheers</p>
| [
{
"answer_id": 25851,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 2,
"selected": false,
"text": "<p>Add this to your ~/.bash_profile which means that your architecture is 64-bit ant you’d like to compile Universal binaries.</... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2196/"
] | I know that MAC OS X 10.5 comes with Apache installed but I would like to install the latest Apache without touching the OS Defaults incase it causes problems in the future with other udpates. So I have used the details located at: <http://diymacserver.com/installing-apache/compiling-apache-on-leopard/> But I'm unsure how to make this the 64 Bit version of Apache as it seems to still install the 32 bit version.
Any help is appreciated
Cheers | Add this to your ~/.bash\_profile which means that your architecture is 64-bit ant you’d like to compile Universal binaries.
```
export CFLAGS="-arch x86_64"
``` |
25,871 | <p>We created several custom web parts for SharePoint 2007. They work fine. However whenever they are loaded, we get an error in the event log saying:</p>
<blockquote>
<p>error initializing safe control - Assembly: ...</p>
</blockquote>
<p>The assembly actually loads fine. Additionally, it is correctly listed in the <code>web.config</code> and <code>GAC</code>.</p>
<p>Any ideas about how to stop these (Phantom?) errors would be appreciated.
</p>
| [
{
"answer_id": 25882,
"author": "Daniel Pollard",
"author_id": 2758,
"author_profile": "https://Stackoverflow.com/users/2758",
"pm_score": 2,
"selected": false,
"text": "<p>You need to add a safecontrol entry to the web,config file, have a look at the following:</p>\n\n<pre><code><Saf... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | We created several custom web parts for SharePoint 2007. They work fine. However whenever they are loaded, we get an error in the event log saying:
>
> error initializing safe control - Assembly: ...
>
>
>
The assembly actually loads fine. Additionally, it is correctly listed in the `web.config` and `GAC`.
Any ideas about how to stop these (Phantom?) errors would be appreciated.
| You need to add a safecontrol entry to the web,config file, have a look at the following:
```
<SafeControls>
<SafeControl
Assembly = "Text"
Namespace = "Text"
Safe = "TRUE" | "FALSE"
TypeName = "Text"/>
...
</SafeControls>
```
<http://msdn.microsoft.com/en-us/library/ms413697.aspx> |
25,914 | <p>I'm trying to setup CruiseControl.net webdashboard at the moment. So far it works nice, but I have a problem with the NAnt Build Timing Report.</p>
<p>Firstly, my current <code>ccnet.config</code> file looks something like this:</p>
<pre><code><project name="bla">
...
<prebuild>
<nant .../>
</prebuild>
<tasks>
<nant .../>
</tasks>
<publishers>
<nant .../>
</publishers>
...
</project>
</code></pre>
<p>As the build completes, NAnt timing report displays three duplicate summaries. Is there a way to fix this without changing the project structure?
</p>
| [
{
"answer_id": 26166,
"author": "Mike Caron",
"author_id": 2836,
"author_profile": "https://Stackoverflow.com/users/2836",
"pm_score": -1,
"selected": false,
"text": "<p>Not a direct answer to your question, but you might want to check out Hudson. It has the benefit of being much easier ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1085/"
] | I'm trying to setup CruiseControl.net webdashboard at the moment. So far it works nice, but I have a problem with the NAnt Build Timing Report.
Firstly, my current `ccnet.config` file looks something like this:
```
<project name="bla">
...
<prebuild>
<nant .../>
</prebuild>
<tasks>
<nant .../>
</tasks>
<publishers>
<nant .../>
</publishers>
...
</project>
```
As the build completes, NAnt timing report displays three duplicate summaries. Is there a way to fix this without changing the project structure?
| Apparently this can be solved by selecting only the first `<buildresults>` node in webdashboard's NAntTiming.xsl. Because each duplicate summary contains the same info this change in `<div id="NAntTimingReport">` section seems to be sufficient:
```
<xsl:variable name="buildresults" select="//build/buildresults[1]" />
``` |
25,938 | <p>I need to have a summary field in each page of the report and in page 2 and forward the same summary has to appear at the top of the page. Anyone know how to do this?
Ex:</p>
<pre><code>>
> Page 1
>
> Name Value
> a 1
> b 3
> Total 4
>
> Page 2
> Name Value
> Total Before 4
> c 5
> d 1
> Total 10
</code></pre>
| [
{
"answer_id": 26144,
"author": "Carlton Jenke",
"author_id": 1215,
"author_profile": "https://Stackoverflow.com/users/1215",
"pm_score": 0,
"selected": false,
"text": "<p>I do not understand your question all the way.</p>\n\n<p>If you need an overall summary that is repeated, you would ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154/"
] | I need to have a summary field in each page of the report and in page 2 and forward the same summary has to appear at the top of the page. Anyone know how to do this?
Ex:
```
>
> Page 1
>
> Name Value
> a 1
> b 3
> Total 4
>
> Page 2
> Name Value
> Total Before 4
> c 5
> d 1
> Total 10
``` | Create a new Running Total Field called, for example "RTotal". In "Field to summarize" select "Value", in "Type of summary" select "sum", under "Evaluate" select "For each record". You can then drag this field into your report to use as the "Total" at the bottom of each page.
You cannot use this running total field in the page header too, however, because Crystal will add the value in the first row on the page to it first (so in your example it would show 9 rather than 4 at the top of page 2). To work around this, create a formula field which subtracts the current value of the Value field from the running total (e.g. {#RTotal}-{TableName.Value}), and put this formula field in your page header. |
25,969 | <p>I am trying to <code>INSERT INTO</code> a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the <code>SQL</code> engine of the day (<a href="http://en.wikipedia.org/wiki/MySQL" rel="noreferrer">MySQL</a>, <a href="http://en.wikipedia.org/wiki/Oracle_Database" rel="noreferrer">Oracle</a>, <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer">SQL Server</a>, <a href="http://en.wikipedia.org/wiki/IBM_Informix" rel="noreferrer">Informix</a>, and <a href="http://en.wikipedia.org/wiki/IBM_DB2" rel="noreferrer">DB2</a>).</p>
<p>Is there a silver-bullet syntax coming from an SQL standard (for example, <a href="http://en.wikipedia.org/wiki/SQL-92" rel="noreferrer">SQL-92</a>) that would allow me to insert the values without worrying about the underlying database?</p>
| [
{
"answer_id": 25971,
"author": "Claude Houle",
"author_id": 244,
"author_profile": "https://Stackoverflow.com/users/244",
"pm_score": 12,
"selected": true,
"text": "<p>Try:</p>\n<pre><code>INSERT INTO table1 ( column1 )\nSELECT col1\nFROM table2 \n</code></pre>\n<p>This is standard... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/244/"
] | I am trying to `INSERT INTO` a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the `SQL` engine of the day ([MySQL](http://en.wikipedia.org/wiki/MySQL), [Oracle](http://en.wikipedia.org/wiki/Oracle_Database), [SQL Server](http://en.wikipedia.org/wiki/Microsoft_SQL_Server), [Informix](http://en.wikipedia.org/wiki/IBM_Informix), and [DB2](http://en.wikipedia.org/wiki/IBM_DB2)).
Is there a silver-bullet syntax coming from an SQL standard (for example, [SQL-92](http://en.wikipedia.org/wiki/SQL-92)) that would allow me to insert the values without worrying about the underlying database? | Try:
```
INSERT INTO table1 ( column1 )
SELECT col1
FROM table2
```
This is standard ANSI SQL and should work on any DBMS
It definitely works for:
* Oracle
* MS SQL Server
* MySQL
* Postgres
* SQLite v3
* Teradata
* DB2
* Sybase
* Vertica
* HSQLDB
* H2
* AWS RedShift
* SAP HANA
* Google Spanner |
25,975 | <p>The Compact Framework doesn't support Assembly.GetEntryAssembly to determine the launching .exe. So is there another way to get the name of the executing .exe?</p>
<p>EDIT: I found the answer on Peter Foot's blog: <a href="http://peterfoot.net/default.aspx" rel="nofollow noreferrer">http://peterfoot.net/default.aspx</a>
Here is the code:</p>
<pre><code>byte[] buffer = new byte[MAX_PATH * 2];
int chars = GetModuleFileName(IntPtr.Zero, buffer, MAX_PATH);
if (chars > 0)
{
string assemblyPath = System.Text.Encoding.Unicode.GetString(buffer, 0, chars * 2);
}
[DllImport("coredll.dll", SetLastError = true)]
private static extern int GetModuleFileName(IntPtr hModule, byte[] lpFilename, int nSize);
</code></pre>
| [
{
"answer_id": 25987,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 3,
"selected": true,
"text": "<p>I am not sure whether it works from managed code (or even the compact framework), but in Win32 you can call GetModuleFileName... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1382/"
] | The Compact Framework doesn't support Assembly.GetEntryAssembly to determine the launching .exe. So is there another way to get the name of the executing .exe?
EDIT: I found the answer on Peter Foot's blog: <http://peterfoot.net/default.aspx>
Here is the code:
```
byte[] buffer = new byte[MAX_PATH * 2];
int chars = GetModuleFileName(IntPtr.Zero, buffer, MAX_PATH);
if (chars > 0)
{
string assemblyPath = System.Text.Encoding.Unicode.GetString(buffer, 0, chars * 2);
}
[DllImport("coredll.dll", SetLastError = true)]
private static extern int GetModuleFileName(IntPtr hModule, byte[] lpFilename, int nSize);
``` | I am not sure whether it works from managed code (or even the compact framework), but in Win32 you can call GetModuleFileName to find the running exe file.
[MSDN: GetModuleFileName](http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx) |
25,982 | <p>Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it?</p>
<p>This is what I'm doing at the moment:</p>
<pre><code>ChannelServices.RegisterChannel(new HttpChannel(), false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton);
MyServerObject = (IRemoteServer)Activator.GetObject(
typeof(IRemoteServer),
String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port));
</code></pre>
| [
{
"answer_id": 26307,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>WCF. </p>\n\n<p>I have used IPC before there was a WCF, and believe me, IPC is a bear. And it isn't documented fully/corre... | 2008/08/25 | [
"https://Stackoverflow.com/questions/25982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2373/"
] | Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it?
This is what I'm doing at the moment:
```
ChannelServices.RegisterChannel(new HttpChannel(), false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton);
MyServerObject = (IRemoteServer)Activator.GetObject(
typeof(IRemoteServer),
String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port));
``` | The first two lines are in the server-side code, for marshaling out the server object, yes?
In that case, yes, the third line is the simplest you can get at client-side.
In addition, you can serve out additional server-side objects from the **MyServerObject** instance, if you include public accessors for them in **IRemoteServer** interface, so, accessing those objects become the simple matter of method calls or property accesses on your main server object, so you don't have to use activator for every single thing:
```
//obtain another marshalbyref object of the type ISessionManager:
ISessionManager = MyServerObject.GetSessionManager();
``` |
26,007 | <p>Is there an easy way to iterate over an associative array of this structure in PHP:</p>
<p>The array <code>$searches</code> has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over <code>$searches[0]</code> through <code>$searches[n]</code>, but also <code>$searches[0]["part0"]</code> through <code>$searches[n]["partn"]</code>. The hard part is that different indexes have different numbers of parts (some might be missing one or two).</p>
<p>Thoughts on doing this in a way that's nice, neat, and understandable?</p>
| [
{
"answer_id": 26013,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 3,
"selected": false,
"text": "<p>You should be able to use a nested foreach statment</p>\n\n<p>from the <a href=\"http://uk3.php.net/foreach\" rel=\"noref... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | Is there an easy way to iterate over an associative array of this structure in PHP:
The array `$searches` has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over `$searches[0]` through `$searches[n]`, but also `$searches[0]["part0"]` through `$searches[n]["partn"]`. The hard part is that different indexes have different numbers of parts (some might be missing one or two).
Thoughts on doing this in a way that's nice, neat, and understandable? | Nest two [`foreach` loops](http://php.net/foreach):
```
foreach ($array as $i => $values) {
print "$i {\n";
foreach ($values as $key => $value) {
print " $key => $value\n";
}
print "}\n";
}
``` |
26,020 | <p>I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?</p>
| [
{
"answer_id": 26027,
"author": "robintw",
"author_id": 1912,
"author_profile": "https://Stackoverflow.com/users/1912",
"pm_score": 3,
"selected": false,
"text": "<p>There is a list of Sqlite wrappers for .Net at <a href=\"http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers\" rel=\"noref... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2674/"
] | I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#? | [Microsoft.Data.Sqlite](https://www.nuget.org/packages/Microsoft.Data.Sqlite) by Microsoft has over 9000 downloads every day, so I think you are safe using that one.
Example usage from [the documentation](https://learn.microsoft.com/dotnet/standard/data/sqlite/):
```
using (var connection = new SqliteConnection("Data Source=hello.db"))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText =
@"
SELECT name
FROM user
WHERE id = $id
";
command.Parameters.AddWithValue("$id", id);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var name = reader.GetString(0);
Console.WriteLine($"Hello, {name}!");
}
}
}
``` |
26,021 | <p>For our application, we keep large amounts of data indexed by three integer columns (source, type and time). Loading significant chunks of that data can take some time and we have implemented various measures to reduce the amount of data that has to be searched and loaded for larger queries, such as storing larger granularities for queries that don't require a high resolution (time-wise).</p>
<p>When searching for data in our backup archives, where the data is stored in bzipped text files, but has basically the same structure, I noticed that it is significantly faster to untar to stdout and pipe it through grep than to untar it to disk and grep the files. In fact, the untar-to-pipe was even noticeably faster than just grepping the uncompressed files (i. e. discounting the untar-to-disk).</p>
<p>This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. So here's my question:</p>
<p><i>Do you think putting the data of multiple rows into a (compressed) blob field of a single row and search for single rows on the fly during extraction could be faster than searching for the same rows via the table index?</i></p>
<p>For example, instead of having this table</p>
<pre><code>CREATE TABLE data ( `source` INT, `type` INT, `timestamp` INT, `value` DOUBLE);
</code></pre>
<p>I would have</p>
<pre><code>CREATE TABLE quickdata ( `source` INT, `type` INT, `day` INT, `dayvalues` BLOB );
</code></pre>
<p>with approximately 100-300 rows in data for each row in quickdata and searching for the desired timestamps on the fly during decompression and decoding of the blob field.</p>
<p>Does this make sense to you? What parameters should I investigate? What strings might be attached? What DB features (any DBMS) exist to achieve similar effects?</p>
| [
{
"answer_id": 26046,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>This made me wonder if the performance impact of disk I/O is actually much heavier than I thought.</p>\n</blo... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] | For our application, we keep large amounts of data indexed by three integer columns (source, type and time). Loading significant chunks of that data can take some time and we have implemented various measures to reduce the amount of data that has to be searched and loaded for larger queries, such as storing larger granularities for queries that don't require a high resolution (time-wise).
When searching for data in our backup archives, where the data is stored in bzipped text files, but has basically the same structure, I noticed that it is significantly faster to untar to stdout and pipe it through grep than to untar it to disk and grep the files. In fact, the untar-to-pipe was even noticeably faster than just grepping the uncompressed files (i. e. discounting the untar-to-disk).
This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. So here's my question:
*Do you think putting the data of multiple rows into a (compressed) blob field of a single row and search for single rows on the fly during extraction could be faster than searching for the same rows via the table index?*
For example, instead of having this table
```
CREATE TABLE data ( `source` INT, `type` INT, `timestamp` INT, `value` DOUBLE);
```
I would have
```
CREATE TABLE quickdata ( `source` INT, `type` INT, `day` INT, `dayvalues` BLOB );
```
with approximately 100-300 rows in data for each row in quickdata and searching for the desired timestamps on the fly during decompression and decoding of the blob field.
Does this make sense to you? What parameters should I investigate? What strings might be attached? What DB features (any DBMS) exist to achieve similar effects? | >
> This made me wonder if the performance impact of disk I/O is actually much heavier than I thought.
>
>
>
Definitely. If you have to go to disk, the performance hit is many orders of magnitude greater than memory. This reminds me of the classic Jim Gray paper, [Distributed Computing Economics](http://research.microsoft.com/research/pubs/view.aspx?tr_id=655):
>
> Computing economics are changing. Today there is rough price parity between (1) one database access, (2) ten bytes of network traffic, (3) 100,000 instructions, (4) 10 bytes of disk storage, and (5) a megabyte of disk bandwidth. This has implications for how one structures Internet-scale distributed computing: one puts computing as close to the data as possible in order to avoid expensive network traffic.
>
>
>
The question, then, is how much data do you have and how much memory can you afford?
And if the database gets *really* big -- as in nobody could ever afford that much memory, even in 20 years -- you need clever distributed database systems like Google's [BigTable](http://research.google.com/archive/bigtable.html) or [Hadoop](http://hadoop.apache.org/core/). |
26,062 | <p>I have an Access database in which I drop the table and then create the table afresh. However, I need to be able to test for the table in case the table gets dropped but not created (i.e. when someone stops the DTS package just after it starts -roll-eyes- ). If I were doing this in the SQL database I would just do:</p>
<pre><code>IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'Table-Name-to-look-for'))
BEGIN
drop table 'Table-Name-to-look-for'
END
</code></pre>
<p>But how do I do that for an Access database?</p>
<p>Optional answer: is there a way to have the DTS package ignore the error and just go to the next step rather than checking to see if it exists?</p>
<p>SQL Server 2000</p>
| [
{
"answer_id": 26045,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "<p>I would reccomend sticking to what you know - PHP is more than capable.</p>\n\n<p>I used to play a game called <a href=\"http... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] | I have an Access database in which I drop the table and then create the table afresh. However, I need to be able to test for the table in case the table gets dropped but not created (i.e. when someone stops the DTS package just after it starts -roll-eyes- ). If I were doing this in the SQL database I would just do:
```
IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'Table-Name-to-look-for'))
BEGIN
drop table 'Table-Name-to-look-for'
END
```
But how do I do that for an Access database?
Optional answer: is there a way to have the DTS package ignore the error and just go to the next step rather than checking to see if it exists?
SQL Server 2000 | >
> I would reccomend sticking to what you know - PHP is more than capable.
>
>
>
That's true of course, but:
>
> I don't mind, and I would even like to use this as an excuse, learning some new thing like Python or Ruby.
>
>
>
Then writing a browser game is an excellent opportunity to do this. Learning something new is never wrong and learning an alternative to PHP can never hurt ([eh, Jeff?](http://www.codinghorror.com/blog/archives/001119.html)). While neither Ruby on Rails nor Django are especially useful for writing games, they're still great. We had to write a small browser game in a matter of weeks for a project once and Rails worked charms. On the other hand, all successful browser games have enormous work loads and if you want to scale well you either have to get good hardware and load balancing or you need a non-interpreted framework (sorry, guys!). |