instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm looking for a library that has functionality similar to Perl's <a href="http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm#SYNOPSIS" rel="noreferrer">WWW::Mechanize</a>, but for PHP. Basically, it should allow me to submit HTTP GET and POST requests with a simple syntax, and then parse the resulting page and return in a simple format all forms and their fields, along with all links on the page.</p>
<p>I know about CURL, but it's a little too barebones, and the syntax is pretty ugly (tons of <code>curl_foo($curl_handle, ...)</code> statements</p>
<p><strong>Clarification:</strong></p>
<p>I want something more high-level than the answers so far. For example, in Perl, you could do something like:</p>
<pre><code># navigate to the main page
$mech->get( 'http://www.somesite.com/' );
# follow a link that contains the text 'download this'
$mech->follow_link( text_regex => qr/download this/i );
# submit a POST form, to log into the site
$mech->submit_form(
with_fields => {
username => 'mungo',
password => 'lost-and-alone',
}
);
# save the results as a file
$mech->save_content('somefile.zip');
</code></pre>
<p>To do the same thing using HTTP_Client or wget or CURL would be a lot of work, I'd have to manually parse the pages to find the links, find the form URL, extract all the hidden fields, and so on. The reason I'm asking for a PHP solution is that I have no experience with Perl, and I could probably build what I need with a lot of work, but it would be much quicker if I could do the above in PHP.</p>
|
<p>SimpleTest's <a href="http://simpletest.sourceforge.net/en/browser_documentation.html" rel="nofollow noreferrer">ScriptableBrowser</a> can be used independendly from the testing framework. I've used it for numerous automation-jobs.</p>
|
<p>If you're on a *nix system you could use shell_exec() with wget, which has a lot of nice options.</p>
| 24,260
|
<p>I'm working on a site which contains a whole bunch of mp3s and images, and I'd like to display a loading gif while all the content loads. </p>
<p>I have no idea how to achieve this, but I do have the animated gif I want to use. </p>
<p>Any suggestions?</p>
|
<p>Typically sites that do this by loading content via ajax and listening to the <code>readystatechanged</code> event to update the DOM with a loading GIF or the content.</p>
<p>How are you currently loading your content?</p>
<p>The code would be similar to this:</p>
<pre class="lang-js prettyprint-override"><code>function load(url) {
// display loading image here...
document.getElementById('loadingImg').visible = true;
// request your data...
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
// content is loaded...hide the gif and display the content...
if (req.responseText) {
document.getElementById('content').innerHTML = req.responseText;
document.getElementById('loadingImg').visible = false;
}
}
};
request.send(vars);
}
</code></pre>
<p>There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.</p>
|
<p>You can use <code><progress></code> element in HTML5. See this page for source code and live demo. <a href="http://purpledesign.in/blog/super-cool-loading-bar-html5/" rel="nofollow">http://purpledesign.in/blog/super-cool-loading-bar-html5/</a></p>
<p>here is the progress element...</p>
<pre><code><progress id="progressbar" value="20" max="100"></progress>
</code></pre>
<p>this will have the loading value starting from 20. Of course only the element wont suffice. You need to move it as the script loads. For that we need JQuery. Here is a simple JQuery script that starts the progress from 0 to 100 and does something in defined time slot.</p>
<pre><code><script>
$(document).ready(function() {
if(!Modernizr.meter){
alert('Sorry your brower does not support HTML5 progress bar');
} else {
var progressbar = $('#progressbar'),
max = progressbar.attr('max'),
time = (1000/max)*10,
value = progressbar.val();
var loading = function() {
value += 1;
addValue = progressbar.val(value);
$('.progress-value').html(value + '%');
if (value == max) {
clearInterval(animate);
//Do Something
}
if (value == 16) {
//Do something
}
if (value == 38) {
//Do something
}
if (value == 55) {
//Do something
}
if (value == 72) {
//Do something
}
if (value == 1) {
//Do something
}
if (value == 86) {
//Do something
}
};
var animate = setInterval(function() {
loading();
}, time);
};
});
</script>
</code></pre>
<p>Add this to your HTML file.</p>
<pre><code><div class="demo-wrapper html5-progress-bar">
<div class="progress-bar-wrapper">
<progress id="progressbar" value="0" max="100"></progress>
<span class="progress-value">0%</span>
</div>
</div>
</code></pre>
<p>Hope this will give you a start.</p>
| 30,270
|
<p>I am opening a new window from a button using var myWindow = window.open(...). I then want to move that window to the correct location on the screen. I use myWindow.moveTo(10,10) to do this but I get an Access Denied error.</p>
<p>The window I open contains information from another server to the one I am executing on. When it isn't, the window moves correctly. Is this the limitation and is there a way around it?</p>
<p>I am using IE7. (The work is for an existing Intranet that includes lots of ActiveX so all users use IE7)</p>
|
<p>You could try to put the information from the other site in an iframe located on the same host that runs the window.open JavaScript. Or maybe even better, get the information server-side and present it directly from your site. Iframes can be trouble.</p>
|
<blockquote>
<p>The window I open contains information from another server to the one I am executing on. When it isn't, the window moves correctly. Is this the limitation and is there a way around it?</p>
</blockquote>
<p>Browsers security model have been increasingly restrictive over the last couple of years. What you could do a few years ago, isn't allowed any more. Blame it on advertising companies.</p>
| 46,818
|
<p>I have a type (System.Type) of an enum and a string containing enumeration value to set.</p>
<p>E.g. given: </p>
<pre><code>enum MyEnum { A, B, C };
</code></pre>
<p>I have typeof(MyEnum) and "B".</p>
<p>How do I create MyEnum object set to MyEnum.B?</p>
|
<pre><code>MyEnum enumValue = (MyEnum)Enum.Parse(typeof(MyEnum), "B");
</code></pre>
<p>You also have a case-insensitive overload.</p>
|
<p>You can do this with generics. I created a Utility class to wrap this:</p>
<pre><code>public static class Utils {
public static T ParseEnum<T>(string value) {
return (T)Enum.Parse(typeof(T), value, true);
}
</code></pre>
<p>Then invoked like:</p>
<pre><code>string s = "B";
MyEnum enumValue = Utils.ParseEnum<MyEnum>(s);
</code></pre>
| 20,410
|
<p>Given an arbitrary sequence of points in space, how would you produce a smooth continuous interpolation between them?</p>
<p>2D and 3D solutions are welcome. Solutions that produce a list of points at arbitrary granularity and solutions that produce control points for bezier curves are also appreciated.</p>
<p>Also, it would be cool to see an iterative solution that could approximate early sections of the curve as it received the points, so you could draw with it.</p>
|
<p>The <a href="http://en.wikipedia.org/wiki/Catmull-Rom_spline#Catmull.E2.80.93Rom_spline" rel="noreferrer">Catmull-Rom spline</a> is guaranteed to pass through all the control points. I find this to be handier than trying to adjust intermediate control points for other types of splines.</p>
<p>This <a href="http://www.cs.cmu.edu/~fp/courses/graphics/asst5/catmullRom.pdf" rel="noreferrer">PDF by Christopher Twigg</a> has a nice brief introduction to the mathematics of the spline. The best summary sentence is:</p>
<blockquote>
<p>Catmull-Rom splines have C1
continuity, local control, and
interpolation, but do not lie within
the convex hull of their control
points.</p>
</blockquote>
<p>Said another way, if the points indicate a sharp bend to the right, the spline will bank left before turning to the right (there's an example picture in that document). The tightness of those turns in controllable, in this case using his tau parameter in the example matrix.</p>
<p>Here is <a href="http://www.mvps.org/directx/articles/catmull/" rel="noreferrer">another example</a> with some downloadable DirectX code. </p>
|
<p>Google "orthogonal regression". </p>
<p>Whereas least-squares techniques try to minimize vertical distance between the fit line and each f(x), orthogonal regression minimizes the perpendicular distances.</p>
<p><strong>Addendum</strong></p>
<p>In the presence of noisy data, the venerable <a href="http://en.wikipedia.org/wiki/RANSAC" rel="nofollow noreferrer">RANSAC</a> algorithm is worth checking out too. </p>
| 13,303
|
<p>Is there an easy way to generate an array containing the letters of the alphabet in C#? It's not too hard to do it by hand, but I was wondering if there was a built in way to do this. </p>
|
<p>I don't think there is a built in way, but I think the easiest would be </p>
<pre><code> char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
</code></pre>
|
<pre><code>char alphaStart = Char.Parse("A");
char alphaEnd = Char.Parse("Z");
for(char i = alphaStart; i <= alphaEnd; i++) {
string anchorLetter = i.ToString();
}
</code></pre>
| 40,575
|
<p>I have 4 2D points in screen-space, and I need to reverse-project them back into 3D space. I know that each of the 4 points is a corner of a 3D-rotated rigid rectangle, and I know the size of the rectangle. How can I get 3D coordinates from this?</p>
<p>I am not using any particular API, and I do not have an existing projection matrix. I'm just looking for basic math to do this. Of course there isn't enough data to convert a single 2D point to 3D with no other reference, but I imagine that if you have 4 points, you know that they're all at right-angles to each other on the same plane, and you know the distance between them, you should be able to figure it out from there. Unfortunately I can't quite work out how though.</p>
<p>This might fall under the umbrella of photogrammetry, but google searches for that haven't led me to any helpful information. </p>
|
<p>Alright, I came here looking for an answer and didn't find something simple and straightforward, so I went ahead and did the dumb but effective (and relatively simple) thing: Monte Carlo optimisation.</p>
<p>Very simply put, the algorithm is as follows: Randomly perturb your projection matrix until it projects your known 3D coordinates to your known 2D coordinates.</p>
<p>Here is a still photo from Thomas the Tank Engine:</p>
<p><a href="https://i.stack.imgur.com/YUhsm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YUhsm.png" alt="Thomas the Tank Engine"></a></p>
<p>Let's say we use GIMP to find the 2D coordinates of what we think is a square on the ground plane (whether or not it is really a square depends on your judgment of the depth):</p>
<p><a href="https://i.stack.imgur.com/u8nKF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/u8nKF.png" alt="With an outline of the square"></a></p>
<p>I get four points in the 2D image: <code>(318, 247)</code>, <code>(326, 312)</code>, <code>(418, 241)</code>, and <code>(452, 303)</code>.</p>
<p>By convention, we say that these points should correspond to the 3D points: <code>(0, 0, 0)</code>, <code>(0, 0, 1)</code>, <code>(1, 0, 0)</code>, and <code>(1, 0, 1)</code>. In other words, a unit square in the y=0 plane.</p>
<p>Projecting each of these 3D coordinates into 2D is done by multiplying the 4D vector <code>[x, y, z, 1]</code> with a 4x4 projection matrix, then dividing the x and y components by z to actually get the perspective correction. This is more or less what <a href="https://www.opengl.org/sdk/docs/man2/xhtml/gluProject.xml" rel="noreferrer">gluProject()</a> does, except <code>gluProject()</code> also takes the current viewport into account and takes a separate modelview matrix into account (we can just assume the modelview matrix is the identity matrix). It is very handy to look at the <code>gluProject()</code> documentation because I actually want a solution that works for OpenGL, but beware that the documentation is missing the division by z in the formula.</p>
<p>Remember, the algorithm is to start with some projection matrix and randomly perturb it until it gives the projection that we want. So what we're going to do is project each of the four 3D points and see how close we get to the 2D points we wanted. If our random perturbations cause the projected 2D points to get closer to the ones we marked above, then we keep that matrix as an improvement over our initial (or previous) guess.</p>
<p>Let's define our points:</p>
<pre><code># Known 2D coordinates of our rectangle
i0 = Point2(318, 247)
i1 = Point2(326, 312)
i2 = Point2(418, 241)
i3 = Point2(452, 303)
# 3D coordinates corresponding to i0, i1, i2, i3
r0 = Point3(0, 0, 0)
r1 = Point3(0, 0, 1)
r2 = Point3(1, 0, 0)
r3 = Point3(1, 0, 1)
</code></pre>
<p>We need to start with some matrix, identity matrix seems a natural choice:</p>
<pre><code>mat = [
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
]
</code></pre>
<p>We need to actually implement the projection (which is basically a matrix multiplication):</p>
<pre><code>def project(p, mat):
x = mat[0][0] * p.x + mat[0][1] * p.y + mat[0][2] * p.z + mat[0][3] * 1
y = mat[1][0] * p.x + mat[1][1] * p.y + mat[1][2] * p.z + mat[1][3] * 1
w = mat[3][0] * p.x + mat[3][1] * p.y + mat[3][2] * p.z + mat[3][3] * 1
return Point(720 * (x / w + 1) / 2., 576 - 576 * (y / w + 1) / 2.)
</code></pre>
<p>This is basically what <code>gluProject()</code> does, 720 and 576 are the width and height of the image, respectively (i.e. the viewport), and we subtract from 576 to count for the fact that we counted y coordinates from the top while OpenGL typically counts them from the bottom. You'll notice we're not calculating z, that's because we don't really need it here (though it could be handy to ensure it falls within the range that OpenGL uses for the depth buffer).</p>
<p>Now we need a function for evaluating how close we are to the correct solution. The value returned by this function is what we will use to check whether one matrix is better than another. I chose to go by sum of squared distances, i.e.:</p>
<pre><code># The squared distance between two points a and b
def norm2(a, b):
dx = b.x - a.x
dy = b.y - a.y
return dx * dx + dy * dy
def evaluate(mat):
c0 = project(r0, mat)
c1 = project(r1, mat)
c2 = project(r2, mat)
c3 = project(r3, mat)
return norm2(i0, c0) + norm2(i1, c1) + norm2(i2, c2) + norm2(i3, c3)
</code></pre>
<p>To perturb the matrix, we simply pick an element to perturb by a random amount within some range:</p>
<pre><code>def perturb(amount):
from copy import deepcopy
from random import randrange, uniform
mat2 = deepcopy(mat)
mat2[randrange(4)][randrange(4)] += uniform(-amount, amount)
</code></pre>
<p>(It's worth noting that our <code>project()</code> function doesn't actually use <code>mat[2]</code> at all, since we don't compute z, and since all our y coordinates are 0 the <code>mat[*][1]</code> values are irrelevant as well. We could use this fact and never try to perturb those values, which would give a small speedup, but that is left as an exercise...)</p>
<p>For convenience, let's add a function that does the bulk of the approximation by calling <code>perturb()</code> over and over again on what is the best matrix we've found so far:</p>
<pre><code>def approximate(mat, amount, n=100000):
est = evaluate(mat)
for i in xrange(n):
mat2 = perturb(mat, amount)
est2 = evaluate(mat2)
if est2 < est:
mat = mat2
est = est2
return mat, est
</code></pre>
<p>Now all that's left to do is to run it...:</p>
<pre><code>for i in xrange(100):
mat = approximate(mat, 1)
mat = approximate(mat, .1)
</code></pre>
<p>I find this already gives a pretty accurate answer. After running for a while, the matrix I found was:</p>
<pre><code>[
[1.0836000765696232, 0, 0.16272110011060575, -0.44811064935115597],
[0.09339193527789781, 1, -0.7990570384334473, 0.539087345090207 ],
[0, 0, 1, 0 ],
[0.06700844759602216, 0, -0.8333379578853196, 3.875290562060915 ],
]
</code></pre>
<p>with an error of around <code>2.6e-5</code>. (Notice how the elements we said were not used in the computation have not actually been changed from our initial matrix; that's because changing these entries would not change the result of the evaluation and so the change would never get carried along.)</p>
<p>We can pass the matrix into OpenGL using <code>glLoadMatrix()</code> (but remember to transpose it first, and remember to load your modelview matrix with the identity matrix):</p>
<pre><code>def transpose(m):
return [
[m[0][0], m[1][0], m[2][0], m[3][0]],
[m[0][1], m[1][1], m[2][1], m[3][1]],
[m[0][2], m[1][2], m[2][2], m[3][2]],
[m[0][3], m[1][3], m[2][3], m[3][3]],
]
glLoadMatrixf(transpose(mat))
</code></pre>
<p>Now we can for example translate along the z axis to get different positions along the tracks:</p>
<pre><code>glTranslate(0, 0, frame)
frame = frame + 1
glBegin(GL_QUADS)
glVertex3f(0, 0, 0)
glVertex3f(0, 0, 1)
glVertex3f(1, 0, 1)
glVertex3f(1, 0, 0)
glEnd()
</code></pre>
<p><a href="https://i.stack.imgur.com/dfeEx.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/dfeEx.gif" alt="With 3D translation"></a></p>
<p>For sure this is not very elegant from a mathematical point of view; you don't get a closed form equation that you can just plug your numbers into and get a direct (and accurate) answer. HOWEVER, it does allow you to add additional constraints without having to worry about complicating your equations; for example if we wanted to incorporate height as well, we could use that corner of the house and say (in our evaluation function) that the distance from the ground to the roof should be so-and-so, and run the algorithm again. So yes, it's a brute force of sorts, but works, and works well.</p>
<p><a href="https://i.stack.imgur.com/smdR8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/smdR8.png" alt="Choo choo!"></a></p>
|
<p>Yes, Monte Carlo works, but I found better solution for this issue. This code works perfectly (and uses OpenCV):</p>
<pre><code>Cv2.CalibrateCamera(new List<List<Point3f>>() { points3d }, new List<List<Point2f>>() { points2d }, new Size(height, width), cameraMatrix, distCoefs, out rvecs, out tvecs, CalibrationFlags.ZeroTangentDist | CalibrationFlags.FixK1 | CalibrationFlags.FixK2 | CalibrationFlags.FixK3);
</code></pre>
<p>This function takes known 3d and 2d points, size of screen and returns rotation (rvecs[0]), translation (tvecs[0]) and matrix of intrinsics values of camera. It's everything you need.</p>
| 10,174
|
<p>I'm experimenting with OpenSSL on my network application and I want to test if the data sent is encrypted and can't be seen by eavesdropper.</p>
<p>What tools can you use to check? Could this be done programmatically so it could be placed in a unit test?</p>
|
<p>check out wire shark <a href="http://www.wireshark.org/" rel="noreferrer">http://www.wireshark.org/</a></p>
<p>and tcp dump <a href="http://en.wikipedia.org/wiki/Tcpdump" rel="noreferrer">http://en.wikipedia.org/wiki/Tcpdump</a></p>
<p>Not sure about integrating these into unit tests. They will let you look at a very low level whats going on at the network level. </p>
<p>Perhaps for the unit test determine what the stream looks like unencrypted and make sure the encrypted stream is not similar</p>
|
<p>For a quick check you can use <a href="http://www.wireshark.org/" rel="nofollow noreferrer">Wireshark</a> (formerly known as Ethereal) to see if your data is transmitted in plain-text or not.</p>
| 17,837
|
<p>At work, I use Cygwin a lot because it offers me a small oasis in the vast desert of Windows. I inevitably end up running some non-Cygwin programs through the bash shell, such as build scripts (batch files created in-house) and the Subversion CLI binaries (I have the Windows ones installed). 99% of the time, I don't have any problems using this setup. The other 1%, however, causes a strange issue:</p>
<p>With both the build scripts and SVN, most of the time the enter key is interpreted correctly. For instance, I'll kick off the database creation script and it will prompt me for the server name. I type in "localhost" and hit enter. Everything's fine. Then it gets to the end, if there are errors, and prints things out using <code>more</code>. No key that I press is recognized by <code>more</code>. I have to Ctrl-C out of it.</p>
<p>Similarly, if I do a Subversion update, normally everything is fine. In the case where the interactive conflict resolution happens, however, I'll usually type in "tf" for "theirs-full" and hit enter, but nothing happens. I have to Ctrl-C out of it and re-run the update with force merge or use TortoiseSVN in Windows to do it.</p>
<p>Any idea why Cygwin seems to randomly not be passing the enter key through to the programs? I considered that it may have something to do with Unix vs Windows style line endings, so I've tried typing those characters manually, but that doesn't seem to make a difference. Thanks.</p>
<p><strong>Edit</strong>: I just had this happen to me again and I realized something. It was SVN prompting me for a password. I typed in the password, which it echoed to the screen (bad) and hit enter... nothing. Hit enter a few more times, the cursor moves, but nothing happens. I hit Ctrl-C and it dumps me back to bash, which then says "bash: [my password]: command not found" followed by a number of new prompts equal to the number of times I hit the enter key. So what happened is the input never made it to SVN, but somehow got read by bash after SVN exited. I thought that may help someone figure out what is going on.</p>
|
<p>Unfortunately, I think you are hitting one of the issues of Cygwin and windows/dos console apps. See "Console Programs" at <a href="http://www.cygwin.com/cygwin-ug-net/using-effectively.html" rel="noreferrer">http://www.cygwin.com/cygwin-ug-net/using-effectively.html</a>.</p>
<p>It is just a limitation on windows console apps. This behavior is common for the windows myqsl cmd client and svn client, for example.</p>
<p>Here are some things to note -- I've successfully used this approach with both the Windows mysql as well as Windows svn clients:</p>
<p>1) Try making sure you do NOT have "tty" in your CYGWIN environment variable and see if that helps (unset it in My Computer->properties->advanced->Environment Variables and close/restart any cygwin bash prompts).</p>
<p>2) Do not use RXVT -- instead, use the basic Cygwin cmd prompt. This is because RXVT implies "tty" and will break #1 above.</p>
<p>3) Try finding a "native" Cygwin package for the cmds you are having issues with instead of using the Windows cmds. (I haven't found a 1.6 svn client for cygwin yet, though.)</p>
<p>Good luck!
Dustin</p>
|
<p>The lengthy discussion on the mintty project is here - <a href="http://code.google.com/p/mintty/issues/detail?id=56" rel="nofollow">http://code.google.com/p/mintty/issues/detail?id=56</a></p>
<p>One solution mentioned which worked in my case (entering authentication passwords for native subversion) is <strong>conin</strong> - <a href="http://code.google.com/p/mintty/downloads/detail?name=conin-0.0.2.zip&can=1&q=label%3ADevelopment" rel="nofollow">http://code.google.com/p/mintty/downloads/detail?name=conin-0.0.2.zip&can=1&q=label%3ADevelopment</a></p>
<pre><code>$ conin svn list https://{repo}
Password for 'user': ******
</code></pre>
| 24,747
|
<p>Is there some way I can use URLs like: </p>
<p><em><a href="http://www.blog.com/team-spirit/" rel="nofollow noreferrer">http://www.blog.com/team-spirit/</a></em></p>
<p>instead of</p>
<p><em><a href="http://www.blog.com/?p=122" rel="nofollow noreferrer">http://www.blog.com/?p=122</a></em></p>
<p>in a Windows hosted PHP server?</p>
|
<p>This is how I did it with WordPress on IIS 6.0</p>
<p><a href="http://www.coderjournal.com/2008/02/url-rewriter-reverse-proxy-iis-wordpress/" rel="nofollow noreferrer">http://www.coderjournal.com/2008/02/url-rewriter-reverse-proxy-iis-wordpress/</a></p>
<p>However it all depends on what version of IIS you are using. If you are lucky enough to use IIS 7.0 you don't really have to worry about pretty urls because everything is supported out of the box. However if you are using IIS 6.0 you are going to have to use a rewriter and some rules to force the IISness out of IIS.</p>
|
<p>We use the free version of <a href="http://www.isapirewrite.com/" rel="nofollow noreferrer">ISAPI_Rewrite</a>. It uses similar syntax to mod_rewrite, so if you're familiar with that you may have an easier time getting started.</p>
<p>There used to be a (syntax-compatible) port of mod_rewrite for IIS, but I can't find it now.</p>
| 5,252
|
<p>Is there any tool that can parse a valid <strong>C</strong> program and generate a report which contains list of <em>functions</em>, <em>global variables</em>, <em><code>#define</code> constants</em>, <em>local variables in each function</em>, etc.</p>
|
<p>Doxygen does all of the above.</p>
|
<p>Try exuberant-ctags with the -x option and tell it to generate all of its kinds.
Exuberant CTAGS is the default ctags on many linux distros.</p>
<p>You might try: exuberant-ctags -x --c-kinds=cdefglmnpstuvx --language-force=c filename</p>
<p>will even work if filename doesn't have .c extension.</p>
<p>You can use exuberant-ctags --list-kinds=c to see the possible tags.</p>
<p>Under windows, the cygwin environment supports ctags. I'm not sure if there's a windows build that doesn't need cygwin.</p>
| 10,985
|
<p>Are there any good source-code analyses tools for OSX. I am particularly interested in tools that are capable of diagramming function-call hierarchies for C and C++ source files.</p>
|
<p>You might take a look at <a href="http://www.doxygen.nl/" rel="nofollow noreferrer">doxygen</a></p>
|
<p><a href="http://www.doxygen.nl/" rel="nofollow noreferrer">doxygen</a> can do this and a lot more.</p>
| 33,552
|
<p>My Google-fu is failing me on this question.</p>
<p>I have a coworker who has Visual Studio 2005 on his machine. I have Visual Studio 2008. He wants to open a project I wrote in C# 3.0, and we've gotten that far, but VS2005 barfs on the 3.0 code, like <code>var</code>.</p>
<p>He has the 3.0 and 3.5 frameworks installed, as well as the Visual Studio 2005 Extensions for Windows Workflow. What else does he need? Or are we pursuing a lost cause, a wild goose chase spurred by my thinking that I heard this was possible somewhere one time?</p>
<p>Please don't suggest he install VS2008 or the Express edition. That simply isn't possible at this time. :(</p>
|
<p>So far as I understand it, this isn't possible. If you weren't using the new C# 3.0 code features, he should be able to work with a project created in VS2008 (and compile it against the 2.0 framework), but I don't think the 2005 compiler is ever going to be able to cope with the new syntax.</p>
|
<p>The IDE itself may not support the 3.0 functionality. If you can live without the 3.0 features you can compile to 2.0 which he should be able to run ok.</p>
| 15,026
|
<p>I've got a C# program that's supposed to play audio files. I've figured out how to play any sound file for which Windows has a codec by using DirectShow, but now I want to properly fill in the file type filter box on the Open dialog. I'd like to automatically list any file format for which Windows has a codec. If some random user installs a codec for an obscure format, its associated extension(s) and file type description(s) need to show up in the list.</p>
<p>Any ideas?</p>
|
<p>If I remember correctly, a codec does not know which file types, i.e. file extensions, it supports, since a codec takes some stream as input and not actually a file. So if what you want is to display the file extensions of the supported audio file formats, you'll most likely be out of luck unless you have a extensive list of file extensions and associated codecs, but even then you'll get problems with container formats and all that.</p>
<p>For example, my Windows Media Player happily plays m4b files, but does not know anything about them. I had to manually associate it with the file type.</p>
|
<p>You could look in the Windows Registry for all file types with a content type of "audio/*". Specifically, look at all of the keys under HKCR/Software/*/Content Type.</p>
| 18,139
|
<p>So if you have a RIA version (Silverlight or Flash) and a standard HTML version (or AJAX even), should you have the same URL for both, or is it ok to have a different one for the RIA app and just redirect accordingly?</p>
<p>So, for instance, if you have a site (<a href="http://example.com" rel="nofollow noreferrer">http://example.com</a>), is it ok to have the about page URL for the RIA app be <a href="http://example.com/#/about" rel="nofollow noreferrer">http://example.com/#/about</a> and the html be <a href="http://example.com/about" rel="nofollow noreferrer">http://example.com/about</a>? Does it matter? </p>
<p>Of course if you take the route with different URLs you will need to map between them. </p>
|
<p>The URLs of your pages denote the identity of the content. In my view, if the content is the same but the presentation varies (i.e RIA vs. HTML), then the URL should be the same and you should use some other mechanism to select between the different presentation forms. Choices of other mechanisms include cookies, content negotiation, session identifiers or, if your users are identified, a persistent user preferences model. Even using a URL argument would at least keep the root of the URL consistent (e.g. <code>http://your.si.te/foobar</code> vs. <code>http://your.si.te/foobar?view=plain</code>)</p>
<p>If the content of the two presentations differs in some meaningful way, then you should make that difference meaningful in the URL. Exploiting the presence or absence of #, and other such hacks, would be a mistake in my view.</p>
<p>Try to pick URL's that do not change over time: so-called <a href="http://www.w3.org/Provider/Style/URI" rel="nofollow noreferrer" title="cool URL's">cool URL's</a>. This will aide the long-term usefulness of your site to your users: consider what happens if they come back to a bookmarked page in a year's time. Consistency will also help you to get a better critical mass of links or reviews of your site in <a href="http://del.icio.us" rel="nofollow noreferrer">del.icio.us</a> and similar bookmarking/review sites.</p>
<p>Ian</p>
|
<p>I guess what I really need here is not a Question/Answer format but some kind of poll. While I agree (and accepted) that because they are getting two different views of the same content, that different urls are ok, but I'm thinking more of sharing these urls out. </p>
<p>Thanks for the reply though!</p>
| 10,292
|
<p>The sample below has two TextBoxes. The second TextBox has a handler for the LostFocus event which calls Clear() on itself. Changing focus between the two text boxes works fine; however, if the focus is on the second text box when the window is closed, TextBox.Clear() generates a NullReferenceException. Is this a bug in WPF? How can I easily detect this situation so I can avoid calling Clear() when the window is closing?</p>
<p>Edit: Possibly relevant - The window is the application's main window. Test is not null at the time Clear() is called. The exception is thrown from somewhere within the call.</p>
<pre><code>using System.Windows;
namespace TextBoxClear
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Test_LostFocus(object sender, RoutedEventArgs e)
{
Test.Clear();
}
}
}
<Window x:Class="TextBoxClear.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<TextBox />
<TextBox LostFocus="Test_LostFocus" Name="Test" />
</StackPanel>
</Window>
</code></pre>
<p>Assembly references:</p>
<ul>
<li>mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</li>
<li>PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li>
<li>PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li>
<li>System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</li>
<li>WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li>
</ul>
|
<p>Could the Test property be null by the time the LostFocus event is fired?</p>
<p>Try:</p>
<pre><code> private void Test_LostFocus(object sender, RoutedEventArgs e)
{
if (Test != null)
Test.Clear();
}
</code></pre>
<p><strong>EDIT:</strong> I'm having trouble reproducing the NullReferenceException with the code you posted. Which version of .NET are you using?</p>
|
<p>Hooking LostKeyboardFocus instead of LostFocus works OK for my situation and stops the event handler throwing exceptions.</p>
| 18,898
|
<p>I just order myself an Ender 3 Pro which will come by the end of the week.
Before it arrives I want to be ready to flash a bootloader onto it.</p>
<p>I was wondering what other options there are to flashing except using an Arduino?</p>
<p>I have a bunch of ESP8266/ESP32 and a <a href="https://www.banggood.com/FT232RL-FTDI-USB-To-TTL-Serial-Converter-Adapter-Module-For-Arduino-p-917226.html?rmmds=myorder&cur_warehouse=CN" rel="nofollow noreferrer">USB to TTL</a>. Would it be possible to use these somehow instead of an Arduino to flash a bootloader to the Ender 3?
Or should I just go buy an Arduino?</p>
|
<p>What you need to is called a ICSP or ISP: <a href="https://en.wikipedia.org/wiki/In-system_programming" rel="noreferrer">in-circuit serial programmer or in-system programmer</a>, which excludes the USB to TTL device you own.</p>
<p>I've never used an ESP8266 as ICSP but it seems there are <a href="https://arduino.stackexchange.com/questions/44702/esp8266-as-isp-program-for-atmega16">some resources out there</a> reporting it is possible.
If you want to go the easiest way probably you want to buy an Arduino and follow the tons of tutorials out there, if you are looking to save some money then you might get around buying an ICSP like the very well known USBASP (just Google for that).</p>
|
<p>You can do AVR programming using USB-TTL adapters. This relies on bit-banging, i.e. emulating the programming protocol by using the serial control lines as general purpose IO.</p>
<p>But this has a few caveats:</p>
<ul>
<li>USB-TTL adapters limit the speed of control line changes. So the programming will be very slow, taking several minutes.</li>
<li>You need to have the RTS, DTR and CTS lines available on the USB-TTL adapter. Many of the cheap adapters do not have these signals available on pins, though you could solder to the chip directly.</li>
</ul>
<p>If those two are in order, go ahead and install <a href="https://www.nongnu.org/avrdude/" rel="nofollow noreferrer">avrdude</a>, take one of the serial port bitbang (<code>serbb</code> driver) example files and configure it with information on which serial adapter pins you've connected to the AVR chip. Then give <code>-i 1000</code> or similar delay value to <code>avrdude</code> to slow it down enough to work over the USB interface.</p>
<p>There is <a href="http://nerdralph.blogspot.com/2014/05/pl-2303hx-bit-bang-avr-programmer.html" rel="nofollow noreferrer">a blog post about doing it with PL2303 based adapter</a>, but the technique should work on other USB-TTL adapters also.</p>
| 1,508
|
<p>I want to use a "spin button control" (also known as an up-down control) in my Delphi Win 32 application (I'm using Delphi 2007). </p>
<p>The aim is to have a control that looks like in Microsoft Office:</p>
<p><a href="http://img167.imageshack.us/my.php?image=updownzn8.png" rel="nofollow noreferrer">image of up/down control in Powerpoint. http://img167.imageshack.us/my.php?image=updownzn8.png</a></p>
<p>I found this on the Microsoft website: <a href="http://msdn.microsoft.com/de-de/library/sfac27cz(VS.80).aspx" rel="nofollow noreferrer">CSpinButtonCtrl Class</a></p>
<p>But I haven't so far found a control that uses this class - here's where I've been searching:</p>
<ul>
<li>The SpinEdit control in Delphi looks well... not so good, and doesn't seem to use the official Microsoft control</li>
<li>The JVCL classes have their own implementation</li>
<li>A Google search did not return any results (except some home-brew up/down controls)</li>
<li>I couldn't find something in the Jedi API as well</li>
</ul>
<p>Can somebody please point me to where I can find a Delphi implementation of the common spin control from Microsoft, or how I can do that myself?</p>
|
<p>Have a look at TUpDown. It wraps the Win32 control.</p>
|
<p><a href="http://tmssoftware.com" rel="nofollow noreferrer">TMS Software</a> do a wide range of components including spin edits (fancy an iPhone style one!) and I have found their support through the newsgroups to be excellent.</p>
| 39,140
|
<p>I currently work for a bespoke software agency. Does anyone have any experience of how to win well priced work?</p>
<p>It seems there is so much competition from offshore/bedroom programming teams, that cost is extremely competetive these days. I feel that it is very different compared to a software product company or an internal IT department in terms of budget.</p>
<p>As someone else said before, we only ever really get to version 1.0 of a lot of our software, unless the client is big enough. In this case it doesn't make business sense to spend ages making the software the best we can. It's like we are doing the same quality of work as internal IT staff. Also a lot of our clients are not technically minded and so therefore will not pay for things they don't understand.</p>
<p>As our company does not have the money to turn down work it often goes that we take on complicated work for far too little money. I have gotten a lot better at managing change and keeping tight specs, etc. It is still hard.</p>
<p>Edit-----------------------</p>
<p>Almost 3 years on from this post and I can list some important lessons that I have learnt since then.</p>
<p>Please see below for my answer</p>
|
<p>If you are concerned with doing too much work for too little money then work on an hourly basis. Yes, that is harder to sell in most situations.</p>
<p>Maybe you can try a two-phased approach instead. Have a very short initial engagement where the deliverables are very specific requirements documents that become the property of the client. You risk having to compete for the actual development but you take away the risk of pricing the project too low because you will already understand what the client is like to work with, as well as, the application requirements.</p>
<p>Once you win the work at a fair price then use the best practices suggested by mathieu to help ensure quality and productivity which both lower the cost you incur.</p>
|
<p>Sell fixed price, fixed scope work, not hourly work. That mitigates your customer's risk of an over-run (you absorb all the risk, but you're doing that anyway), and frames the project in terms of the value of the software, not the quality of the effort going into it.</p>
| 25,046
|
<p>I would like to replace only the group in parenthesis in this expression :</p>
<pre><code>my_string.gsub(/<--MARKER_START-->(.)*<--MARKER_END-->/, 'replace_text')
</code></pre>
<p>so that I get : <code><--MARKER_START-->replace_text<--MARKER_END--></code></p>
<p>I know I could repeat the whole <code>MARKER_START</code> and <code>MARKER_END</code> blocks in the substitution expression but I thought there should be a more simple way to do this.</p>
|
<p>You could do something like this:</p>
<pre><code>my_string.gsub(/(<--MARKER_START-->)(.*)(<--MARKER_END-->)/, '\1replace_text\3')
</code></pre>
|
<p>You can do it with <a href="http://www.perlmonks.org/?node_id=518444" rel="nofollow noreferrer">zero width look-ahead and look-behind assertions</a>.</p>
<p>This regex should work in ruby 1.9 and in perl and many other places:</p>
<p><em>Note: ruby 1.8 only supports look-ahead assertions. You need both look-ahead and look-behind to do this properly.</em></p>
<pre><code> s.gsub( /(?<=<--MARKER START-->).*?(?=<--MARKER END-->)/, 'replacement text' )
</code></pre>
<p>What happens in ruby 1.8 is the <code>?<=</code> causes it to crash because it doesn't understand the look-behind assertion. For that part, you then have to fall back to using a backreference - like <a href="https://stackoverflow.com/questions/118839/gsub-partial-replace#118852">Greig Hewgill mentions</a></p>
<p>so what you get is</p>
<pre><code> s.gsub( /(<--MARKER START-->).*?(?=<--MARKER END-->)/, '\1replacement text' )
</code></pre>
<h3>EXPLANATION THE FIRST:</h3>
<p>I've replaced the <code>(.)*</code> in the middle of your regex with <code>.*?</code> - this is non-greedy.
If you don't have non-greedy, then your regex will try and match as much as it can - if you have 2 markers on one line, it goes wrong. This is best illustrated by example:</p>
<pre><code>"<b>One</b> Two <b>Three</b>".gsub( /<b>.*<\/b>/, 'BOLD' )
=> "BOLD"
</code></pre>
<p>What we actually want:</p>
<pre><code>"<b>One</b> Two <b>Three</b>".gsub( /<b>.*?<\/b>/, 'BOLD' )
=> "BOLD Two BOLD"
</code></pre>
<h3>EXPLANATION THE SECOND:</h3>
<p>zero-width-look-ahead-assertion sounds like a giant pile of nerdly confusion.</p>
<p>What "look-ahead-assertion" actually means is "Only match, if the thing we are looking for, is followed by this other stuff.</p>
<p>For example, only match a digit, if it is followed by an F.</p>
<pre><code>"123F" =~ /\d(?=F)/ # will match the 3, but not the 1 or the 2
</code></pre>
<p>What "zero width" actually means is "consider the 'followed by' in our search, but don't count it as part of the match when doing replacement or grouping or things like that.
Using the same example of 123F, If we didn't use the lookahead assertion, and instead just do this:</p>
<pre><code>"123F" =~ /\dF/ # will match 3F, because F is considered part of the match
</code></pre>
<p>As you can see, this is ideal for checking for our <code><--MARKER END--></code>, but what we need for the <code><--MARKER START--></code> is the ability to say "Only match, if the thing we are looking for FOLLOWS this other stuff". That's called a look-behind assertion, which ruby 1.8 doesn't have for some strange reason..</p>
<p>Hope that makes sense :-)</p>
<p>PS: Why use lookahead assertions instead of just backreferences? If you use lookahead, you're not actually replacing the <code><--MARKER--></code> bits, only the contents. If you use backreferences, you are replacing the whole lot. I don't know if this incurs much of a performance hit, but from a programming point of view it seems like the right thing to do, as we don't actually want to be replacing the markers at all.</p>
| 14,463
|
<p>There is a similar question going around, but it just got the same old answers that people always give about Regex syntax, but that's not the point here, so please try to not knee jerk the same old answers about regex syntax. Try to be a little more original and personal about it this time.</p>
<p>Regex syntax is very VERY compact, almost too compact to be good. Its like code-golfing,
and everyone agrees code-golfing isn't a good thing in production code. However most people accept regex syntax, which seems... contradictory to say the least.</p>
<p>So now some common defenses one is likely to hear include :</p>
<ul>
<li><p><em>Answer</em>: It's compact</p></li>
<li><p><em>Counter</em>: Haven't we all agreed in this day and age that code should be literate and a variable like "client" is better than "c"?</p></li>
<li><p><em>Answer</em>: It's a "domain specific language"</p></li>
<li><p><em>Counter</em>: how about all the very easy to understand, non compact, non cryptic and dare I say pretty domain languages out there like SQL or LINQ?</p></li>
<li><p><em>Answer</em>: Its easy to understand once you know it.</p></li>
<li><p><em>Counter</em>: Most great languages are easy to understand even if you've never used them before. For example anyone could jump into Python very easily even if they had never seen it before. And why do people defend Regex when its such a hard language to look at, but then go on and complain about Lisps parenthesis?</p></li>
</ul>
<p>Ok now everyone try to be original and honest here, don't just pull out the same old rote answers programmers used 20 years ago to design regex. Unless you really believe they are valid propositions in this day and age.</p>
<hr>
<p><strong>Edit:</strong> For the record, I know Regex from years ago, use them frequently even today and might even grok them. However I suddenly had a feeling it was perhaps time to reconsider things I had taken as "truths" about regex, and look at them from a modern standpoint. Mostly because questioning principles is necessary for further development, and because so many newcomers complain vehemently about them, they can't just be flat out right, so I decided to try to step into the shoes of a newcomer and consider what are some good points against regex.</p>
<p>As for being <strong>subjective</strong>, I don't think this is less subjective OR less programmer related than <strong>Programmer Jokes</strong> of the days stuff. On the contrary it is very programmer related.</p>
<p>As for <strong>argumentative</strong>, thats the point of the question. To get good arguments pro and con regex outdated syntax, that can serve newcomers to actually understand more about why regex are what they are, and even better hopefully get some newcomer to come up with a better solution US old minded can't see because we are blinded by the "coolness" of regex.</p>
<hr>
<p><strong>Quote:</strong></p>
<blockquote>
<p>The Perl 5.10 documentation for
regexes has melted down into a heap of
unreadable drivel because so many zany
features have creeped into the syntax
that no-one can write sensible
documentation for it any more.</p>
</blockquote>
<p>You're trying to say regex have become unmaintainable? Well then as good programmers should we consider refactoring them? Maybe cleaning up and trying over as we've done with some many other technologies?</p>
|
<p>Most of what I have to say were addressed by Adam and DGM, but I don't think they cover your second point very well.</p>
<p>"how about all the very easy to understand, non compact, non cryptic and dare I say pretty domain languages out there like SQL or LINQ?"</p>
<p>I think a good way to express an answer to this is to ask, how would you use English to explain a regular expression?</p>
<pre><code><TAG\b[^>]*>(.*?)</TAG>
</code></pre>
<p>Look for "<TAG" a word boundary zero or more of something that is not '>' followed by a '>' remember zero or more of something, stopping at the first "</TAG>"</p>
<p>This is a fairly simple regex. Is the English form really easier to understand? Could you do better?</p>
<p>Regular expressions are hard to read, but what you want from them can be just as hard to explain.</p>
|
<p>I bet all participants in this discussion will agree that for certain <strong>small</strong> regex codes one would have to write a long paragraph in English describing what it does. Any kind of language that may be used to do what even the simplest regexp describes will probably do it with N lines of code, where N (probably) grows exponentially in comparison to the length of the regexp itself.</p>
| 33,103
|
<p>I have just built my first 3D printer, and I am having some problems. It is a Cartesian based 3D printer, using Marlin firmware and Pronterface software. My problem is homing the 3D printer. I do not have a probe to calibrate the z offset but I have all 6 endstops. The problem is that the "ZMIN" endstop isn't precise enough and my hotend is always either too far from or too close to the heatbed. Is there a way to manually set the home position, so when I start the printer, It just starts printing and it doesn't have to home again; Or maybe some other way to set the correct offset. It would also be helpful if I could use just the "ZMAX" plug, and then manually set the minimum Z position using a piece of paper.</p>
|
<p>It is possible to "home a printer" without having endstops, technically, you don't <strong>require</strong> endstops, but it makes your job a lot easier if you want to print something!</p>
<p>Basically, when you don't have endstops or limit switches, you need to define where the head of the printer is located. E.g. you can set the nozzle at [0, 0, 0] (origin in [x, y, z]) and add the command <a href="https://reprap.org/wiki/G-code#G92:_Set_Position" rel="nofollow noreferrer"><code>G92</code></a> to your print G-code file that it is at that position using <code>G92 X0 Y0 Z0</code> (or any other location you use, e.g. you could engineer a parking position and refer to that position instead, note that you also need to write the movement commands to get out of that location safely). Don't forget to remove the homing command from your start code in your slicer, replace <code>G28</code> with the <code>G92</code> command with appropriate X, Y and Z values.</p>
<p>Regarding the inaccurate repetitive accuracy of your Z min endstop, it might be worth to find out why this is causing such a spread in triggering, maybe you need to invest in some new endstop switches or look more closely to the heated bed attachment to the frame.</p>
<p>Using Z max as a reference point is e.g. used by Ultimaker machines. The heated platform lowers to Z max; the printer knows from calibration and geometry how far it needs to rise to get to Z=0.</p>
|
<p>You can reconfigure marlin to use the MAXZ endstop instead of MINZ in Configuration.h, and then reflash it to your printer.</p>
<p><a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration.h#L877" rel="nofollow noreferrer">https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration.h#L877</a></p>
<p>Now this is highly unusual, as most printers only have MIN endstops. If you post a pic of your faulty MINZ endstop, we can probably figure out how you could fix it. Zipties come to mind as a likely solution.</p>
| 1,216
|
<p>For some reason I'm not getting this. (Example model below) If I write: </p>
<pre><code>var property = typeof(sedan).GetProperty("TurningRadius");
Attribute.GetCustomAttributes(property,typeof(MyAttribute), false)
</code></pre>
<p>the call will return MyAttribute(2) despite indicating I don't want to search the inheritance chain. Does anyone know what code I can write so that calling</p>
<pre><code>MagicAttributeSearcher(typeof(Sedan).GetProperty("TurningRadius"))
</code></pre>
<p>returns nothing while calling</p>
<pre><code>MagicAttributeSearcher(typeof(Vehicle).GetProperty("TurningRadius"))
</code></pre>
<p>returns MyAttribute(1)?</p>
<hr>
<p>Example Model:</p>
<pre><code>public class Sedan : Car
{
// ...
}
public class Car : Vehicle
{
[MyAttribute(2)]
public override int TurningRadius { get; set; }
}
public abstract class Vehicle
{
[MyAttribute(1)]
public virtual int TurningRadius { get; set; }
}
</code></pre>
|
<p>Okay, given the extra information - I believe the problem is that <code>GetProperty</code> is going up the inheritance change.</p>
<p>If you change your call to <code>GetProperty</code> to:</p>
<pre><code>PropertyInfo prop = type.GetProperty("TurningRadius",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
</code></pre>
<p>then <code>prop</code> will be null if the property isn't overridden. For instance:</p>
<pre><code>static bool MagicAttributeSearcher(Type type)
{
PropertyInfo prop = type.GetProperty("TurningRadius", BindingFlags.Instance |
BindingFlags.Public | BindingFlags.DeclaredOnly);
if (prop == null)
{
return false;
}
var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false);
return attr != null;
}
</code></pre>
<p>This returns <code>true</code> and only if:</p>
<ul>
<li>The specified type overrides the <code>TurningRadius</code> property (or declares a new one)</li>
<li>The property has the <code>MyAttribute</code> attribute.</li>
</ul>
|
<p>I think this is what you're after - note that I had to make TurningRadius abstract in Vehicle and overridden in Car. Is that okay?</p>
<pre><code>using System;
using System.Reflection;
public class MyAttribute : Attribute
{
public MyAttribute(int x) {}
}
public class Sedan : Car
{
// ...
}
public class Car : Vehicle
{
public override int TurningRadius { get; set; }
}
public abstract class Vehicle
{
[MyAttribute(1)]
public virtual int TurningRadius { get; set; }
}
class Program
{
static void Main(string[] args)
{
MagicAttributeSearcher(typeof(Sedan));
MagicAttributeSearcher(typeof(Vehicle));
}
static void MagicAttributeSearcher(Type type)
{
PropertyInfo prop = type.GetProperty("TurningRadius");
var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false);
Console.WriteLine("{0}: {1}", type, attr);
}
}
</code></pre>
<p>Output:</p>
<pre><code>Sedan:
Vehicle: MyAttribute
</code></pre>
| 34,517
|
<p>I have a situation in which I parse a body of text and replace certain phrases with links. I then need to re-parse the string to replace a second set of phrases with links. The problem arises at this point, where certain words or phrases in the second set can be substrings of phrases already replaced in the first pass.</p>
<p><strong>Example</strong>: The string "blah blah grand canyon blah" will become "blah blah <code><a href="#">grand canyon</a></code> blah" after the first pass. The second pass might try to replace the word "canyon" with a link, so the resulting, broken, text would read: "blah blah <code><a href="#"></code>grand <code><a href="#"></code>canyon<code></a></a></code> blah".</p>
<p>So I've been trying to use preg_replace and a regular expression to prevent nested <code><a></code> tags from occurring - by only replacing text which is not already in a link. I have tried to regexes that check based on whether there are <code></a></code> tags further on in the text but can't get these to work.</p>
<p>Maybe another approach is required?</p>
<p>Many thanks in advance!
Dave</p>
|
<p>This might work for all passes:</p>
<pre><code>$string = preg_replace('/([^>]|^)grand canyon\b/','$1<a href=#>grand canyon</a>',$string);
</code></pre>
<p>EDIT: assuming you can afford missing when the text contains stuff like "amazonas>grand canyon"</p>
|
<p>For the second pass, you could use a regex such as:</p>
<pre><code>(<a[^>]*>.*?</a>)|grand
</code></pre>
<p>This regex matches either a link, or the word "grand". If the link is matched, it is captured into the first (and only) capturing group. If the group matched, simply re-insert the existing link. If the word grand matches, you know it's outside a link, and you can turn it into a link.</p>
<p>In PHP you can do this with preg_replace_callback:</p>
<pre><code>$result = preg_replace_callback('%(<a[^>]*>.*?</a>)|grand%', compute_replacement, $subject);
function compute_replacement($groups) {
// You can vary the replacement text for each match on-the-fly
// $groups[0] holds the regex match
// $groups[n] holds the match for capturing group n
if ($groups[1]) {
return $groups[1];
} else {
return "<a href='#'>$groups[0]</a>";
}
</code></pre>
| 49,899
|
<p>I am new at this and maybe my model is not the best, I adapted it for another one actually. Can you tell me why I can't get the holes printed? I already checked the faces and they are all in the correct orientation (I think)</p>
<p>What happens is that I start printing with the holes facing down and they are not printed at all. I never let it keep going for long but it seems to be completely filled inside.</p>
<p>You can check the file <a href="https://ufile.io/9favbj6e" rel="nofollow noreferrer">here</a>.</p>
<p><a href="https://i.stack.imgur.com/lSvn0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lSvn0.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/b1PSD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b1PSD.png" alt="enter image description here" /></a></p>
|
<h1>The problem is internal geomoetry</h1>
<p>The body you modeled consists of a non-manifold shell: There exists a fully enclosed shell on the inside of the item that tries to define an "outside" of the body. In the following picture, I have hidden part of the geometry to better show the problematic internal surfaces in orange:</p>
<p><a href="https://i.stack.imgur.com/UWHWH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UWHWH.jpg" alt="internal Geometry" /></a></p>
<p>Automatic processes such as Meshmixer or Windows 10 3D builder interpret such an internal, one-sided open cylinder as "This probably is missing a surface on both ends". This solution leads to two intersecting and manifold shells - <a href="https://3dprinting.stackexchange.com/q/6230/8884">a cylinder overlapping the drilled holes and the body with the drilled holes</a> - which then promptly get treated with a boolean union... and voila! No more holes. Or even no more outer shell as the easiest solution is to just stitch that lower surface and discard the rest. This is what happens when Meshmixer does just that: you are left with the cone half and some inverted artifact areas.</p>
<p><a href="https://i.stack.imgur.com/AshxK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AshxK.png" alt="Meshmixer automatic repair removes half the model leaving a few inverted artifacts" /></a></p>
<p>So the best solution is to ensure the parts don't contain such volumes encased by a non-manifold surface in the first place. Due to the nature of the part, in this case, it is rather simple: Simply removing the circle of vertices that spans up both the plane, as well as the cylinder, marked orange results in all internal surfaces getting removed. Note that due to the orange parts sharing (at least partially) vertices with the wanted outside, this has to be done manually. Would both surfaces share no vertex, a simple "separate shells" operation could result in a very quick way to remove offending structures.</p>
<p><a href="https://i.stack.imgur.com/tEKZJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tEKZJ.png" alt="Without internal geometry" /></a></p>
<p>Without the internal geometry, the model gets interpreted correctly - the mere presence of such superfluous internal geometry makes the slicer believe that some surfaces are inverted or missing, and thus need to be inverted or stitched - and the solution to the slicing is... utter mess.</p>
<p><a href="https://i.stack.imgur.com/Vbix6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vbix6.png" alt="Cura rendition of the defect and cured model" /></a>
<a href="https://i.stack.imgur.com/kgC0I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kgC0I.png" alt="Slicing solutions, before and after removal of internal geometry" /></a></p>
|
<p>The overall appearance is that the normals are "normal," that you have no reversed facets, but there are discontinuities within the model that Meshmixer and Netfabb show as failure points. Windows 10 3DBuilder also attempts a repair which fills in the holes.</p>
<p><a href="https://i.stack.imgur.com/L92T7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L92T7.png" alt="meshmixer failure indicators" /></a></p>
<p>The Meshmixer capture image shows red lines and points at the flaws in the model. Both above programs fill the faces, which works fine on the cylinder, but fills in the plane where the holes reside, as well as removes the internal holes/cylinders, preventing a simple plane cut repair.</p>
<p>Additional examination of the original model shows an internal cylinder formed axially on the end face red warning markers in the image above.
I used Rhino3D v6 to slip inside, select the cylinder and remove it. Because the cylinder is "inside" the overall model, there's no inside face and outside face, causing the software to glitch.</p>
<p>On the red line along the circumference of the cylinder, there's an internal disk/disc with an internal diameter to match the previously removed internal cylinder. As it also resides within the overall model, the same trouble applies: no true inside/outside surface for the software to comprehend.</p>
<p>Once these were removed, a problematic set of errors appeared. I'm working on that. Work completed. Windows 10 3DBuilder has a pretty amazing repair facility, once the deep stuff is cleaned away. The end result passes the Meshmixer Inspector test and I suspect will work for you. The cylinder appears to be 37 mm in diameter (about an inch and a half) which is rather tiny, but with the flaws repaired, will scale up just fine.</p>
<p>It loaded into Simplify3D slicer with no errors and appears will print nicely, although with support required along the beveled portion of the cylinder.</p>
| 2,125
|
<p>I had a little discussion with a friend about the usage of collections in return/input values of a method. He told me that we have to use
- the most derived type for return values.
- the least derived type for input parameters.</p>
<p>So, it means that, for example, a method has to get a ReadOnlyCollection as parameter, and as return a List.</p>
<p>Moreover, he said that we must not use List or Dictionary in publics API, and that we have to use, instead Collection, ReadOnlyCollection, ... So, in the case where a method is public, its parameters and its return values must be Collection, ReadOnlyCollection, ...</p>
<p>Is it right ?</p>
|
<p>Regarding input parameters, it's generally more flexible to use the least specific type. For example, if all your method is going to do is enumerate the items in a collection passed as an argument, it's more flexible to accept IEnumerable<T>.</p>
<p>For example, consider a method "ProcessCustomers" that accepts a parameter that is a collection of customers:</p>
<pre><code>public void ProcessCustomers(IEnumerable<Customer> customers)
{
... implementation ...
}
</code></pre>
<p>If you declare the parameter as IEnumerable<Customer>, your callers can easily pass in a subset of a collection, using code like the following (pre-NET 3.5: with .NET 3.5 you could use lambda expressions):</p>
<pre><code>private IEnumerable<Customer> GetCustomersByCountryCode(IEnumerable<Customer> customers, int countryCode)
{
foreach(Customer c in customers)
{
if (c.CountryCode == countryCode) yield return c;
}
}
...
ProcessCustomers(GetCustomersByCountryCode(myCustomers, myCountryCode);
...
</code></pre>
<p>In general MS guidelines recommend not exposing List<T>. For a discussion of why this is so, see <a href="http://blogs.msdn.com/fxcop/archive/2006/04/27/faq-why-does-donotexposegenericlists-recommend-that-i-expose-collection-lt-t-gt-instead-of-list-lt-t-gt-david-kean.aspx" rel="nofollow noreferrer">this blog entry</a> from the Code Analysis (FxCop) team.</p>
|
<p>I tend to agree with not returning or using List or Dictionary as parameters in API's because it really limits the developer targeting the API. Instead returning or passing IEnumerable<> works really well.</p>
<p>Of coarse, all of this depends on the application. Just my opinion.</p>
| 21,402
|
<p>I need to find occurrences of ~ 25 000 words within a text. What is the most suitable algorithm/library for this purpose?</p>
<p>target language is C++</p>
|
<p>build a hashtable with the words, and scan throuhgt the text, for each word lookup in the wordtable and stuff the needed info (increment count, add to a position list, whatever).</p>
|
<p>viceBerg says:</p>
<blockquote>
<p>I once used the Boyer-Moore algorithm
and it was quite fast.</p>
</blockquote>
<p>With Boyer-Moore, aren't you typically searching a block of text for a <strong>single</strong> string?</p>
<p>For a simple to implement solution go with the hash table approach suggested by Javier. The Bloom Filter suggested by FatCat1111 should work too... depending on the goals.</p>
| 18,654
|
<p>I want to save and store simple mail objects via serializing, but I get always an error and I can't find where it is.</p>
<pre><code>package sotring;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.sun.org.apache.bcel.internal.generic.INEG;
public class storeing {
public static void storeMail(Message[] mail){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mail.ser"));
out.writeObject(mail);
out.flush();
out.close();
} catch (IOException e) {
}
}
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
for (int i=0; i< array.length;i++)
System.out.println("EMail von:"+ array[i].getSender() + " an " + array[i].getReceiver()+ " Emailbetreff: "+ array[i].getBetreff() + " Inhalt: " + array[i].getContent());
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
return null;
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User user1 = new User("User1", "geheim");
User user2 = new User("User2", "geheim");
Message email1 = new Message(user1.getName(), user2.getName(), "Test", "Fooobaaaar");
Message email2 = new Message(user1.getName(), user2.getName(), "Test2", "Woohoo");
Message email3 = new Message(user1.getName(), user2.getName(), "Test3", "Okay =) ");
Message [] mails = {email1, email2, email3};
storeMail(mails);
Message[] restored = getStoredMails();;
}
}
</code></pre>
<p>Here are the user and message class</p>
<pre><code>public class Message implements Serializable{
static final long serialVersionUID = -1L;
private String receiver; //Empfänger
private String sender; //Absender
private String Betreff;
private String content;
private String timestamp;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Message (String receiver, String sender, String Betreff, String content) {
this.Betreff= Betreff;
this.receiver = receiver;
this.sender = sender;
this.content = content;
this.timestamp = getDateTime();
}
Message() { // Just for loaded msg
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getBetreff() {
return Betreff;
}
public void setBetreff(String betreff) {
Betreff = betreff;
}
public String getContent() {
return content;
}
public String getTime() {
return timestamp;
}
public void setContent(String content) {
this.content = content;
}
}
public class User implements Serializable{
static final long serialVersionUID = -1L;
private String username; //unique Username
private String ipadress; //changes everytime
private String password; //Password
private int unreadMsg; //Unread Messages
private static int usercount;
private boolean online;
public String getName(){
return username;
}
public boolean Status() {
return online;
}
public void setOnline() {
this.online = true;
}
public void setOffline() {
this.online = false;
}
User(String username,String password){
if (true){
this.username = username;
this.password = password;
usercount++;
} else System.out.print("Username not availiable");
}
public void changePassword(String newpassword){
password = newpassword;
}
public void setIP(String newip){
ipadress = newip;
}
public String getIP(){
if (ipadress.length() >= 7){
return ipadress;
} else return "ip address not set.";
}
public int getUnreadMsg() {
return unreadMsg;
}
}
</code></pre>
<p>Here is the exception:</p>
<p><code>exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type Message[]
at sotring.storeing.getStoredMails(storeing.java:22)
at sotring.storeing.main(storeing.java:57)</code></p>
<p>THANK YOU FOR YOUR HELP!!!!!!!!!!!</p>
|
<p>If an exception occurs, you never get to the return statement in getStoredMails. You need to either throw the exception you catch (possibly wrapping it in another more descriptive exception) or just return null at the end of the method. It really depends on what you want to do if there's an error.</p>
<p>Oh, and your in.close() should be in a finally block. Otherwise, it is possible that you could read the data fine but then throw it away if you can't close the stream.</p>
|
<p>I modified the source. I added "return null" in exception and the for loop the output in the function. And the function gives me the right output but then throws it the exception.</p>
| 21,207
|
<p>We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses?</p>
|
<p>if you want to only filter if certain criteria is passed, do something like this</p>
<pre><code>var logs = from log in context.Logs
select log;
if (filterBySeverity)
logs = logs.Where(p => p.Severity == severity);
if (filterByUser)
logs = logs.Where(p => p.User == user);
</code></pre>
<p>Doing so this way will allow your Expression tree to be exactly what you want. That way the SQL created will be exactly what you need and nothing less.</p>
|
<p>Just use C#'s && operator:</p>
<pre><code>var items = dc.Users.Where(l => l.Date == DateTime.Today && l.Severity == "Critical")
</code></pre>
<p>Edit: Ah, need to read more carefully. You wanted to know how to <em>conditionally</em> add additional clauses. In that case, I have no idea. :) What I'd probably do is just prepare several queries, and execute the right one, depending on what I ended up needing.</p>
| 3,235
|
<p>I have a web app that uses log4net to log errors to a log file.
It works well when I publish my website via xcopy but when I build a package installer, log4net does not appear to work when remote users access my site.</p>
<p>I use <em>impersonate=true</em> in my web.config and log4net only logs errors when I am the logged user.</p>
<p>I have another app that works fine in all cases but was not package deployed.</p>
<p>Does anyone have any thoughts?</p>
|
<p>After all it was a permission issue
setting the write permission to everyone log4net started logging well as it uses the
current logged user account</p>
<p>regards</p>
|
<p>i don't think so because same config is used in a working app</p>
<p>but here it is</p>
<p>what user does log4net uses when writing to disk?!
Is there any need to add permissions to write to log folders? Because i use impersonate=true the user logged to the site is the one that log4net is using to write
to file system right?!</p>
<pre><code> <!-- log4net -->
<log4net debug="false">
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="D:\\WSBank\\Solution\\Logs\\Solution.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1024KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
</code></pre>
| 46,399
|
<p>I have created a multi column datastore on a table that allows me to do full text indexing on the table. What I need to be able to do is weight each column different and add the scores together.</p>
<p>The following query works, but is slow:</p>
<pre><code>SELECT document.*, Score(1) + 2*Score(2) as Score
FROM document
WHERE (CONTAINS(documentContent, 'the_keyword', 1) > 0
OR CONTAINS(documentTitle, 'the_keyword', 2) > 0 )
ORDER BY Score DESC
</code></pre>
<p>After quite a bit of Googling, people have proposed the solution as:</p>
<pre><code>SELECT document.*, Score(1) as Score
FROM document
WHERE CONTAINS(dummy, '(((the_keyword) within documentTitle))*2 OR ((the_keyword) within documentText)',1) > 0)
ORDER BY Score Desc
</code></pre>
<p>The above query is faster than its predecessor but it does not solve the actual problem. In this case, if the keyword is found in the documentTitle, it will not search the documentText (it uses the OR operator). What I really need is to ADD the two scores together so that if a keyword appears in the title AND the text it will have a higher score than if it only appears in the title. </p>
<p>So, how do you add the scores for weighted columns in one CONTAINS clause? </p>
|
<p>Instead of the OR operator, use ACCUM:</p>
<p>SELECT document.*, Score(1) as Score
FROM document
WHERE CONTAINS(dummy, '(((the_keyword) within documentTitle))*2 <strong>ACCUM</strong> ((the_keyword) within documentText)',1) > 0)
ORDER BY Score Desc</p>
|
<p>What if you do a nested select?</p>
<pre><code>select *, Score(1) + 2 * Score(2) as Score
from (
SELECT document.*, Score(1) as Score
FROM document
WHERE CONTAINS(dummy, '(((the_keyword) within documentTitle))
OR ((the_keyword) within documentText)',1) > 0)
)
ORDER BY Score Desc
</code></pre>
| 28,911
|
<p>Has anyone gotten the jquery plugin <a href="http://www.appelsiini.net/projects/jeditable" rel="nofollow noreferrer">jeditable</a> to run properly in a Rails applications. If so, could you share some hints on how to set it up? I'm having some trouble with creating the "submit-url".</p>
<hr>
<p>IIRC, you cannot simply call ruby code from within javascript (please let me be wrong:-). Do you mean RJS??? Isn't that limited to Prototype? I'm using jQuery.</p>
<hr>
<p><strong>UPDATE:</strong><br>
uh.....asked this a while back and in the meantime switched to a different solution. But IIRC my main issue was the following:</p>
<p>I'm using the RESTful resources. So let's say I have to model a blog and thus have the resource "posts". If I want to edit a post (e.g. the post with the ID 8), my update is sent via HTTP to the URL <a href="http://my.url.com/posts/8" rel="nofollow noreferrer">http://my.url.com/posts/8</a> with the HTTP verb POST. This URL however is constructed in my Rails code. So how would I get my submit-url into my jQuery code? Since this is RESTful code, my update URL will change with every post.</p>
|
<p>Excuse me for bringing this up only now, but I just found the time to look into my code again. I think I solved my problem by the following javascript (my application.js within rails):</p>
<pre><code>jQuery(document).ready(function($) {
$(".edit_textfield").each( function(i) {
$(this).editable("update", {
type : 'textarea',
rows : 8,
name : $(this).attr('name'),
cancel : 'Cancel',
submit : 'OK',
indicator : "<img src='../images/spinner.gif' />",
tooltip : 'Double-click to edit...'
})
});
});
</code></pre>
<p>This works, if your Controller URLs are RESTful.</p>
|
<p>I"m not sure I entirely understand the problem you're having, but I think you could put something like this in your javascript:</p>
<pre><code><%= url_for(@post) %>
</code></pre>
<p>It depends how you're structuring your javascript, how you've got your files organised etc...</p>
| 27,283
|
<p>I'm working on a program to do some image wrangling in Python for work. I'm using FreeImagePy because PIL doesn't support multi-page TIFFs. Whenever I try to save a file with it from my program I get this error message (or something similar depending on which way I try to save):</p>
<pre><code>Error returned. TIFF FreeImage_Save: failed to open file C:/OCRtmp/ocr page0
Traceback (most recent call last):
File "C:\Python25\Projects\OCRPageUnzipper\PageUnzipper.py", line 102, in <mod
ule> OCRBox.convertToPages("C:/OCRtmp/ocr page",FIPY.FIF_TIFF)
File "C:\Python25\lib\site-packages\FreeImagePy\FreeImagePy\FreeImagePy.py", l
ine 2080, in convertToPages self.Save(FIF, dib, fileNameOut, flags)
File "C:\Python25\lib\site-packages\FreeImagePy\FreeImagePy\FreeImagePy.py", l
ine 187, in Save return self.__lib.Save(typ, bitmap, fileName, flags)
WindowsError: exception: priviledged instruction
</code></pre>
<p>When I try and do the same things from IDLE, it works fine.</p>
|
<p>Looks like a permission issues, make sure you don't have the file open in another application, and that you have write permissions to the file location your trying to write to.</p>
|
<p>That's what I thought too, but I figured it out a couple hours ago. Apparently if the directory/file I'm trying to write to doesn't exist, FreeImagePy isn't smart enough to create it (most of the time. Creating a new multipage image seems to work fine) but i guess running it within IDLE, IDLE figures it out and takes care of it or something. I managed to work around it by using os.mkdir to explicitly make sure things that I need exist.</p>
| 29,710
|
<p>Many products/services we are interact with (including our own) uses XML-over-HTTP or derivatives (like OMA IMPS IM/presence protocol).</p>
<p>I am looking for some tool that will "listen" to a traffic and produce client/server stubs for simulation/testing.</p>
<p>Thanks. </p>
|
<p>To some degree, it sounds like what <a href="http://maxq.tigris.org/" rel="nofollow noreferrer">maxq</a> is trying to do.</p>
|
<p>That sounds like a good idea for a project.</p>
<p>This is not a solution, but your first step should be to at least support know webservice descriptors. </p>
<p>To do that should sniff the traffic using wireshark or something similar and see the URL's that are being accessed. If you are lucky these services would be webservices with a retrievable descriptor or schema for the interface. Check for .xsd, .wsdl, .asmx</p>
<p>Here are some examples:</p>
<p><a href="http://www.webservicex.net/CurrencyConvertor.asmx" rel="nofollow noreferrer">http://www.webservicex.net/CurrencyConvertor.asmx</a></p>
<p><a href="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl" rel="nofollow noreferrer">http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl</a></p>
<p><a href="http://www.weather.gov/forecasts/xml/DWMLgen/schema/DWML.xsd" rel="nofollow noreferrer">http://www.weather.gov/forecasts/xml/DWMLgen/schema/DWML.xsd</a></p>
<p>There are Microsoft tools available that come packaged with the SDL that can provide stubs for these.</p>
<p>I don't know of any drop in solution for you but my approach to solving this problem would be:
- use wireshark to record http conversations for specific webservices.
- parse (or look at) these files to extract the URLs that are invoked and track the message passing + xml documents.
- Create stubs based on what appear to be the parameters.
- Start by creating some simple pattern matchers and transforms (xml + xsl can = code or some page for debug).</p>
<p>You may also need to consider
- communication may not be 2 way xml- it could be HTTP posts with query string one way and xml responses back.
- The XML documents may not be properly formatted XML- test parse each message before trying to generate anything.</p>
| 37,398
|
<p>Is it possible to skip a couple of characters in a capture group in regular expressions? I am using .NET regexes but that shouldn't matter.</p>
<p>Basically, what I am looking for is:</p>
<blockquote>
<p>[random text]AB-123[random text]</p>
</blockquote>
<p>and I need to capture 'AB123', without the hyphen.</p>
<p>I know that AB is 2 or 3 uppercase characters and 123 is 2 or 3 digits, but that's not the hard part. The hard part (at least for me) is skipping the hyphen.</p>
<p>I guess I could capture both separately and then concatenate them in code, but I wish I had a more elegant, regex-only solution.</p>
<p>Any suggestions?</p>
|
<p>In short: You can't. A match is always consecutive, even when it contains things as zero-width assertions there is no way around matching the next character if you want to get to the one after it.</p>
|
<p>Kind of late, but I think I figured this one out. At least one way to do it.</p>
<p>I used positive lookahead to stop at the # sign in my text. I didn't want the space or the # sign, so I had to figure a way out to "skip" over them. So when I was forced to match them again, I dumped them into a garbage group that I didn't plan on using (.ie, a bit bucket) which in the code is . Now, my place pointer is one character position beyond the # sign (where I want to be, skipping the space and the # sign). And I now just match to the end of the file name at the . and ignore the file extension.</p>
<pre><code>(?i)English\\(?<Series>[^ ]+) - (?<Title>.+(?= #))(?<garb1>..)(?<Number>[^.]+)(?-i)
</code></pre>
<p>The Filename this was used on is</p>
<pre><code>F:\Downloads\Downloads\500 Comics CCC CBR English\Isukani - Great Girl #01.cbr
</code></pre>
| 35,027
|
<p>If I would write:</p>
<pre>
int selectedChannels = selector.select();
Set selectedKeys = selector.selectedKeys();
if ( selectedChannels != selectedKeys.size() ) {
// Selector.select() returned because of a call to Selector.wakeup()
// so do synchronization.
}
// Continue with handling selected channels.
</pre>
<p>would it correctly detect the wakeup-call?</p>
<p><strong>Backgroundinformation:</strong></p>
<p>I'm writing a server which most of the time just receives packets and stores them in a file. Very rarely the application has the need to send itself a special packet. For this it initiates a connection (from a different thread) to the server socket:</p>
<pre>
SocketChannel channel = SocketChannel.open();
channel.configureBlocking( false );
channel.connect( new InetSocketAddress( InetAddress.getLocalHost(), PORT ));
selector.wakeup();
SelectionKey key = channel.register( selector, SelectionKey.OP_CONNECT );
</pre>
<p>The problem is that SelectableChannel.register() might block if the main thread is already in Selector.select(). To prevent this from happening I'm calling Selector.wakeup() which let's the main thread return prematurely from select(). To make sure the other thread has the chance to complete the register-call, I would have to synchronize the main thread, but I would have to do it after <strong>every</strong> return from select(). If I could detect whether it returned from select() because of a wakeup() call, then I could optimize it for just this case.</p>
<p>So, in theory the top code snippet should work, but I was wondering whether it would only do so, because it relies on some unspecified behavior?</p>
<p>Thanks for any hints.</p>
|
<p>I would guess that the proposed snippet would not work at all in principle, per the contracts of <code>Selector#select()</code> and <code>Selector#selectedKeys()</code>. From <a href="http://java.sun.com/javase/6/docs/api/java/nio/channels/Selector.html" rel="nofollow noreferrer">Selector</a>:</p>
<blockquote>
<ul>
<li>The selected-key set is the set of keys such that each key's channel was detected to be ready for at least one of the operations identified in the key's interest set during a prior selection operation. This set is returned by the selectedKeys method.</li>
</ul>
</blockquote>
<pre>public abstract int select(long timeout)
throws IOException
Returns:
The number of keys, possibly zero, whose ready-operation sets were
updated
</pre>
<p>As I read that, the size of the <code>selectedKeys</code> set should always equal the number returned by <code>select</code> by definition. I have noticed - as you may have as well - that some implementations don't quite follow the documentation, and in fact <code>selectedKeys</code> returns all keys with updated ready-operation sets, even if they were not updated during a call to <code>select</code>. The only other indicator that the select woke up due to a call to <code>wakeup</code> might be that the number of keys is zero; however either method would be unreliable, at best.</p>
<p>The usual way to handle this is, as implied, through concurrency control. I wouldn't worry about execution time here; this is a classic example of <a href="http://en.wikipedia.org/wiki/Optimization_(computer_science)#When_to_optimize" rel="nofollow noreferrer">premature optimization</a>.</p>
<p>Unless you're really worried about single digit microsecond tolerances, you won't notice any slowdown - and if you are worried about that level of tolerance, a <code>Selector</code> isn't going to be reliable enough for you anyway.</p>
<p>Here's an example of the usual mechanism for this, using a <code>ReentrantLock</code> to accomplish the appropriate concurrency:</p>
<pre><code>ReentrantLock selectorGuard;
Selector selector;
private void doSelect() {
// Don't enter a select if another thread is in a critical block
selectorGuard.lock();
selectorGuard.unlock();
selector.select();
Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
while(keyIter.hasNext()) {
SelectionKey key = keyIter.next();
keyIter.remove();
// Process key
}
}
private void addToSelector() {
// Lock the selector guard to prevent another select until complete
selectorGuard.lock();
try {
selector.wakeup();
// Do logic that registers channel with selector appropriately
} finally {
selectorGuard.unlock();
}
}
</code></pre>
|
<p>You can't really be sure that the only reason that the selector woke up was due to the wakeup call. You may also have socket activity.</p>
<p>So, you need to make the caller of wakeup also do something like setting a volatile boolean to indicate its desire for attention. The the selector loop can check the value of this boolean every time it wakes up.</p>
| 43,242
|
<p>I know that <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>B</kbd> launches a solution build, but I would like a shortcut that just builds the current project. Is a custom shortcut my only option?</p>
<p><strong>Edit:</strong> Looks like a custom shortcut is my only option as <kbd>Shift</kbd> + <kbd>F6</kbd> does not work for me.</p>
|
<p>Assigning the shortcut to "Build.BuildOnlyProject" command doesn't seem to work in VS2008.</p>
<p>Assign the shortcut to "Build.BuildSelection". If you have a solution with several projects and files open from the various projects, whatever file you are currently editing will define the project that will be built when you use the assigned shortcut for "Build.BuildSelection".</p>
<p>You'll know the keyboard shortcut is working when you click the Build menu option and you see the keyboard shortcut on the menu itself.</p>
<p>btw - a restart/reboot is not required when assigning keyboard shortcuts.</p>
|
<p>In the Visual Studio options window, under "Keyboard", look for the "Build.BuildOnlyProject" command and you can set whatever you want.</p>
| 30,775
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/164926/c-sharp-how-do-i-round-a-decimal-value-to-2-decimal-places-for-output-on-a-pa">c# - How do I round a decimal value to 2 decimal places (for output on a page)</a> </p>
</blockquote>
<p>I want to truncate the decimals like below</p>
<p>i.e.</p>
<ul>
<li>2.22939393 -> 2.229</li>
<li>2.22977777 -> 2.229</li>
</ul>
|
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/zy06z30k.aspx" rel="noreferrer">Math.Round</a>:</p>
<pre><code>decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229
</code></pre>
<p>Or you can use ToString with the N3 <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx" rel="noreferrer">numeric format</a>.</p>
<pre><code>string roundedNumber = number.ToString("N3");
</code></pre>
<p><strong>EDIT:</strong> Since you don't want rounding, you can easily use <a href="http://msdn.microsoft.com/en-us/library/system.math.truncate.aspx" rel="noreferrer">Math.Truncate</a>:</p>
<pre><code>Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229
</code></pre>
|
<p>Try this:</p>
<pre><code>decimal original = GetSomeDecimal(); // 22222.22939393
int number1 = (int)original; // contains only integer value of origina number
decimal temporary = original - number1; // contains only decimal value of original number
int decimalPlaces = GetDecimalPlaces(); // 3
temporary *= (Math.Pow(10, decimalPlaces)); // moves some decimal places to integer
temporary = (int)temporary; // removes all decimal places
temporary /= (Math.Pow(10, decimalPlaces)); // moves integer back to decimal places
decimal result = original + temporary; // add integer and decimal places together
</code></pre>
<p>It can be writen shorter, but this is more descriptive.</p>
<p><strong>EDIT:</strong> Short way:</p>
<pre><code>decimal original = GetSomeDecimal(); // 22222.22939393
int decimalPlaces = GetDecimalPlaces(); // 3
decimal result = ((int)original) + (((int)(original * Math.Pow(10, decimalPlaces)) / (Math.Pow(10, decimalPlaces));
</code></pre>
| 42,745
|
<p>Mine would have to be the float and margin bugs...</p>
<p>If you float an element, and then specify a margin for it, it will double the margin.</p>
<p>The solution to this is to add <code>display: inline</code> to the element. This will stop the double margin, and all other browsers will ignore it because only block level objects can be floated.</p>
|
<p>I wish I'd known that I'd be spending hours trying to fix a bug in IE 6 over and over again for years on end and I really would have been happier delivering pizza.</p>
|
<p>in addition to other IE bug lists that Ross and Loque gave above (gtalbot.com, what a beautiful site!</p>
<p><a href="http://css-discuss.incutio.com/?page=InternetExplorerWinBugs" rel="nofollow noreferrer">http://css-discuss.incutio.com/?page=InternetExplorerWinBugs</a></p>
<p><a href="http://webbugtrack.blogspot.com/search/label/IE7" rel="nofollow noreferrer">http://webbugtrack.blogspot.com/search/label/IE7</a></p>
<p><a href="http://www.enhanceie.com/ie/bugs.asp" rel="nofollow noreferrer">http://www.enhanceie.com/ie/bugs.asp</a></p>
<p><a href="http://channel9.msdn.com/wiki/internetexplorerprogrammingbugs/" rel="nofollow noreferrer">http://channel9.msdn.com/wiki/internetexplorerprogrammingbugs/</a>
(like gtalbot, it'll take you hours to scroll thru this</p>
<hr>
<p>and, hey, IE 8 beta 2</p>
<p><a href="http://css-class.com/test/bugs/ie/ie-bugs.htm" rel="nofollow noreferrer">http://css-class.com/test/bugs/ie/ie-bugs.htm</a></p>
<hr>
<p>finally, the IE voodoo doll!</p>
<p><a href="http://www.flickr.com/photos/chisa/1349759901/" rel="nofollow noreferrer">http://www.flickr.com/photos/chisa/1349759901/</a></p>
| 29,987
|
<p>When debugging, a trick I do whenever I want to exit the current method without running of its any statements, I move the current execution pointer to the end of the method, then click F10/11.</p>
<p>Is there a keyboard shortcut (or can I program one) to accomplish this?</p>
<p>(I don't mean shift-F11 (step out) - that does run all the code until the method's end, which I do not want).</p>
|
<p>The following sequence of keystrokes works for me (tested in Visual Studio 2008); I was able to record them as a temporary macro and play them back successfully:</p>
<ol>
<li><code>Ctrl+M, Ctrl+M</code> (Edit.ToggleOutliningExpansion: collapses the current method)</li>
<li><code>Right arrow</code> (skips past the collapsed parameter list)</li>
<li><code>Ctrl+]</code> (Edit.GotoBrace: goes to the opening brace)</li>
<li><code>Ctrl+]</code> (Edit.GotoBrace: goes to the closing brace)</li>
<li><code>Ctrl+Shift+F10</code> (Debug.SetNextStatement: sets the next statement to the closing brace at the end of the function)</li>
<li><code>F10</code> (Debug.StepOver: leaves the method)</li>
</ol>
|
<p>AFAIK that's the only way to do it.</p>
| 26,813
|
<p>Something happened that I'm not sure should be possible. Obviously it is, because I've seen it, but I need to find the root cause & I was hoping you all could help.</p>
<p>We have a system that looks up latitude & longitude for a zipcode. Rather than access it every time, we cache the results in a cheap in-memory HashTable cache, since the lat & long of a zip code tend to change less often than we release.</p>
<p>Anyway, the hash is surrounded by a class that has a "get" and "add" method that are both synchronized. We access this class as a singleton.</p>
<p>I'm not claiming this is the best setup, but it's where we're at. (I plan to change to wrap the Map in a Collections.synchronizedMap() call ASAP.)</p>
<p>We use this cache in a multi-threaded environment, where we thread 2 calls for 2 zips (so we can calculate the distance between the two). These sometimes happen at very nearly the same time, so its very possible that both calls access the map at the same time.</p>
<p>Just recently we had an incident where two different zip codes returned the same value. Assuming that the initial values were actually different, is there any way that writing the values into the Map would cause the same value to be written for two different keys? Or, is there any way that 2 "gets" could cross wires and accidentally return the same value?</p>
<p>The only other explanation I have is that the initial data was corrupt (wrong values), but it seems very unlikely.</p>
<p>Any ideas would be appreciated.
Thanks,
Peter</p>
<p>(PS: Let me know if you need more info, code, etc.)</p>
<pre><code>public class InMemoryGeocodingCache implements GeocodingCache
{
private Map cache = new HashMap();
private static GeocodingCache instance = new InMemoryGeocodingCache();
public static GeocodingCache getInstance()
{
return instance;
}
public synchronized LatLongPair get(String zip)
{
return (LatLongPair) cache.get(zip);
}
public synchronized boolean has(String zip)
{
return cache.containsKey(zip);
}
public synchronized void add(String zip, double lat, double lon)
{
cache.put(zip, new LatLongPair(lat, lon));
}
}
public class LatLongPair {
double lat;
double lon;
LatLongPair(double lat, double lon)
{
this.lat = lat;
this.lon = lon;
}
public double getLatitude()
{
return this.lat;
}
public double getLongitude()
{
return this.lon;
}
}
</code></pre>
|
<p>Why it's happening is hard to tell. More code could help.</p>
<p>You should probably just be using a ConcurrentHashMap anyway. This will be more efficient, in general, than a synchronized Map. You don't synchronize access to it, it handles it internally (more efficiently than you could).</p>
|
<p>I don't really see anything wrong with the code you posted that would cause the problem you described. My guess would be that it's a problem with the client of your geo-code cache that has problems.</p>
<p>Other things to consider (some of these are pretty obvious, but I figured I'd point them out anyway):</p>
<ol>
<li>Which two zip codes were you having problems with? Are you sure they don't have identical geocodes in the source system?</li>
<li>Are you sure you aren't accidentally comparing two identical zip codes?</li>
</ol>
| 30,295
|
<p>I have to read data from some files and insert the data into different tables in a database. Is Unix shell script powerful enough to do the job?</p>
<p>Is it easy to do the job in shell script or should I go about doing this in Java?</p>
|
<p>If the data you are trying to import is in a reasonable format -- comma-delimited, for example -- and your database server has reasonable command line utilities, this should be no problem. MySQL has the "mysqlimport" command-line tool that will accept various arguments describing the format of the file:</p>
<pre class="lang-sh prettyprint-override"><code>mysqlimport \
--fields-terminated-by=, \
--ignore-lines=1 \
--fields-optionally-enclosed-by='"' < datafile.txt
</code></pre>
<p>Passing the data through perl/sed/awk one-liners can help with getting it in the proper format, and the shell script can easily handle prompting for filenames, handling arguments, etc.</p>
<p>Using the various command-line tools provided by Unix is the entire point of bash scripting. Perl, mysql, etc. are all part of that toolkit.</p>
|
<p>Shell scripting (Bash or similar) primary intention is not to deal with databases. Go for Java or even better, ride this opportunity to learn the basics of a scripting language like Python or Ruby.</p>
| 9,731
|
<p>I have a foxpro app, that contains hard coded path for icons and bitmaps. That's how foxpro does it and there is no way around it. And this works fine, except that when a removable drive has been used but is not connected, and when is connected windows assigns the same letter as hard coded path, when opening any form that contains such path, the following error message apears (<strong>FROM WINDOWS</strong>, not fox):</p>
<p>Windows-No disk
Exception Processing Message c0000012 Parameters .....</p>
<p>Any help please
Nelson Marmol</p>
|
<p>Nelson:</p>
<p>"That's how foxpro does it and there is no way around it"?</p>
<p>I'm using FOX since FoxPro 2.5 to Visual FoxPro 9, and you are NEVER forced in any way to hard-code a path, you can use SET PATH TO (sYourPath), you can embed the icons and bitmaps in your EXE / APP file and therefore there's no need of including this resources externally.</p>
<p>You say that you have a "Foxpro App": which version? Old MS-DOS FoxPro o Visual FoxPro?
If you're using VFP 8+, you can use SYS(2450, 1):</p>
<pre><code>Specifies how an application searches for data and resources such as functions, procedures, executable files, and so on.
You can use SYS(2450) to specify that Visual FoxPro searches within an application for a specific procedure or user-defined function (UDF) before it searches along the SET DEFAULT and SET PATH locations. Setting SYS(2450) can help improve performance for applications that run on a local or wide area network.
SYS(2450 [, 0 | 1 ])
Parameters
0
Search along path and default locations before searching in the application. (Default)
1
Search within the application for the specified procedure or UDF before searching the path and default locations.
</code></pre>
<p>One quick workaround could be assign another letter to your USB via the Disk Manager.</p>
|
<p>I agree with @PabloG - it's been over a decade since I worked with FoxPro (Dos & Windows) but even back in FPW2.6 you could determine where your app was running 'from', set absolute or relative search paths and even bundle your resources straight into the "compiled" (heh) exe. All of our resources lived in a specific subfolder within the app folder, the database files in another subfolder also below the app folder. We used relative paths for everything as I recall.</p>
<p>Can you give us a bit more information about the problem?</p>
<p>If you think it would be helpful I could try and dig out some of our FPW2.6 code where we're doing this kind of thing. :-)</p>
| 8,037
|
<p>Is there any way to add a field to a class at runtime ( a field that didn't exist before ) ? Something like this snippet :</p>
<pre><code>Myobject *ob; // create an object
ob->addField("newField",44); // we add the field to the class and we assign an initial value to it
printf("%d",ob->newField); // now we can access that field
</code></pre>
<p>I don't really care how it would be done , I don't care if it's an ugly hack or not , I would like to know if it could be done , and a small example , if possible .</p>
<p><strong>Another Example:</strong> say I have an XML file describing this class :</p>
<pre><code><class name="MyClass">
<member name="field1" />
<member name="field2" />
</class>
</code></pre>
<p>and I want to "add" the fields "field1" and "field2" to the class (assuming the class already exists) . Let's say this is the code for the class :</p>
<pre><code>class MyClass {
};
</code></pre>
<p>I don't want to create a class at runtime , I just want to add members/fields to an existing one .</p>
<p>Thank you !</p>
|
<h2>Use a map and a variant.</h2>
<p>For example, using boost::variant. See <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html" rel="noreferrer">http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html</a></p>
<p>(But of course, you can create your own, to suit the types of your XML attributes.)</p>
<pre><code>#include <map>
#include <boost/variant.hpp>
typedef boost::variant< int, std::string > MyValue ;
typedef std::map<std::string, MyValue> MyValueMap ;
</code></pre>
<p>By adding MyValueMap as a member of your class, you can add properties according to their names. Which means the code:</p>
<pre><code>oMyValueMap.insert(std::make_pair("newField", 44)) ;
oMyValueMap.insert(std::make_pair("newField2", "Hello World")) ;
std::cout << oMyValueMap["newField"] ;
std::cout << oMyValueMap["newField2"] ;
</code></pre>
<p>By encapsulating it in a MyObject class, and adding the right overloaded accessors in this MyObject class, the code above becomes somewhat clearer:</p>
<pre><code>oMyObject.addField("newField", 44) ;
oMyObject.addField("newField2", "Hello World") ;
std::cout << oMyObject["newField"] ;
std::cout << oMyObject["newField2"] ;
</code></pre>
<p>But you lose somewhat the type safety of C++ doing so. But for XML, this is unavoidable, I guess.</p>
|
<p>No -- C++ does not support any manipulation of the type system like this. Even languages with some degree of runtime reflection (e.g. .NET) would not support exactly this paradigm. You would need a much more dynamic language to be able to do it.</p>
| 29,135
|
<p>In postgres I am fairly sure you can do something like this</p>
<pre><code>SELECT
authors.stage_name,
count(select id from books where books.author_id = authors.id)
FROM
authors,
books;
</code></pre>
<p>Essentially, in this example I would like to return a list of authors and how many books each has written.... in the same query.</p>
<p>Is this possible? I suspect this approach is rather naive..</p>
<p>Thanks :)</p>
|
<p>Well, for one thing, it returns a Cartesian product of all authors to all books, regardless of whether that author wrote that book.</p>
<p>Here's how I'd write a query to get the result you say you want:</p>
<pre><code>SELECT a.stage_name, COUNT(b.id)
FROM authors a
LEFT OUTER JOIN books b ON (a.id = b.author_id)
GROUP BY a.id;
</code></pre>
<p>You need to learn how to write join queries if you use SQL. The join is to SQL what the loop is to application programming languages. I.e. it's a fundamental programming construct that you need to know.</p>
|
<p>How about using a join:</p>
<pre><code>SELECT authors.stage_name, count(*)
FROM authors INNER JOIN books on books.author_id = authors.id
GROUP BY authors.stage_name
</code></pre>
| 47,063
|
<p>I'm writing a PHP application with testability in mind, so my classes always ask in their constructors for the "collaborator objects" they depend on, in respect to the Dependency Injection pattern.</p>
<p>That way, I'm able to pass in mocks or test implementations in my unit tests.</p>
<p>What I want to achieve though, is to be able to instantiate a class with null values passed to its constructor arguments, in order to trigger a fallback mechanism which instantiates a default implementation class for each collaborator.</p>
<p>Because object-type parameters cannot be given a default value in PHP, I have to do it inside the constructor. The following code is an example of the approach I'm currently using :</p>
<pre><code>class Engine
{
private $loader;
private $logger;
public function __construct(ResourceLoader $loader = null, Logger $logger = null)
{
if ($loader == null) $loader = new DefaultResourceLoader;
if ($logger == null) $logger = new DefaultLogger;
$this->loader = $loader;
$this->logger = $logger;
}
}
</code></pre>
<p>What do you think of this ? Should I use an IoC container instead or is there another way of giving object-type arguments a default value ?</p>
|
<p>Of course you'd better use an IoC/DIP container to do the job. Your code above (the if statements) increase the coupling of the classes. The client class (Engine) should not care what’s implementing the loader and logger roles. That’s the factory’s or DIP container work to know this. By putting a concrete class name into your code and bind the classes together making your code less flexible (agile), less reusable and thus less maintainable. </p>
|
<p>You could use my tiny library <a href="https://github.com/LapaLabs/ValueResolver" rel="nofollow">ValueResolver</a> in this case, for example:</p>
<pre><code>$logger = ValueResolver::resolve($logger, new DefaultLogger);
</code></pre>
<p>and don't forget to use namespace <code>use LapaLabs\ValueResolver\Resolver\ValueResolver;</code></p>
<p>There are also ability to typecasting, for example if your variable's value should be <code>integer</code>, so use this:</p>
<pre><code>$id = ValueResolver::toInteger('6 apples', 1); // returns 6
$id = ValueResolver::toInteger('There are no apples', 1); // returns 1 (used default value)
</code></pre>
<p>Check the <a href="https://github.com/LapaLabs/ValueResolver" rel="nofollow">docs</a> for more examples</p>
| 49,322
|
<p>I figured someone can answer the question generally but if anyone wants to get specific I am trying to use:</p>
<p>using System.Web.Security.SingleSignOn;
using System.Web.Security.SingleSignOn.Authorization;</p>
<p>I've googled my brains out and this is the closest answer I found:</p>
<p>"We discussed this offline, but it looks like the ADFS assembly is GACed, but
not installed on the file system or registered with VS.NET so that it shows
up in the .NET tab. I'm guessing MS may need to beef up the installer for
this scenario. In the meantime, you probably need to do this yourself."</p>
<p>What on earth, do WHAT myself?</p>
|
<p>I found an <a href="http://web2.minasi.com/forum/topic.asp?TOPIC_ID=23116" rel="nofollow noreferrer">install log</a> showing that it was expected to be in</p>
<blockquote>
<p>C:\WINDOWS\ADFS\System.Web.Security.SingleSignon.dll</p>
</blockquote>
<p>on Windows Server 2003. You probably need to have active directory installed for it to appear there because I checked one of my 2003 servers without AD and it wasn't there.</p>
<p>Normally I would guess the DLL would be registered in the system-wide Global Assembly Cache (GAC), so you wouldn't have to know the actual path for it. If an assembly is registered in the GAC, then you can add a reference to it by bringing up the "Add Reference" dialog and clicking on the ".NET" Tab.</p>
|
<p>For projects using specific environment (like SharePoint object model)is recommended using virtual pc with installed in GAC assemblies. ADFS assemblies should have only Win server. If you find them and install manually in work environment (desktop) some possibilities (like debugging) will not impossible.</p>
| 12,875
|
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p>
<p>If the standard library doesn't support that, does the dateutil package support this?</p>
|
<p><a href="https://docs.python.org/library/calendar.html#calendar.monthrange" rel="noreferrer"><code>calendar.monthrange</code></a> provides this information:</p>
<blockquote>
<p>calendar.<b>monthrange</b>(year, month)<br>
Returns weekday of first day of the month and number of days in month, for the specified <em>year</em> and <em>month</em>.</p>
</blockquote>
<pre><code>>>> import calendar
>>> calendar.monthrange(2002, 1)
(1, 31)
>>> calendar.monthrange(2008, 2) # leap years are handled correctly
(4, 29)
>>> calendar.monthrange(2100, 2) # years divisible by 100 but not 400 aren't leap years
(0, 28)
</code></pre>
<p>so:</p>
<pre><code>calendar.monthrange(year, month)[1]
</code></pre>
<p>seems like the simplest way to go.</p>
|
<p>If you pass in a date range, you can use this:</p>
<pre><code>def last_day_of_month(any_days):
res = []
for any_day in any_days:
nday = any_day.days_in_month -any_day.day
res.append(any_day + timedelta(days=nday))
return res
</code></pre>
| 6,456
|
<p>I've been always thinking that DOMNodeInsertedIntoDocument/DOMNodeRemovedFromDocument events should not bubble, and for me that made enough sence. However, just recently I looked into specification once again and found out that in one location it says these events should not bubble (<a href="http://www.w3.org/TR/DOM-Level-3-Events/events.html#Events-EventTypes-complete" rel="nofollow noreferrer">Complete list of event types</a>), while in other location is says they should (<a href="http://www.w3.org/TR/DOM-Level-3-Events/events.html#event-DOMNodeInsertedIntoDocument" rel="nofollow noreferrer">DOMNodeInsertedIntoDocument</a> and <a href="http://www.w3.org/TR/DOM-Level-3-Events/events.html#event-DOMNodeRemovedFromDocument" rel="nofollow noreferrer">DOMNodeRemovedFromDocument</a>).</p>
<p>I've also looked up on the Internet and found several implementations, all of them are different in the behavior implemented.</p>
<p>The question is: Should these events actually bubble ot not? What do you think make more sence?</p>
<p><b>Update</b>: Found out that in <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html" rel="nofollow noreferrer">DOM-Level-2-Events</a> specification there is no ambiguity since it olny mentions these events in a single location.</p>
<p><b>Update 2</b>: This question was asked in order to validate the behavior of these events in the <a href="http://www.clientside.ru/" rel="nofollow noreferrer">Ample SDK</a> Ajax Framework that aims to implement all standards-based technologies.</p>
|
<p>What about something like this?</p>
<pre><code>for(i=0;i<array_size;i++) {
print "group" + (Math.floor(i/(array_size/N)) + 1)
}
</code></pre>
|
<p>I think the problem is a little more complicated; and considering that your only look at group as a 1 dimensional problem your going to get a very odd view of what groups actually are.</p>
<p>Firstly the problem is dimensional according to the number of group primes, and group combinations you are dealing with. In Mathematics; this is represented as n to the power of n or n^n which can be translated to !n (factor of n).</p>
<p>If I have 5 groups arrayed as (1, 2, 3, 4, 5) then I wanted to represent it as certain groups or combonations of groups according to a factorial expression then the combonations get bigger</p>
<p>Group 1x1 = 1,2,3,4,5<BR>
Group 2x1 = 12, 23, 45, 13, 14, 15, 21, 24, 25, 31, 32, 34, 35, 41, 42, 43, 45, 51, 52, 53, 54<BR>
so the strategy creates a branch systematic branch (easy enough)<BR>
12, 13, 14, 15<BR>
21, 22, 23, 24<BR>
31, 32, 34, 35<BR>
41, 42, 43, 45<BR>
51, 52, 53, 55<BR>
Group 1 + 2x2x1 = (1, 23, 45), (2, 13, 45), (3, 12, 45), (4, 12, 35), (1, 24, 35), (1, 25, 35), (1, 32, 45), (1, 34, 25), (1, 35, 24), ... etc</p>
<p>As you can see when you begin to add factorial sets the comboniations become not so easy to create a mathematic reference to express the terms. It gets worst when you get up into a base set > 3 or 4 length.</p>
<p>If I am understanding your question: you want to expressing in a generic terms an algorythm which allows you to create grouping strategies programmatically?</p>
<p>This is a complicated set; and is represented best in calculus; as set theory. Otherwise all your doing is a two dimensional array handling.</p>
<p>the first Array expresses the grouping strategy;
the second Array expresses the grouping elements.</p>
<p>I don't think this is what your being asked to do, because the term "GROUP" in mathematics has a very specific allocation for the term. You should not use the term group; rather express it as a set; set1, set2 if that is what you are doing.</p>
<p>Set1 contains elements of set2; and therefor this is handled with the same mathematics as Sets and unions are expressed. Lookup "Vin Diagrams" and "Union"; avoid using the term group unless you are representing the factor of a set.
<BR>
<a href="http://en.wikipedia.org/wiki/Group_(mathematics)" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Group_(mathematics)</a><BR>
<BR>
I think what you are trying to express is the groups within a known set or table; This is on the wikipedia.org example D2.
<BR><BR>
In which case that means you have to look at the problem like a rubik's cube; and it gets complicated.<BR>
<BR>
I'm working the same problem in javascript; when I am done I might publish it ;). It's very complicated.</p>
| 41,734
|
<p>How do you go about verifying the type of an uploaded file reliably without using the extension? I'm guessing that you have to examine the header / read some of the bytes, but I really have no idea how to go about it. Im using c# and asp.net.</p>
<p>Thanks for any advice.</p>
<hr>
<p>ok, so from the above links I now know that I am looking for 'ff d8 ff e0' to positively identify a .jpg file for example.</p>
<p>In my code I can read the first twenty bytes no problem:</p>
<pre><code> FileStream fs = File.Open(filePath, FileMode.Open);
Byte[] b = new byte[20];
fs.Read(b, 0, 20);
</code></pre>
<p>so (and please excuse my total inexperience here) but how do I check whether the byte array contains 'ff d8 ff e0'?</p>
|
<p>Here's a quick-and-dirty response to the followup question you posted:</p>
<pre><code>byte[] jpg = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 };
bool match = true;
for (int i = 0; i < jpg.Length; i++)
{
if (jpg[i] != b[i])
{
match = false;
break;
}
}
</code></pre>
|
<p>Reading the contents of the file is the fool proof way. Since you are building it in .Net, you could probably check the MIME Type of the uploaded file.</p>
<p>You can DllImport urlmon.dll to help. Please refer a post at:
<a href="http://coding-passion.blogspot.com/2008/11/validating-file-type.html" rel="nofollow noreferrer">http://coding-passion.blogspot.com/2008/11/validating-file-type.html</a></p>
<p>And to clarify regarding Content-type, it invariably is driven by the extension of the file. So even a .zip file got its extension renamed to .txt, the content type will still say Text only.</p>
| 30,414
|
<p>How do you determine when to use <a href="http://www.iselfschooling.com/mc4articles/mc4cluster.htm" rel="noreferrer">table clusters</a>? There are two types, index and hash, to use for different cases. In your experience, have the introduction and use of table clusters paid off?</p>
<p>If none of your tables are set up this way, modifying them to use table clusters would add to the complexity of the set up. But would the expected performance benefits outweight the cost of increased complexity in future maintenance work? </p>
<p>Do you have any favorite online references or books that describe table clustering well and give good implementation examples? </p>
<p>//Oracle tips greatly appreciated. </p>
|
<p>The killer feature of table clusters is that you can store <strong>related rows of different tables</strong> at the same physical location.</p>
<p>That can improve join performance by an order of magnitude. However, it doesn't pay of so often as it sounds.</p>
<p>The only time I used it was a three-table join, executed by two hash joins. It took too long ;). However, the join was on the same column, so it was possible to use a hash table cluster keyed by the join column. That caused all related rows to be stored alongside (ideally, in the same database block). Knowing that, Oracle can execute the join with a special optimization ("cluster join").</p>
<p>It's more or less pre-joined, but still feeling like normal tables (for INSERT/SELECT/UPDATE/DELETE).</p>
<p>On the other hand, there are "single table clusters" that are mostly used to control the "clustering factor" -- A similar idea like clustered indexes (called Index-Organized-Table in Oracle) but not adding high cost if using a secondary index.</p>
|
<p>I haven't used Oracle's table clusters myself, but I understand that its index table clusters are very much like MS SQL Server's clustered indexes. That is, the row data is physically organized by the clustered index's key.</p>
<p>That makes one ideal for a heavily-accessed column that has a reasonably small number of possible values (compared to the total number of rows), where most queries want to retrieve all rows with a particular value. Because all such rows are physically stored together, disk I/O, particularly seek time, is reduced.</p>
<p>"Reasonably small" is not easily defined, but postal or zip codes in an address table seems reasonable if you're often querying for all addresses in a single code's region. Province/state/territory codes are likely too small a selection for a country-wide address table.</p>
<p>So, you don't want to use them on columns with few possible values (e.g., M/F for gender) because then the clustering doesn't buy you anything and likely costs you for insertions. You also never want to use clustering on "autonumber" surrogate key columns (from sequences in Oracle) because that will create a "hot spot" in the last extent of the table as all insertions must physically happen there. You also don't want to apply clustering to a column value that will be updated because the RDBMS will have to physically move the record to maintain the clustered ordering.</p>
| 4,769
|
<p>Is there a generic way to clone objects in VBA? So that i could copy x to y instead of copying just the pointer?</p>
<pre><code> Dim x As New Class1
Dim y As Class1
x.Color = 1
x.Height = 1
Set y = x
y.Color = 2
Debug.Print "x.Color=" & x.Color & ", x.Height=" & x.Height
</code></pre>
<p>By generic i mean something like <code>Set y = CloneObject(x)</code> rather than having to create my own method for the class copying its properties one by one.</p>
|
<p>OK, here's the beginning of something that illustrates it:</p>
<p>Create a class, call it, oh, "Class1":</p>
<pre><code>Option Explicit
Public prop1 As Long
Private DontCloneThis As Variant
Public Property Get PrivateThing()
PrivateThing = DontCloneThis
End Property
Public Property Let PrivateThing(value)
DontCloneThis = value
End Property
</code></pre>
<p>Now we need to give it a Clone function. In another module, try this:</p>
<p>Option Explicit</p>
<pre><code>Public Sub makeCloneable()
Dim idx As Long
Dim line As String
Dim words As Variant
Dim cloneproc As String
' start building the text of our new function
cloneproc = "Public Function Clone() As Class1" & vbCrLf
cloneproc = cloneproc & "Set Clone = New Class1" & vbCrLf
' get the code for the class and start examining it
With ThisWorkbook.VBProject.VBComponents("Class1").CodeModule
For idx = 1 To .CountOfLines
line = Trim(.lines(idx, 1)) ' get the next line
If Len(line) > 0 Then
line = Replace(line, "(", " ") ' to make words clearly delimited by spaces
words = Split(line, " ") ' so we get split on a space
If words(0) = "Public" Then ' can't set things declared Private
' several combinations of words possible
If words(1) = "Property" And words(2) = "Get" Then
cloneproc = cloneproc & "Clone." & words(3) & "=" & words(3) & vbCrLf
ElseIf words(1) = "Property" And words(2) = "Set" Then
cloneproc = cloneproc & "Set Clone." & words(3) & "=" & words(3) & vbCrLf
ElseIf words(1) <> "Sub" And words(1) <> "Function" And words(1) <> "Property" Then
cloneproc = cloneproc & "Clone." & words(1) & "=" & words(1) & vbCrLf
End If
End If
End If
Next
cloneproc = cloneproc & "End Function"
' put the code into the class
.AddFromString cloneproc
End With
End Sub
</code></pre>
<p>Run that, and the following gets added into Class1</p>
<pre><code>Public Function Clone() As Class1
Set Clone = New Class1
Clone.prop1 = prop1
Clone.PrivateThing = PrivateThing
End Function
</code></pre>
<p>...which looks like a start. Lots of things I'd clean up (and probably will - this turned out to be fun). A nice Regular Expression to find gettable/lettable/settable attributes, refactoring into several small functions, code to remove old "Clone" functions (and put the new one at the end), something a bit more Stringbuilder-ish to DRY (Don't Repeat Yourself) up the concatenations, stuff like that.</p>
|
<p>I don't think there's anything built in, although it would be nice.</p>
<p>I think there should at least be a way to create a Clone method automatically using the VBA Editor. I'll see if I can take a look at it once I've got the kids to bed...</p>
| 26,909
|
<p>We've got some problems with an external company trying in integrate into a WCF service we expose and they are a Java shop. I was wondering if there are more than one toolkit that they can try to solve their issues and would like a list to suggest to them but I'm not familiar with the Java world at all.</p>
<p>Essentially they've got some memory leak (apparently!) but they are very sketchy in the details.</p>
|
<p>Microsoft and Sun <a href="https://wsit.dev.java.net/" rel="nofollow noreferrer">worked together</a> to ensure that their latest web services toolkits worked with each other. Sun's java implementation is <a href="https://metro.dev.java.net/" rel="nofollow noreferrer">Metro</a>.</p>
|
<p>Are they using Axis, if you are presenting a standard webservice to them? Or are you presenting a custom REST service that they have had to do more manual coding for (HTTPClient, XML generators/parsers, etc)?</p>
| 16,810
|
<p>This is something I've pseudo-solved many times and have never quite found a solution for.</p>
<p>The problem is to come up with a way to generate <code>N</code> colors, that are as distinguishable as possible where <code>N</code> is a parameter.</p>
|
<p>My first thought on this is "how to generate N vectors in a space that maximize distance from each other."</p>
<p>You can see that the RGB (or any other scale you use that forms a basis in color space) are just vectors. Take a look at <a href="http://mathworld.wolfram.com/topics/RandomPointPicking.html" rel="noreferrer">Random Point Picking</a>. Once you have a set of vectors that are maximized apart, you can save them in a hash table or something for later, and just perform random rotations on them to get all the colors you desire that are maximally apart from each other!</p>
<p>Thinking about this problem more, it would be better to map the colors in a linear manner, possibly (0,0,0) → (255,255,255) lexicographically, and then distribute them evenly.</p>
<p>I really don't know how well this will work, but it should since, let us say:</p>
<pre><code>n = 10
</code></pre>
<p>we know we have 16777216 colors (256^3).</p>
<p>We can use <a href="https://stackoverflow.com/questions/561/using-combinations-of-sets-as-test-data#794">Buckles Algorithm 515</a> to find the lexicographically indexed color.<img src="https://i.stack.imgur.com/gEuCs.gif" alt="\frac {\binom {256^3} {3}} {n} * i">. You'll probably have to edit the algorithm to avoid overflow and probably add some minor speed improvements.</p>
|
<p>I've read somewhere the human eye can't distinguish between less than 4 values apart. so This is something to keep in mind. The following algorithm does not compensate for this.</p>
<p>I'm not sure this is exactly what you want, but this is one way to randomly generate non-repeating color values:</p>
<p>(beware, inconsistent pseudo-code ahead)</p>
<pre><code>//colors entered as 0-255 [R, G, B]
colors = []; //holds final colors to be used
rand = new Random();
//assumes n is less than 16,777,216
randomGen(int n){
while (len(colors) < n){
//generate a random number between 0,255 for each color
newRed = rand.next(256);
newGreen = rand.next(256);
newBlue = rand.next(256);
temp = [newRed, newGreen, newBlue];
//only adds new colors to the array
if temp not in colors {
colors.append(temp);
}
}
}
</code></pre>
<p>One way you could optimize this for better visibility would be to compare the distance between each new color and all the colors in the array:</p>
<pre><code>for item in color{
itemSq = (item[0]^2 + item[1]^2 + item[2]^2])^(.5);
tempSq = (temp[0]^2 + temp[1]^2 + temp[2]^2])^(.5);
dist = itemSq - tempSq;
dist = abs(dist);
}
//NUMBER can be your chosen distance apart.
if dist < NUMBER and temp not in colors {
colors.append(temp);
}
</code></pre>
<p>But this approach would significantly slow down your algorithm.</p>
<p>Another way would be to scrap the randomness and systematically go through every 4 values and add a color to an array in the above example.</p>
| 2,268
|
<p>One of the local libraries has a new small Makerbot 3D printer. I have been submitting Sketchup files converted to STL files for printing. </p>
<p>The tech guy who runs the printer for patrons is having trouble getting a project of mine to come out to be the right size. I need this item go be 2 inches wide. The tech guy sizes the item on the screen to 2 inches. I watched him do it. But, the item is printed with a base of 2 inches, and the item itself comes out smaller. </p>
<p>Does anyone have suggestions about this? I can get more info if someone can give me the right questions to ask. The tech is open to taking suggestions. He wants to get the printer running smoothly for patrons.</p>
<p>I submitted a file with my own base with supports made in Sketchup. But, the tech guy said he needs to set the printer to create it's own base and supports.</p>
<p>Additional info:</p>
<p>When I printed it by letting Makerbot create the base and supports, it came out to be 1 3/4" as shown here:
<a href="https://flic.kr/p/EashnD" rel="nofollow">https://flic.kr/p/EashnD</a></p>
<p>Printer: Makerbot Replicator with Smart Extruder (not Plus).
(I am now at the library with the technician.)</p>
<p>Here is a screenshot of what I am trying to print. It is a replacement clip for a messenger bag. So, it has to be 2 inches across.
<a href="https://flic.kr/p/EtdM6s" rel="nofollow">https://flic.kr/p/EtdM6s</a></p>
<p>Here is the printer:
<a href="https://flic.kr/p/E5F1M6" rel="nofollow">https://flic.kr/p/E5F1M6</a></p>
<p>I used a website to convert the DAE file exported from Sketchup to an STL file. It was GreenToken.com.</p>
<p>If I open the object's STL file in Tinkercad, the object appears two inches wide. And, if I open the file in one of the 3D printer websites in Tinkercad, the object appears two inches wide (in cm).</p>
<p>The security on the library's computers do not allow me to apply plug-ins to Sketchup. The library's Tech staff is going to eventually put the plug-in in there.</p>
<p>If it is resized to 2 inches wide in the MakerBot software to be sent to the printer, why is it printing the generated base 2 inches wide and not the object? Are there some settings the tech guy in the library is missing in this set up window? </p>
<p>Additional notes:
The library now has the latest version of SketchUp on Macs. They are working on installing the STL plugin. (Security issues)</p>
<p>My process for producing an STL file to print is now this:</p>
<ol>
<li><p>I create something in SU and export it as a DAE file.</p></li>
<li><p>I have found that meshconverter.com produces better STL files than greentoken. </p></li>
<li><p>I then upload/fix the STL file at the netFabb website. </p></li>
<li><p>I then import the STL file into TinkerCad to view it. If there are problems in the file, I can see them. And, I run it through netFabb again. I can also modify the file in TinkerCad. It is no where near as sophisticated as SketchUp. But, it doesn't claim to be. </p></li>
</ol>
<p>I have found that there is a way to export the STL file to 3D printer hubs through TinkerCad. You can see the prices, the material available and the location of the company/person doing the printing. You can contact the printer ahead of time and they can look at your file to give you advice. </p>
<p><strong>Update</strong></p>
<p>I just wanted to add that the netFabb website does not export STL files after it fixes them. It now gives you a 3MF file format when you upload an STL file. I am not sure why this happens. But, this has put a big wrench in my process. I can no longer fix SketchUp STL files with netFabb. When I bring them into TinkerCad, I see errors in the object. It seems like there are issues with complex curves.</p>
|
<p>It appears that you have scaled the object after the raft and supports were added. As you can see in your photo of the raft, the clip is approximately 7/8ths (1.75/2) the size of the raft.</p>
<p>Edit: As a side note, STL files don't actually have a concept of units. Each axis is defined in arbitrary units. That's why when you export and import it you have to set the scale appropriately. </p>
|
<p>My advice is to use a micrometer (i.e., sliding dial caliper) accurate to within .001" and measure the printed object. If it is 1 7/8" for example, you would open the STL file in Makerbot software and use their scaling tool to scale the object to 1.0666666...., which is what you get when you divide the desired size (2") by the actual printed size (1.875").
I have found that it is much simpler to do that than to reinvent the wheel and try to figure out what each software engineer was thinking on each program and each conversion process and try to make it work right every time. Chances are that the same conversion factor might work right for any file originating from the same source and going through the same conversion software package. Also,
3D printers in general don't like edges that aren't completely "welded", or continuous seams. With Sketchup if you keep zooming in on an edge you almost always get seams that are stitched at intervals determined by Sketchup algorithms. They are "unwelded" seams. Some 3D printers can handle them. Many don't. I have used various 3D software packages, including Sketchup, and the best one so far has been Rhinoceros 3D. It handles multiple complex curvaceous planes and can radius adjoining curved edges and can "weld" them. Aeronautical and boat building companies use it for CAD/CAM applications.<br>
...
The STL file converter you mentioned is probably taking the Sketchup file and "cleaning it up" so Makerbot likes it. You would almost have to know exactly what algorithms each developer uses. to try and 'fix' it mathematically
Like I said, do your own measuring and scale accordingly.
BTW, it's better in my opinion to let Makerbot do the rafts and supports. Their engineers typically do a pretty good job. Where I have had issues is on things with a shallow angle (almost horizontal) hanging out into empty space. If you can re-orient the object in the makerbot software so those types of angles are minimized, the print is alot cleaner.</p>
| 212
|
<p>I'm currently developing a security solution that should work across domains and as such I need a small private dns server to add various entries to. I could alter the hosts file to achieve the same result but since the hosts file doesn't support wildcard chars I will have a whole lot of entries, so a DNS server that supports wildcards would be a little bit easier. Any suggestions?</p>
|
<p>As a reference: <a href="http://sourceforge.net/projects/acrylic/" rel="noreferrer">http://sourceforge.net/projects/acrylic/</a></p>
<p>Acrylic is a local DNS proxy which improves the performance of your computer by caching the responses coming from your DNS servers.</p>
<p>I found it to work flawless on every Windows system from XP up to Win8, and it's open source.</p>
<p>And yes, it supports wildcards... it even supports regex for domain names.</p>
|
<p>You can use Microsoft DNS if you are using Windows Server (except Web edition). Or install a <a href="http://www.simpledns.com/" rel="nofollow noreferrer">Simple DNS Plus</a> trial (14 day) if you don't manage with BIND.</p>
| 48,023
|
<p>I'm coding a small CMS to get a better understanding of how they work and to learn some new things about PHP. I have however come across a problem.</p>
<p>I want to use mod_rewrite (though if someone has a better solution I'm up for trying it) to produce nice clean URLs, so site.com/index.php?page=2 can instead be site.com/tools</p>
<p>By my understanding I need to alter my .htaccess file each time I add a new page and this is where I strike a problem, my PHP keeps telling me that I can't update it because it hasn't the permissions. A quick bit of chmod reveals that even with 777 permissions it can't do it, am I missing something?</p>
<p>My source for mod_rewrite instructions is currently <a href="http://wettone.com/code/clean-urls" rel="noreferrer">this page here</a> incase it is important/useful.</p>
|
<p>One approach is to rewrite everything to a handling script</p>
<pre><code>RewriteEngine on
RewriteBase /
# only rewrite if the requested file doesn't exist
RewriteCond %{REQUEST_FILENAME} !-s
# pass the rest of the request into index.php to handle
RewriteRule ^(.*)$ /index.php/$1 [L]
</code></pre>
<p>so if you have a request to <a href="http://yourserver/foo/bar/" rel="nofollow noreferrer">http://yourserver/foo/bar/</a></p>
<p>what you actually get is a request to <a href="http://yourserver/index.php/foo/bar" rel="nofollow noreferrer">http://yourserver/index.php/foo/bar</a> - and you can leave index.php to decide what to do with /foo/bar (using $_SERVER['PATH_INFO'] -<a href="https://stackoverflow.com/users/22224/tom">tom</a>)</p>
<p>You only need to modify .htaccess the first time. All future requests for inexistent files can then be handled in PHP. </p>
<p>You might also find <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html" rel="nofollow noreferrer">the docs for mod_rewrite</a> useful - but keep it simple or prepare to lose a lot of sleep and hair tracking down obscure errors.</p>
|
<p>Your PHP should for very obvious reasons not be able to modify <code>.htaccess</code>. Even if you get that to work, I'm not sure if it is wise.</p>
<p>How about using a more abstract setup in regard to mod_rewrite rules? Define your general URL pattern, as you would like to use it. For example:</p>
<pre>
/object/action/id
</pre>
<p>Then write a set of rules that reroute HTTP requests to a PHP page, which in turn makes the decision what page is to run (say, by including the relevant PHP script).</p>
<pre>
RewriteRule ^/(\w+)/?(\w+)?/?(\d+)?$ /index.php?object=$1&action=$2&id=$3 [nocase]
</pre>
<p>This way you would not have to update <code>.htaccess</code> very often an still be flexible.</p>
| 33,342
|
<p>Google custom search code is provided as a form tag. However, Asp.net only allows a single form tag on a page. What is the best way to implement their code so you can include it on an aspx page (say as part of a Masterpage or navigation element). </p>
|
<p>You can have multiple form tags on an ASP.NET page. The limitation is on server-side (runat="server") form tags. </p>
<p>You can implement two form tags (or more) as long as only one has the runat="server" attribute and one is not contained in the other. Example:</p>
<pre><code><body>
<form action="http://www.google.com/cse" id="cse-search-box"> ... </form>
<form runat="server" id="aspNetform"> ... </form>
<body>
</code></pre>
|
<p>You could use Javascript:</p>
<pre><code><input name="Query" type="text" class="searchField" id="Query" value="Search" size="15" onfocus="if(this.value == 'Search') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Search'; }" onkeydown="var event = event || window.event; var key = event.which || event.keyCode; if(key==13) window.open('http://www.google.com/search?q=' + getElementById('Query').value ); " /><input name="" type="button" class="searchButton" value="go" onclick="window.open('http://www.google.com/search?q=' + getElementById('Query').value );" />
</code></pre>
| 10,073
|
<p>I want to use the <a href="http://simplehtmldom.sourceforge.net/manual_api.htm" rel="noreferrer">php simple HTML DOM parser</a> to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set_callback which Sets a callback function. However im not sure what this does or how I would use it? In one of the examples its used to call a function which strips out some stuff, im wondering if you have to use this to call all functions?</p>
<p>I guess im wondering why I use this, and what does it do as I have never come across a callback function before!</p>
|
<p>Here's a basic callback function example:</p>
<pre><code><?php
function thisFuncTakesACallback($callbackFunc)
{
echo "I'm going to call $callbackFunc!<br />";
$callbackFunc();
}
function thisFuncGetsCalled()
{
echo "I'm a callback function!<br />";
}
thisFuncTakesACallback( 'thisFuncGetsCalled' );
?>
</code></pre>
<p>You can call a function that has its name stored in a variable like this: <strong>$variable()</strong>.</p>
<p>So, in the above example, we pass the name of the <strong>thisFuncGetsCalled</strong> function to <strong>thisFuncTakesACallback()</strong> which then calls the function passed in.</p>
|
<p>With <code>PHP 5.3</code>, you can now do this:</p>
<pre><code>function doIt($callback) { $callback(); }
doIt(function() {
// this will be done
});
</code></pre>
<p>Finally, a nice way to do it. A great addition to <code>PHP</code>, because callbacks are awesome.</p>
| 28,636
|
<pre><code>test[_nObjectives].pool[j].feedbackCorrect =
oQuestions[j].getElementsByTagName("feedbackCorrect")[0].firstChild.data;
</code></pre>
<p>and the XML in this case contains this: </p>
<pre><code> <feedbackCorrect>
</feedbackCorrect>
</code></pre>
<p>When executing that line of code the following error occurs: Message: Object required</p>
<p>I don't get it. The tag is there, if it is empty the error occurs and even has spaces chars it doesn't work.</p>
|
<p>you are getting the error because</p>
<pre><code>oQuestions[j].getElementsByTagName("feedbackCorrect")[0]
</code></pre>
<p>is returning that tag, and the .firstChild is returning null, because it has no children...</p>
<p>Are you sure you dont want</p>
<pre><code>oQuestions[j].getElementsByTagName("feedbackCorrect")[0].data
</code></pre>
<p>?</p>
|
<p>but why it is working when the xml is like this: </p>
<pre><code><feedbackCorrect>any value</feedbackCorrect>
</code></pre>
<p>?</p>
| 47,568
|
<p>We're getting our feet wet with unit testing in VS 2008 Professional Edition and have hit what might be a pretty large snag: there appears to be no way to determine code coverage in this particular VS edition. It seems that this is something only available in VS Team System Development Edition.</p>
<p>In other words, VS 2008 Professional Edition allows you to write all the unit tests you want, but provides NO WAY to check which code does not have an associated unit test (or how much code is covered by tests). Is this observation correct? </p>
<p>If so, can someone recommend a 3rd-party tool to determine code coverage? I tried TestMatrix but was thoroughly unimpressed (The settings screen was hiding the OK and Cancel buttons at 120 DPI, running my current set of tests caused a complete VS lockup). </p>
<p>A side question: Instead of a 3rd party coverage tool, and instead of upgrading to VS Team System Development Edition, would it make better sense to adopt NUnit and find a free/low-cost code coverage tool? We're not knee-deep in unit testing yet, and we want to choose a testing method which won't hamper our efforts down the line... and not break the bank.</p>
|
<p><a href="http://www.ncover.com/" rel="nofollow noreferrer">NCover</a></p>
|
<p>I've been using <a href="http://www.ncover.com/" rel="nofollow noreferrer">NCover</a> with <a href="http://www.nunit.org/" rel="nofollow noreferrer">NUnit</a> under VS2008 for a few days. I've found it so easy to find and fill gaps in my test coverage, I've giggled aloud when NCover pops up. </p>
<p>One tip: if your tests are in the same file as the code they're testing, don't bother running NCover unless all of your tests pass. Otherwise, it'll flag all the failing test methods' trailing braces as uncovered. Though, perhaps that's just a hint that I should be putting my tests in a different file…</p>
| 22,258
|
<p>I'm building an application that is targeting Windows, Mac and Linux soon. I was wondering where should I keep application data such as settings, etc.</p>
<p>Application's installation folder is the easiest choice, but I think that might be a problem with new Vista security model. Besides, users might want different settings.</p>
<p>Is it C:\Documents and Settings\username\MyApp good for both Vista and XP?
Is it /home/username/.MyApp good for Linux and Macs?</p>
<p>Any ideas and/or links to best practices much appreciated.</p>
<p>Thanks!</p>
<p>Juan</p>
|
<p>Each platform has its own API for finding the user's home folder, or documents folder, or preferences folder. </p>
<ul>
<li>Windows: SHGetFolderPath() or SHGetKnownFolderPath()</li>
<li>Mac OS X and iPhone OS: NSSearchPathForDirectoriesInDomains()</li>
<li>Unix: $HOME environment variable</li>
</ul>
<p>Don't hardcode specific paths or just tack a prefix and suffix on the user's name. Also, try to follow whatever conventions there are for the platform for naming the files.</p>
|
<p>Never, ever store user data in the application folder. It's just a bad idea.</p>
<p>Most operating systems have a $HOME (or %HOME%) environment variable. That would be the first place to look. </p>
<p>If you want to cleanly support multiple operating systems, though, you're going to have to have some OS-specific code for each that figures out exactly where things need to go. (~/Library for Mac OS, ~/.config for GNOME-based systems, %HOME%/Application Data for Windows, etc.).</p>
| 8,122
|
<p>I'm trying to understand how namespaces work in XML. When I have an element like foo:bar, the attributes will often not have namespaces on them. But sometimes they will. Are the attribute in the namespace of the element, even when the default namespace has been declared? Looking over the xsd for xhtml it seems the attributes are part of the schema and should be in the namespace for xhtml, but they are never presented that way...</p>
|
<p>Most of the time, attributes will not be in any namespace. The <a href="http://www.w3.org/TR/REC-xml-names/#defaulting" rel="noreferrer">namespace spec</a> says (<em>emphasis</em> mine):</p>
<blockquote>
<p>A default namespace declaration applies to all unprefixed <em>element</em> names within its scope. Default namespace declarations do <em>not</em> apply directly to <em>attribute</em> names; the interpretation of unprefixed attributes is determined by the element on which they appear.</p>
</blockquote>
<p>There's a reason that most XML vocabularies use non-namespaced attributes:<br>
When your elements have a namespace and those elements have attributes, then there can be no confusion: the attributes belong to your element, which belongs to your namespace. Adding a namespace prefix to the attributes would just make everything more verbose.</p>
<p>So why do namespaced attributes exist?<br>
Because some vocabularies do useful work with mostly attributes, and can do this when mixed in with other vocabularies. The best known example is <a href="http://en.wikipedia.org/wiki/XLink" rel="noreferrer">XLink</a>.</p>
<p>Lastly, W3C XML Schema has an all too easy way (<code><schema attributeFormDefault="qualified"></code>) of declaring your attributes as being in a namespace, forcing you to prefix them in your documents, <em>even</em> when you use a default namespace.</p>
|
<p>Read up at <a href="http://www.w3.org/TR/REC-xml-names/#scoping" rel="nofollow noreferrer">6.1 Namespace Scoping</a> and <a href="http://www.w3.org/TR/REC-xml-names/#defaulting" rel="nofollow noreferrer">6.2 Namespace Defaulting</a> on w3c.</p>
<p>Basically:</p>
<blockquote>
<p>The scope of a namespace declaration declaring a prefix extends from the beginning of the start-tag in which it appears to the end of the corresponding end-tag</p>
</blockquote>
<p>However, the text here doesn't seem to explain if means a is foo:a or the default namespace in the context. I would assume that it does not refer to foo:a, but rather the documents default namespace a. Considering this quote at least:</p>
<blockquote>
<p>Such a namespace declaration applies to all element and attribute names within its scope whose prefix matches that specified in the declaration. </p>
</blockquote>
<p>Ie. the namespace "foo:" only applies to elements prefixed with foo:</p>
| 6,287
|
<p>Can anyone recommend a good (preferably open source) tool for creating WSDL files for some soap web services?</p>
<p>I've tried playing around with some of the eclipse plug ins available and was less than impressed with what I found.</p>
|
<p>As mentioned above, probably the easiest thing to do is use Apache CXF or Apache Axis2 to automatically generate your WSDL for you.</p>
<p>If you have downloaded the Java EE version of Eclipse, you should be able to create a Dynamic Web Project with the Axis2 facets. If you create a simple Java class in the project, you should be able to right-click on it, and choose Web Services->Create Web Service. That should automatically create an Axis2 service for you.</p>
<p>WSDL would then be available from some URL like: <code>http://localhost/axis/{yourservice}?WSDL</code></p>
|
<p>Depends on which language you're working in, but if you're active in Java then I'd recommend looking at <a href="http://cxf.apache.org/" rel="nofollow noreferrer">Apache CXF</a>. It's a pretty solid framework for publishing java code as a SOAP web service. It also includes a tool for directly generating WSDL files: <a href="http://cwiki.apache.org/CXF20DOC/java-to-wsdl.html" rel="nofollow noreferrer">java2wsdl</a></p>
| 9,842
|
<p>All the generated webservice-stubs from our backend have an equals-method similar to this one:</p>
<pre><code>private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof PropertyData)) return false;
PropertyData other = (PropertyData) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.key==null && other.getKey()==null) ||
(this.key!=null &&
this.key.equals(other.getKey()))) &&
((this.value==null && other.getValue()==null) ||
(this.value!=null &&
this.value.equals(other.getValue())));
__equalsCalc = null;
return _equals;
}
</code></pre>
<p>Can someone please explain to me the purpoise of <code>__equalsCalc</code>? I just don't get it. It is not used somewhere else in the class. The way I see it, it is not null exactly during the calculation of the "equality". However the equals is declared <code>synchronized</code>. Therefore only one thread can be in it at any given time.
I can't see, why <code>if (__equalsCalc != null)</code> should ever be true.</p>
<p>Please show me my stupid misunderstanding ;-)</p>
<p>EDIT: I am new to the project and therefore my answer may be wrong. But if I trace it correctly, the method is generated by axis-wsdl2java</p>
|
<p>I suspect it's trying to stop recursion - if something has itself as its key, you don't want it to recurse forever.</p>
<p>However, at that point it uses reference equality for the test, which is possibly not desirable.</p>
<p>What's generating this code? Is it a home-grown system, or a public one? If it's home-grown, is the developer responsible still at the company?</p>
<p>EDIT: Okay, now that we know it's WSDL2Java, the answer is (sort of) in the <a href="https://github.com/apache/axis-axis1-java/blob/master/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaBeanWriter.java" rel="nofollow noreferrer">source code</a>:</p>
<pre><code> // The __equalsCalc field and synchronized method are necessary
// in case the object has direct or indirect references to itself.
</code></pre>
<p>and then:</p>
<pre><code> // Have we been here before ? return true if yes otherwise false
pw.println(" if (__equalsCalc != null) {");
pw.println(" return (__equalsCalc == obj);");
pw.println(" }");
</code></pre>
<p>Not the most explanatory of comments, but at least they show we were on the right track thinking about recursion.</p>
|
<p>The __equalsCal behave as a Cache for the last call to Equals. So, if two calls in the same instance to equals method are invoked with the same parameter the method will be faster</p>
<p>EDIT: Sorry this would be true if the </p>
<pre><code>__equalsCalc = null;
</code></pre>
<p>would not be there, but rechecking your code, probably my answer is not valid.</p>
| 48,021
|
<p>I'm looking for a method to reliably extract the host name from a URL string in Ruby.</p>
<p>e.g.
<a href="http://www.mglenn.com/directory" rel="noreferrer">http://www.mglenn.com/directory</a> = www.mglenn.com
OR
<a href="http://www.mglenn.com?param=x" rel="noreferrer">http://www.mglenn.com?param=x</a> = www.mglenn.com</p>
|
<p>You could try something like this:</p>
<pre><code>require 'uri'
myUri = URI.parse( 'http://www.mglenn.com/directory' )
print myUri.host
# => www.mglenn.com
</code></pre>
|
<pre><code>URI("http://www.mglenn.com/directory").host
</code></pre>
| 35,182
|
<p>I want to create variables inside function from dictionary.</p>
<p>Lets say I have a dictionary</p>
<pre><code>bar = {'a': 1, 'b': 2, 'c': 3}
</code></pre>
<p>and function</p>
<pre><code>def foo():
pass
</code></pre>
<p>What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values</p>
<p>So in the end it should be similar to</p>
<pre><code>def foo():
a = 1
b = 2
c = 3
</code></pre>
<p>Is it possible at all? And if it does, how to do such thing?</p>
|
<p>Your question is not clear.</p>
<p>If you want to "set" said variables when foo is not running, no, you can't. There is no frame object yet to "set" the local variables in.</p>
<p>If you want to do that in the function body, you shouldn't (check the <a href="http://docs.python.org/lib/built-in-funcs.html" rel="nofollow noreferrer">python documentation</a> for locals()).</p>
<p>However, you <em>could</em> do a <code>foo.__dict__.update(bar)</code>, and then you could access those variables even from inside the function as foo.a, foo.b and foo.c. The question is: why do you want to do that, and why isn't a class more suitable for your purposes?</p>
|
<p>Why would you want to do such a thing? Unless you actually do anything with the variables inside the function, a function that just assigns several variables and then discards them is indistinguishable to def foo(): pass (An optimiser would be justified in generating exactly the same bytecode).</p>
<p>If you also want to dynamically append code that uses the values, then you could do this by using exec (though unless this is really user-input code, there are almost certainly better ways to do what you want). eg:</p>
<pre><code>some_code = ' return a+b+c'
exec "def foo():\n " + '\n '.join('%s = %s' for k,v in bar.items()) + '\n' + some_code
</code></pre>
<p>(Note that your code must be indented to the same level.)</p>
<p>On the other hand, if you want to actually assign these values to the function <strong>object</strong> (so you can do foo.a and get 1 - note that your sample code doesn't do this), you can do this by:</p>
<pre><code>for key, val in bar.items():
setattr(foo, key, val)
</code></pre>
| 14,585
|
<p>I’ve built a custom Maven2 plug-in using Ant. I would like to call another maven plug-in in particular the Cargo Maven2 plug-in immediately after the custom Ant plug-in successfully completes. However, I do not want to attach the Cargo plug-in to another goal or phase. Is there a way to have them run consecutively without having to write a batch script? Is there away to have the Custom Ant plug-in call out to the Cargo plug-in?</p>
|
<p>See this discussion: <a href="http://mail-archives.apache.org/mod_mbox/maven-users/200706.mbox/%3C4669508E.1020903@apache.org%3E" rel="nofollow noreferrer">Re: calling plugin in another plugin?</a> According to the Maven developers, this is not the way plugins are supposed to work.</p>
<p>However, there is this interesting comment:</p>
<blockquote>
<p>Plugins/Mojos should be thin wrappers around a library. You'd want to use the library directly.</p>
</blockquote>
<p>Cargo is not only a Maven plugin, it also has a Java API and an <a href="http://cargo.codehaus.org/Ant+support" rel="nofollow noreferrer">Ant task</a>. So you could probably:</p>
<ul>
<li><p>call the Cargo Ant task from your Ant mojo (I think you'll just need the Cargo JARs in your plugin's classpath);</p></li>
<li><p>rewrite your Ant mojo in Java, and invoke the Cargo API (you'd want to look at the sources of the Cargo plugin).</p></li>
</ul>
|
<p>The Ant script that the maven-ant-plugin executes is not really aware of Maven as such; this plugin is designed for backwards compatibility with custom Ant tasks. I cannot think of a clean way of doing what you want though there may be some kind of hack that allows you to do it.</p>
<p>It should also be possible to execute a second instance of Maven from inside Ant, which runs purely the Cargo goal, but in that case you might encounter problems with locked files and the like. The way to do it would be to just use an tag in your Ant script and call the "mvn" executable with the appropriate goals as arguments.</p>
<p>The cleanest way is to simply bind the Cargo goal to a phase of the build, and have that run after Ant is finished. I do not see any disadvantage to that approach - you haven't really stated any specific reasons why you want to avoid it.</p>
| 41,779
|
<p>I have a print I need to make holes in.<br>
I have read some other threads where the answers was in short, "don't, print the holes", and "make sure to make the hole from the top or bottom".<br>
The problem is I need the hole in the side of a print with about 1 mm walls. </p>
<p>The holes I need is to run a USB cable in and a few to hold 3 mm LEDs.<br>
One of the holes needs to be 10 mm. </p>
<p>What is my best option?<br>
I read that there is a risk it cracks, so I was thinking maybe I can use a soldering iron for the smaller holes?<br>
That will melt the plastic and create nice smooth walls, right? Less risk of cracks?<br>
The piece will not be loaded in any way, it's just holdin it's own weight. </p>
<p>I never anticipated that it would be an issue to drill holes in prints. If I had known it I might have tried more to change the print before ordering it.<br>
(I don't have a printer to make a new one with.)</p>
<p><strong>Note:</strong> The part has <em>already</em> been printed. This is a question about post-printing processing, <em>not</em> modelling for a new print.</p>
|
<p>You're going to have to drill those holes. The plastic will melt if you drill too quickly. If at all possible, use a slow speed drill, a hand drill, or wrap a cloth around a drill bit and twist it with your hand. If you go too fast, the part will melt. If you press to hard the part will break.</p>
<p>Once the hole has been drilled you will need to reinforce it with a metal/plastic tube of the required diameter. Press the tube into the hole. I don't know what your wall thickness is, but try to ensure the tube is the same length.</p>
<p>If at all possible you should get flanged tubes like these from mc master car:</p>
<p><a href="https://i.stack.imgur.com/zh0UT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zh0UT.png" alt="Flanged tube insert"></a></p>
<p>The parts with the 1/2 inch inner diameter and 5/8 outer diameter should fit your 10 mm requirement. The rest is up to you. Go to mcmaster.com/inserts scroll down to "Other Inserts" then "Tube and tube fittings".</p>
|
<p>As a follow up on this I wanted to post some pictures of the result with only the soldering iron.<br>
I was soldering some cables and when it was still hot I figured I could give it a go. </p>
<p>The hole is on the underside and in a closed compartment so it's not visible.</p>
<p>Anyways, about 3 mm hole at this point and quite pleased with the result.</p>
<p><a href="https://i.stack.imgur.com/QXfa5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QXfa5.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/noyMb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/noyMb.jpg" alt="enter image description here"></a></p>
| 1,442
|
<p>I am trying to setup tracd for the project I am currently working on.
After creating a password file with the python script given in the <a href="http://trac.edgewall.org/wiki/TracStandalone" rel="noreferrer">site</a> I am trying to start the server with authentication on. But it throws up warning saying No users found in the realm. What actually is a realm - I tried using trac as the value and also tried leaving it empty. I am using Windows XP. I am using Tracd Standalone server.</p>
<p>The Command Line sent was: tracd --port 8000 --auth=My_Test_Project,D:\My_Test_Project\Documents\Trac\digest.txt,Trac D:\My_Test_Project\Documents\Trac</p>
<p>The Warning message was - 'Warning: found no users in realm: trac'</p>
<p>Thanks...</p>
|
<p>Replacing the above said command line with the one bellow helps.</p>
<p>tracd --port 8000 --auth=Trac,D:\My_Test_Project\Documents\Trac\digest.txt,Trac D:\My_Test_Project\Documents\Trac</p>
<p>The string after --auth= should be the environment name and not the project name.</p>
|
<p>The text referred to says that you must specify the realm name as "trac", not "<strong>T</strong>rac", but I have no chance of testing whether that makes any difference, sorry.</p>
| 24,452
|
<p>I'm trying to have the modrewrite rules skip the directory <code>vip</code>. I've tried a number of things as you can see below, but to no avail.</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
#RewriteRule ^vip$ - [PT]
RewriteRule ^vip/.$ - [PT]
#RewriteCond %{REQUEST_URI} !/vip
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>How do I get modrewrite to entirely ignore the <code>/vip/</code> directory so that all requests pass directly to the folder?</p>
<h3>Update:</h3>
<p>As points of clarity:</p>
<ul>
<li>It's hosted on Dreamhost</li>
<li>The folders are within a wordpress directory</li>
<li>the /vip/ folder contains a webdav .htaccess etc (though I dont think this is important</li>
</ul>
|
<p>Try putting this before any other rules.</p>
<pre><code>RewriteRule ^vip - [L,NC]
</code></pre>
<p>It will match any URI beginning <code>vip</code>. </p>
<ul>
<li>The <code>-</code> means do nothing. </li>
<li>The <code>L</code> means this should be last rule; ignore everything following. </li>
<li>The <code>NC</code> means no-case (so "VIP" is also matched).</li>
</ul>
<p>Note that it matches anything <em>beginning</em> <code>vip</code>. The expression <code>^vip$</code> would match <code>vip</code> but not <code>vip/</code> or <code>vip/index.html</code>. The <code>$</code> may have been your downfall. If you really want to do it right, you might want to go with <code>^vip(/|$)</code> so you don't match <code>vip-page.html</code> </p>
|
<p>I'm not sure if I understand your objective, but the following might do what you're after?</p>
<pre><code>RewriteRule ^/vip/(.*)$ /$1?%{QUERY_STRING} [L]
</code></pre>
<p>This will cause a URL such as <a href="http://www.example.com/vip/fred.html" rel="nofollow noreferrer">http://www.example.com/vip/fred.html</a> to be rewritten without the /vip.</p>
| 19,737
|
<p>I've found out how to convert errors into exceptions, and I display them nicely if they aren't caught, but I don't know how to log them in a useful way. Simply writing them to a file won't be useful, will it? And would you risk accessing a database, when you don't know what caused the exception yet?</p>
|
<p>You could use <a href="http://www.php.net/manual/en/function.set-error-handler.php" rel="noreferrer">set_error_handler</a> to set a custom exception to log your errors. I'd personally consider storing them in the database as the default Exception handler's backtrace can provide information on what caused it - this of course won't be possible if the database handler triggered the exception however.</p>
<p>You could also use <a href="http://www.php.net/manual/en/function.error-log.php" rel="noreferrer">error_log</a> to log your errors. It has a choice of message destinations including:</p>
<blockquote>
<p>Quoted from <a href="http://www.php.net/manual/en/function.error-log.php" rel="noreferrer">error_log</a></p>
<ol>
<li>PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option.</li>
<li>Sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used.</li>
<li>Appended to the file destination . A newline is not automatically added to the end of the message string.</li>
</ol>
</blockquote>
<p><em>Edit: Does markdown have a noparse tag for underscores?</em></p>
|
<p>I think it depends a lot of where your error occured. If the DB is down logging it to the DB is no good idea ;)</p>
<p>I use the <a href="http://php.net/syslog" rel="nofollow noreferrer">syslog()</a> function for logging the error, but I have no problems writing it to a file when I'm on a system which has no syslog-support. You can easily set up your system to send you an email or a jabber message using for example <a href="http://www.logwatch.org/" rel="nofollow noreferrer">logwatch</a> or <a href="http://www.johnandcailin.com/blog/john/how-setup-real-time-email-notification-critical-syslog-events" rel="nofollow noreferrer">the standard syslogd</a>.</p>
| 4,069
|
<p>I'm trying to do a very simple INSERT using VB.NET. For some reason I'm getting a SqlException on every insert though. The data is inserted, but still get the following: </p>
<p>Violation of PRIMARY KEY constraint 'PK_User'. Cannot insert duplicate key in object 'dbo.Employee'. The statement has been terminated</p>
<p>When I check in SQL Management Studio, the data is succesfully inserted.</p>
<p>Here is the code where the problem is happening</p>
<pre><code>Try
conn.Open()
Dim insertSQL As String = "insert into Employee(uName, firstName, lastName,
On_Switch, On_Phone) " + "values('" & uName & "', '" & firstName & "', '" _
& lastName & "', '" & onSwitch & "', '" & onPhone & "')"
Dim AddCom As SqlCommand = New SqlCommand(insertSQL, conn)
If (AddCom.ExecuteNonQuery() = 1) Then
lblError.Text = "User Added."
' string urlBack = "../ViewAsset.aspx?DeptID=" + DeptID;
' Response.Redirect(urlBack);
End If
conn.Close()
Catch ex As SqlException
Dim ExMsg As String = ex.Message.ToString()
lblError.Text = ExMsg
</code></pre>
<p>I went back and tested the same code in C# and there is no Exception thrown. It seems to be something small I'm doing in VB, but I'm lost as to what it is.</p>
|
<p>Two theories. Either your code is being executed twice, or there's a trigger on the Employee table that's attempting an insert following the successful insert. (Edit: @Mitchel Sellers is exactly right, if the same code works in c# it's absolutely not a trigger issue.)</p>
<p>My hunch is that your code is being executed twice. Try running with the debugger attached and a breakpoint set on the ExecuteNonQuery - I think you'll find that some other method calls this method multiple times.</p>
<p>@Mitchel Sellers - GOOD CATCH ON THE SQL INJECTION BUG! Parameters, please! </p>
|
<p>As another side note, I noticed that your code could potentially leave a sql connection open. If you're using the .NET 2.0 framework you should use the Using statement. It ensures that connections are closed and disposed even if an exception is thrown. Check this article on MSDN for more detail: <a href="http://msdn.microsoft.com/en-us/library/htd05whh.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/htd05whh.aspx</a>. The other option would be to add the close statement in a Finally block of your try-catch handler.</p>
| 28,979
|
<p>One example is described <strong><a href="http://sujitmanolikar.blogspot.com/2007/07/generic-statemanagedcollection.html" rel="nofollow noreferrer">here</a></strong>. But the author apparently forgot to include the code for download.</p>
<p>Another example is shown <strong><a href="http://blog.spontaneouspublicity.com/child-collections-in-asp-net-custom-controls" rel="nofollow noreferrer">here</a></strong>. However, this one doesn't quite work (as described in comments).</p>
<p>How do you do this correctly?</p>
|
<p>DanHerbert got it. Darn, I spent hours on this too! In the process of trying to answer this question I came up with a simplified generic StateManagedCollection that inherits from the framework's built-in StateManagedCollection, based on the version <a href="http://blog.spontaneouspublicity.com/post/2007/05/Child-Collections-in-AspNet-Custom-Controls.aspx" rel="nofollow noreferrer">here</a>. Maybe you'll find it useful. Full source code of my sample project available <a href="http://files.tomeofwisdom.com/StateMangedExample.zip" rel="nofollow noreferrer">here</a>.</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Specialized;
using System.Security.Permissions;
using System.Web;
using System.Collections.Generic;
using System.Web.UI;
namespace Web
{
public abstract class StateManagedCollection<T> : StateManagedCollection, IList<T>, ICollection<T>, IEnumerable<T>
where T : class, IStateManagedItem, new()
{
protected override object CreateKnownType(int index)
{
return Activator.CreateInstance<T>();
}
protected override Type[] GetKnownTypes()
{
return new Type[] { typeof(T) };
}
protected override void SetDirtyObject(object o)
{
((IStateManagedItem)o).SetDirty();
}
#region IList<T> Members
public int IndexOf(T item)
{
return ((IList)this).IndexOf(item);
}
public void Insert(int index, T item)
{
((IList)this).Insert(index, item);
if (((IStateManager)this).IsTrackingViewState)
{
this.SetDirty();
}
}
public void RemoveAt(int index)
{
((IList)this).RemoveAt(index);
if (((IStateManager)this).IsTrackingViewState)
{
this.SetDirty();
}
}
public T this[int index]
{
get { return (T)this[index]; }
set { this[index] = value; }
}
#endregion
#region ICollection<T> Members
public void Add(T item)
{
((IList)this).Add(item);
this.SetDirty();
}
public bool Contains(T item)
{
return ((IList)this).Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
((IList)this).CopyTo(array, arrayIndex);
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
if (((IList)this).Contains(item))
{
((IList)this).Remove(item);
return true;
}
return false;
}
#endregion
#region IEnumerable<T> Members
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return ((IList)this).GetEnumerator();
}
#endregion
}
}
</code></pre>
|
<p>I have used the code above the provided solution is ok but i was getting exception - "StackOverflow " cool :) the issue is reproducible by adding a few child items in the aspx page and switch to Design view to design view of Visual studio ( Visual Studio just restart and nobody knows what is going on....). </p>
<pre><code> IEnumerator IEnumerable.GetEnumerator()
{
return ((IList)this).GetEnumerator();
}
</code></pre>
<p>So, I guess I figured it out just change the implementation of the above method like this:</p>
<pre><code> IEnumerator IEnumerable.GetEnumerator()
{
// return ((IList)this).GetEnumerator();
return this.GetEnumerator();
}
</code></pre>
<p>Hope this will help someone else like me :) just not to loose few hours to get it work with the designer of VS </p>
| 47,567
|
<p>I'm wondering about the practical use of #undef in C. I'm working through K&R, and am up to the preprocessor. Most of this was material I (more or less) understood, but something on page 90 (second edition) stuck out at me:</p>
<blockquote>
<p>Names may be undefined with <code>#undef</code>,
usually to ensure that a routine is
really a function, not a macro:</p>
<p><code>#undef getchar</code></p>
<p><code>int getchar(void) { ... }</code></p>
</blockquote>
<p>Is this a common practice to defend against someone <code>#define</code>-ing a macro with the same name as your function? Or is this really more of a sample that wouldn't occur in reality? (EG, no one in his right, wrong nor insane mind should be rewriting <code>getchar()</code>, so it shouldn't come up.) With your own function names, do you feel the need to do this? Does that change if you're developing a library for others to use?</p>
|
<h3>What it does</h3>
<p>If you read Plauger's <a href="https://smile.amazon.com/dp/0131315099" rel="nofollow noreferrer">The Standard C Library</a> (1992), you will see that the <code><stdio.h></code> header is allowed to provide <code>getchar()</code> and <code>getc()</code> as function-like macros (with special permission for <code>getc()</code> to evaluate its file pointer argument more than once!). However, even if it provides macros, the implementation is also obliged to provid actual functions that do the same job, primarily so that you can access a function pointer called <code>getchar()</code> or <code>getc()</code> and pass that to other functions.</p>
<p>That is, by doing:</p>
<pre><code>#include <stdio.h>
#undef getchar
extern int some_function(int (*)(void));
int core_function(void)
{
int c = some_function(getchar);
return(c);
}
</code></pre>
<p>As written, the <code>core_function()</code> is pretty meaningless, but it illustrates the point. You can do the same thing with the <code>isxxxx()</code> macros in <code><ctype.h></code> too, for example.</p>
<p>Normally, you don't want to do that - you don't normally want to remove the macro definition. But, when you need the real function, you can get hold of it. People who provide libraries can emulate the functionality of the standard C library to good effect.</p>
<h3>Seldom needed</h3>
<p>Also note that one of the reasons you seldom need to use the explicit <code>#undef</code> is because you can invoke the function instead of the macro by writing:</p>
<pre><code>int c = (getchar)();
</code></pre>
<p>Because the token after <code>getchar</code> is not an <code>(</code>, it is not an invocation of the function-like macro, so it must be a reference to the function. Similarly, the first example above, would compile and run correctly even without the <code>#undef</code>.</p>
<p>If you implement your own function with a macro override, you can use this to good effect, though it might be slightly confusing unless explained.</p>
<pre><code>/* function.h */
…
extern int function(int c);
extern int other_function(int c, FILE *fp);
#define function(c) other_function(c, stdout);
…
</code></pre>
<pre><code>/* function.c */
…
/* Provide function despite macro override */
int (function)(int c)
{
return function(c, stdout);
}
</code></pre>
<p>The function definition line doesn't invoke the macro because the token after <code>function</code> is not <code>(</code>. The <code>return</code> line does invoke the macro.</p>
|
<h3>If a macro can be def'ed, there must be a facility to undef.</h3>
<p>a memory tracker I use defines its own new/delete macros to track file/line information. this macro breaks the SC++L.</p>
<pre><code>#pragma push_macro( "new" )
#undef new
#include <vector>
#pragma pop_macro( "new" )
</code></pre>
<p>Regarding your more specific question: namespaces are often emul;ated in C by prefixing library functions with an identifier.</p>
<p>Blindly undefing macros is going to add confusion, reduce maintainability, and may break things that rely on the original behavior. If you were forced, at least use push/pop to preserve the original behavior everywhere else.</p>
| 26,662
|
<p>There's some object-oriented engineering principle that states something along the lines of "a class should only know about the contracts of the classes that it takes as arguments, or any internal ones it uses."</p>
<p>The counter-example, in C++, is:</p>
<pre><code>Foo::bar( Baz* baz)
{
baz()->blargh()->pants()->soil(); // this is bad, Foo knows about blarghs and pants
}
</code></pre>
<p>Does this principle have a name? Also, the actual principle rather than my paraphrase above would be nice to see.</p>
|
<p>The <a href="http://en.wikipedia.org/wiki/Law_of_Demeter" rel="nofollow noreferrer">law of demeter</a> <sub>thanks to <a href="https://stackoverflow.com/users/20164/jim-burger">Jim Burger</a></sub> says:</p>
<blockquote>
The Law of Demeter (LoD), or Principle of Least Knowledge, is a design guideline for developing software, particularly object-oriented programs. The guideline was invented at Northeastern University towards the end of 1987, and can be succinctly summarized as “Only talk to your immediate friends.” The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents).
</blockquote>
|
<p>That may or may not compile (due to the parentheses after the baz pointer), but your example breaks at least one principle that I can think of. It breaks the Law of Demeter (also called the Law of Parsimony, I believe). The main principles can be found here:
<a href="http://www.lostechies.com/blogs/chad_myers/archive/2008/03/07/pablo-s-topic-of-the-month-march-solid-principles.aspx" rel="nofollow noreferrer">S.O.L.I.D. Principles</a></p>
<p>Aside from these, I'm not sure if there is a specific name for what you're describing. You can look up the Law of Demeter on wikipedia.</p>
| 38,085
|
<p>I am messing around with different PHP logging frameworks. I am currently trying PEAR::Log. I figured that I would use its <code>singleton</code> function to make sure there was only one instance of the class around.</p>
<p>I have a small daemon-like script I wanted to add logging to because it was probably the simplest script in the system to test. This script has several functions. I will probably want to log things inside the functions.</p>
<p>The question I have is how do I best manage this singleton? </p>
<p>To me calling this:</p>
<pre><code>&Log::singleton($handler, $name, $ident, $conf, $maxLevel);
</code></pre>
<p>in every function doesn't seem ideal especially since I already specified all of the options in the initial call. Pear::Log serializes this info, but from what it looks like you still have to provide all of those variables to get the instance.</p>
<p>Another alternative is passing the instance into every function. Again, seems like it's less than ideal.</p>
<p>I suppose you could make the instance a 'global' as well.</p>
<p>What do you in this situation? Are there better solutions? </p>
|
<p>I don't know much about PEAR::Log, but why not create another singleton that wraps/simplifies logging.</p>
<pre><code>class Logger {
private static $log;
private function __construct() { }
public static function init(Log $log) {
self::$log = $log;
}
public static function get() {
return self::$log;
}
}
</code></pre>
<p>Once you initialize <code>Logger</code> with <code>Log</code> instance you can access it via <code>Logger::get</code>. Since dereference is possible in PHP you can then do</p>
<pre><code>Logger::get()->doSomething($foo, $bar);
</code></pre>
|
<blockquote>
<p>Another alternative is passing the instance into every function. Again, seems like its less than ideal.</p>
</blockquote>
<p>Basically you have the choice of passing dependencies per function, per object instance or in one of the global scopes. I find that using the object instance scope usually hits a good balance of flexibility. Generally, you should try to limit the scope of variables as much as possible, so if it makes sense, by all means pass through function parameters.</p>
| 47,390
|
<p>I'm wondering what the best practices are for storing a relational data structure in XML. Particulary, I am wondering about best practices for enforcing node order. For example, say I have three objects: <code>School</code>, <code>Course</code>, and <code>Student</code>, which are defined as follows:</p>
<pre><code>class School
{
List<Course> Courses;
List<Student> Students;
}
class Course
{
string Number;
string Description;
}
class Student
{
string Name;
List<Course> EnrolledIn;
}
</code></pre>
<p>I would store such a data structure in XML like so:</p>
<pre><code><School>
<Courses>
<Course Number="ENGL 101" Description="English I" />
<Course Number="CHEM 102" Description="General Inorganic Chemistry" />
<Course Number="MATH 103" Description="Trigonometry" />
</Courses>
<Students>
<Student Name="Jack">
<EnrolledIn>
<Course Number="CHEM 102" />
<Course Number="MATH 103" />
</EnrolledIn>
</Student>
<Student Name="Jill">
<EnrolledIn>
<Course Number="ENGL 101" />
<Course Number="MATH 103" />
</EnrolledIn>
</Student>
</Students>
</School>
</code></pre>
<p>With the XML ordered this way, I can parse <code>Courses</code> first. Then, when I parse <code>Students</code>, I can look up each <code>Course</code> listed in <code>EnrolledIn</code> (by its <code>Number</code>) in the <code>School.Courses</code> list. This will give me an object reference to add to the <code>EnrolledIn</code> list in <code>Student</code>. If <code>Students</code>, however, comes <em>before</em> <code>Courses</code>, such a lookup to get a object reference is not possible. (Since <code>School.Courses</code> has not yet been populated.)</p>
<p>So what are the best practices for storing relational data in XML?
- Should I enforce that <code>Courses</code> must always come before <code>Students</code>?
- Should I tolerate any ordering and create a stub <code>Course</code> object whenever I encounter one I have not yet seen? (To be expanded when the definition of the <code>Course</code> is eventually reached later.)
- Is there some other way I should be persisting/loading my objects to/from XML? (I am currently implementing <code>Save</code> and <code>Load</code> methods on all my business objects and doing all this manually using <code>System.Xml.XmlDocument</code> and its associated classes.)</p>
<p>I am used to working with relational data out of SQL, but this is my first experience trying to store a non-trivial relational data structure in XML. Any advice you can provide as to how I should proceed would be greatly appreciated.</p>
|
<p>Don't think in SQL or relational when working with XML, because there are no order constraints. </p>
<p>You can however query using XPath to any portion of the XML document at any time. You want the courses first, then "//Courses/Course". You want the students enrollments next, then "//Students/Student/EnrolledIn/Course".</p>
<p>The bottom line being... just because XML is stored in a file, don't get caught thinking all your accesses are serial.</p>
<hr>
<p>I posted a separate question, <a href="https://stackoverflow.com/questions/142010/can-xpath-do-a-foreign-key-lookup-across-two-subtrees-of-an-xml">"Can XPath do a foreign key lookup across two subtrees of an XML?"</a>, in order to clarify my position. The solution shows how you can use XPath to make relational queries against XML data.</p>
|
<p>From experience, XML isn't the best to store relational data. Have you investigated <a href="http://www.yaml.org/" rel="nofollow noreferrer" title="YAML">YAML</a>? Do you have the option?</p>
<p>If you don't, a safe way would be to have a strict DTD for the XML and enforce that way. You could also, as you suggest, keep a hash of objects created. That way if a Student creates a Course you keep that Course around for future updating when the tag is hit.</p>
<p>Also remember you can use XPath queries to access specific nodes directly, so you can enforce parsing of courses first regardless of position in the XML document. (making a more complete answer, thanks to dacracot)</p>
| 17,110
|
<p>I'm looking for the concept to <strong>spawn a process</strong> such that:</p>
<ul>
<li>it has only access to certain libraries/APIs</li>
<li>it cannot acess the file system or only specific parts</li>
<li>it can <strong>do least harm should malicious code run in it</strong></li>
</ul>
<p>This concept is known as sandbox or jail.</p>
<p>It is required to do this <strong>for each major Operating system (Windows, MacOSX and Linux)</strong> and the question is conceptual (as in what to do, <strong>which APIs to use and and what to observe</strong>) rather then language specific.</p>
<h2>answer requirements</h2>
<p>I <strong>really</strong> want to accept an answer and give you 20 points for that. I cannot accept my own answer, and I don't have it yet anyway. So if you <strong>really</strong> want your answer to be accepted, please observe:</p>
<ul>
<li>The answer has to be specific and complete</li>
<li>With specific I mean that it is more then a pointer to some resource on the internet. It has to summarize what the resource says about the topic at least.</li>
<li>It may or may not contain example code, but if it does please write it in C</li>
<li>I cannot accept an answer that is 2/3 complete even if the 2/3 that are there are perfect.</li>
</ul>
<h2>this question FAQ</h2>
<ul>
<li>Is this homework? No.</li>
<li>Why do you ask this like a homework question? If you ask a specific question and you want to get a specific answer, and you know how that answer should look like, even though you don't know <em>the</em> answer, that's the style of question you get.</li>
<li>If you know how it should look like, why do you ask? 1) because I don't know all the answer 2) because on the internet there's no single place that contains all the details to this question in one place. Please also read the stackoverflow FAQ</li>
<li>Why is the main part of your question how to answer this question? Because nobody reads the FAQ.</li>
</ul>
|
<p>Mac OS X has a sandbox facility code-named Seatbelt. The public API for it is documented in the sandbox(7), sandbox_init(3), and related manual pages. The public API is somewhat limited, but the facility itself is very powerful. While the public API only lets you choose from some pre-defined sandboxes (e.g. “All sockets-based networking is prohibited”), you can also use the more powerful underlying implementation which allows you to specify exactly what operating system resources are available via a Scheme-like language. For example, here is an excerpt of the sandbox used for portmap:</p>
<pre><code>(allow process-exec (regex #"^/usr/sbin/portmap$"))
(allow file-read-data file-read-metadata (regex
#"^/etc"
#"^/usr/lib/.*\.dylib$"
#"^/var"
#"^/private/var/db/dyld/"
#"^/dev/urandom$"))
(allow file-write-data (regex
#"^/dev/dtracehelper$"))
</code></pre>
<p>You can see many sandboxes used by the system in /usr/share/sandbox. It is easy to experiment with sandboxes by using the sandbox-exec(1) command.</p>
<p>For Windows, you may want to have a look at <a href="http://media.blackhat.com/bh-usa-07/video/2007_BlackHat_Vegas-V11-LeBlanc-Practical_Sandboxing.mp4" rel="noreferrer">David LeBlanc’s “Practical Sandboxing” talk given at Black Hat USA 2007</a>. Windows has no built-in sandboxing technology per se, so the techniques described leverage an incomplete mechanism introduced with Windows 2000 called SAFER. By using restricted tokens, one can create a process that has limited access to operating system resources.</p>
<p>For Linux, you might investigate the complicated SELinux mechanism:
<a href="http://www.nsa.gov/selinux/" rel="noreferrer">SELinux home</a>,
<a href="http://www.lurking-grue.org/gettingstarted_newselinuxHOWTO.html" rel="noreferrer">a HOWTO</a>. It is used by Red Hat, for example, to harden some system services in some of their products.</p>
|
<p>I'm not an expert on the topic, but i think the standard answer for linux is to define a SeLinux policy with the right capabilities for the process. </p>
| 16,444
|
<p>I know what PermGen is, what it's used for, why it fails, how to increase it etc.</p>
<p>What I don't know is what PermGen actually stands for. Permanent... Gen... something?</p>
<p>Does anyone know what PermGen actually stands for?</p>
|
<p>Permanent Generation. Details are of course implementation specific.</p>
<p>Briefly, it contains the Java objects associated with classes and interned strings. In Sun's client implementation with sharing on, <code>classes.jsa</code> is memory mapped to form the initial data, with about half read-only and half copy-on-write.</p>
<p>Java objects that are merely old are kept in the Tenured Generation.</p>
|
<p>Permgen stands for Permanent Generation. It is one of the JVM memory areas. It's part of Heap with fixed size by using a flag called MaxPermSize.</p>
<p><strong><em>Why the name "PermGen" ?</em></strong></p>
<p>This permgen was named in early days of Java. Permgen mains keeps all the meta data of loaded classes. But the problem is that once a class is loaded it'll remain in the JVM till JVM shutdown. So name permgen is opt for that. But later, dynamic loading of classes came into picture but name was not changed. But with <strong>Java 8</strong>, they have addressed that issue as well. Now <strong>permagen</strong> was renamed as <strong>MetaSpace</strong> with dynamic memory size.</p>
| 41,235
|
<p>I have a Java program that uses Hibernate and MySQL to store a lot of tracing data about the use of the Eclipse IDE. This data contains a lot of strings such as method names, directories, perspective name, etc. </p>
<p>For example, an event object (which is then reflected in a record) can specify the source file and the current method, the user name, etc. Obviously, string data can repeat itself. </p>
<p>As long as it's in memory, much of it is internalized so all repeated string instances point to the same object (I make sure of that). However, with @Basic (I use annotations), Hibernate maps it into a VARCHAR(255), which means a lot of wasted space.</p>
<p>If I was coding the SQL myself, I could have replaced the VARCHAR with an index to a manually-managed string lookup table and saved the space (at the cost of extra lookups). </p>
<p>Is there some way to get Hibernate to do this for me? I'm willing to pay the performance hit for the space.</p>
|
<p>Building on sblundy's answer, you could probably get away with something like:</p>
<pre><code>class Foo {
// client code uses this to get the value... ignored by Hibernate
@Transient
public String getString() {
return getStringHolder().getString();
}
public StringHolder getStringHolder() {...}
}
</code></pre>
<p>At least then the client code wouldn't necessarily have to be aware of the change. I don't know if it'd be worth the trouble, though.</p>
|
<p>I suspect you'll need a string holder object and then make sure all these objects refer to that. </p>
<pre><code>class StringHolder {
private Long id;
private String string;
public StringHolder() {/* Not sure if this is necessary */}
public StringHolder(String string) {
this.string = string;
}
public void getString() {
return this.string;
}
}
</code></pre>
| 17,441
|
<p>A method I work with that is called tens of thousands of times started throwing exceptions recently. In most debugging circumstances I would set a breakpoint at the top of this method and run through until I reach the call I'm interested in with a parameter value that triggers the exception. In this case that would be impractical, so I tried setting a breakpoint with a condition that will only break when that parameter value appears. I created a breakpoint at the position indicated below and gave it a condition <code>str == "OffendingValue"</code>. </p>
<pre><code>class Foo
{
// Bar() is called many, many times
void Bar(string str)
{
try
{
// Breakpoint inserted here
...
}
catch (Exception ex)
{
...
}
}
}
</code></pre>
<p>To my surprise, doing this caused Visual Studio and my application to stop functioning in Debug mode. My application started and output some simple logging messages but then stopped responding entirely. Thinking Visual Studio might just be performing a little slower due to the extra work it has to do to monitor the breakpoint condition, I stepped away from my desk for 15 mintues to give it some time to run. When I returned there was no change. I can reproduce the condition by deleting the breakpoint and recreating it with the same condition. Strangest of all, the Break All debugging command, which will usually break program execution on the statement that's currently execting whether it's a breakpoint or not, does nothing at all when I have this problematic breakpoint enabled. </p>
<p>Has anyone encountered similar behavior with Visual Studio breakpoint conditions? I am able to use Hit Count conditions without problem. </p>
|
<p>Anytime that I have tried to use conditional breakpoints in Visual Studio I've had the same problem. The debugger runs so slowly that it becomes useless. Instead I end up temporarily adding an if statement to the code and adding my breakpoint inside of that. This isn't as convenient, but the code executes at a normal pace and it does get the job done.</p>
<pre><code>class Foo
{
// Bar() is called many, many times
void Bar(string str)
{
try
{
if(str == "condition")
{
int i = 0; // Breakpoint inserted here
}
...
}
catch (Exception ex)
{
...
}
}
}
</code></pre>
|
<p>I wonder if you are getting a stack overflow. Does VS track all the values for str or anything to do with each state of Bar? If so, the thousands of copies might add up.</p>
<p>I wonder if you could eliminate the problem monitoring the value via a global variable instead, rather than one within the function.</p>
| 36,706
|
<p>Is there an online resource somewhere that maintains statistics on the install-base of Java including JRE version information? If not, is there any recent report that has some numbers?</p>
<p>I'm particularly interested in Windows users, but all other OS's are welcome too.</p>
|
<p>Take a look at <a href="http://www.pixel-technology.com/freeware/tessnet2/" rel="noreferrer">tessnet</a></p>
|
<p>Disclaimer: I work for Atalasoft</p>
<p>Our <a href="http://www.atalasoft.com/products/dotimage/ocr" rel="nofollow noreferrer">OCR module supports Tesseract</a> and if that proves to not be good enough, you can upgrade to a better engine and just change one line of code (we provide a common interface to multiple OCR engines).</p>
| 5,026
|
<p>I have a website which uses themes. Depending on the url (if it is A.something.com or B.something.com, where A and B represent clients), I will load a different theme. The intention is to use one codebase for different clients. I have an app_themes folder, several themes inside, for different clients, and different CSS files for each theme (for business reasons the CSS file is the same for each theme, but duplicated). So my code looks like this:</p>
<p>Public Overrides Property StyleSheetTheme() As String</p>
<pre><code> Get
Dim myHost As String = Request.Url.Host
Return myHost
End Get
Set(ByVal value As String)
End Set
End Property
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
If Request.Url.Host.Contains("Savills") Then
Page.Theme = "Savills"
ElseIf Request.Url.Host.Contains("localhost") Then
Page.Theme = "localhost"
ElseIf Request.Url.Host.Contains("test.concepglobal.com") Then
Page.Theme = "test.concepglobal.com"
ElseIf Request.Url.Host.Contains("concepglobal") Then
Page.Theme = "concepglobal"
End If
End Sub
</code></pre>
<p>My app_themes folder structure:</p>
<p>App_Themes:</p>
<p>localhost:</p>
<p>Default.css</p>
<p>Savills</p>
<p>Savills.css</p>
<p>However, everytime I load the site, the css is not picked up. So I don't get the h1 style I designed in the css (it is in there), but only the graphics specified in the aspx page.</p>
<p>My source when running the site:</p>
<p> (loading the site at that url).</p>
<p>Confusingly, there is another link to the same css:</p>
<p></p>
<p>What am I doing wrong?</p>
<p>Thanks </p>
|
<p>Is this occurring only when you run the code from within Visual Studio? </p>
<p>When running in ASP.Net Development Server, the styles in App_Themes won't be used on any unauthenticated page (such as Login.aspx or ForgotPassword.aspx). That's because the user doesn't have browse permissions on that folder yet, or the App_Themes folder lacks browsing permissions. Apparently, IIS handles this but Cassini doesn't.</p>
<p>Try adding this to web.config to let Themes and styles work before authentication.</p>
<pre><code><location path="App_Themes">
<system.web>
<authorization>
<allow users="?" />
</authorization>
</system.web>
</location>
</code></pre>
<p>Or, if possible, switch to running the app on IIS on your machine. </p>
|
<p>Instead of doing this though code, you can specify the theme used by the application (or a folder) through your web.config:</p>
<pre><code><system.web>
<pages theme="concepglobal"></pages>
</system.web>
</code></pre>
<p>This assumes you have different web.config files for each client.</p>
| 33,277
|
<p>While building a small experimental HTTP server, I need to implement the persistent connection feature of HTTP 1.1 (and the pipelining feature).
How do I test it?
Using a browser like Firefox gives me little or no control, and it's hard to check.
Any ideas?</p>
<p>Thanks</p>
|
<p>curl(<a href="http://curl.haxx.se/" rel="nofollow noreferrer">http://curl.haxx.se/</a>) -- gives you very good control over GET/POST and many other attributes.</p>
<p>curl also comes with libcurl so that you can do things programatically.</p>
<p>Perl and python(urllib or urllib2 ) will help you get there.</p>
|
<p>Netcat. You can type in the request(s) and see the response(s) from the server. If you know the HTTP protocol, it's not a problem at all. In fact, it's better than curl or other higher-level libraries/applications, since here you can send whatever you like (malformed requests) and test the corner cases in your server's behavior. You can also redirect the input (and output), which is especially useful when you want to test HTTP/1.1 request pipelining. Keep in mind that sending CRLFs in Unix using Netcat is harder than on Windows, where you can simply press Enter.</p>
| 25,883
|
<p>I am having a problem with deploying a ASP.NET V2 web application to our deployment environment and am having trouble with the sql server setup .</p>
<p>When I run the website I get a Login failed for user 'MOETP\MOERSVPWLG$'. error when it tries to connect to the database.</p>
<p>This seems to be the network service user which is the behaviour I want from the application but I don't seem to be able to allow the network service user to access the database.</p>
<p>Some details about the setup. IIS 6 and SQL Server 2005 are both setup on the same server in the deployment environment. The only change from the test setup I made is to point the database connection string to the new live database and of course copy everything over. </p>
<p>My assumption at this point is that there is something that needs to be done to the SQL server setup to allow connections from asp.net. But I can't see what it could be.</p>
<p>Any Ideas?</p>
|
<p>It sounds like you're able to connect to the database alright and you're using integrated windows authentication.</p>
<p>With integrated windows authentication your connection to your database is going to use whatever your application pool user identity is using. You have to make sure that the user identity that asp.net is using is on the database server.</p>
|
<p>Make sure there is a login created for the user you are trying to log in as on the sql server.</p>
| 12,337
|
<p>Here's a curious one. I have a class A. It has an item of class B, which I want to initialize in the constructor of A using an initializer list, like so:</p>
<pre><code>class A {
public:
A(const B& b): mB(b) { };
private:
B mB;
};
</code></pre>
<p>Is there a way to catch exceptions that might be thrown by mB's copy-constructor while still using the initializer list method? Or would I have to initialize mB within the constructor's braces in order to have a try/catch?</p>
|
<p>Have a read of <a href="http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/" rel="noreferrer">http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/</a>)</p>
<p>Edit: After more digging, these are called "Function try blocks".</p>
<p>I confess I didn't know this either until I went looking. You learn something every day! I don't know if this is an indictment of how little I get to use C++ these days, my lack of C++ knowledge, or the often Byzantine features that litter the language. Ah well - I still like it :)</p>
<p>To ensure people don't have to jump to another site, the syntax of a function try block for constructors turns out to be:</p>
<pre><code>C::C()
try : init1(), ..., initn()
{
// Constructor
}
catch(...)
{
// Handle exception
}
</code></pre>
|
<p>I don't see how you'd do that with initializer-list syntax, but I'm also a bit sceptical that you'll be able to do anything useful by catching the exception in your constructor. It depends on the design of the classes, obviously, but in what case are you going to fail to create "mB", and still have a useful "A" object? </p>
<p>You might as well let the exception percolate up, and handle it wherever the constructor for A is being called.</p>
| 19,368
|
<p>It appears that each app has access to its own config settings, which could be kept after app be shutdown. I am wondering whether one app's config setting could be accessed from other app. </p>
<p>Should I save sensitive data like password to the app config?</p>
<p>Is there some better way?</p>
|
<p>The Keychain is where passwords or other sensitive information should be saved.</p>
|
<p>Buzz Andersen has code that will get and set Keychain passwords correctly on both the simulator and on the iPhone: <a href="http://log.scifihifi.com/post/55837387/simple-iphone-keychain-code" rel="nofollow noreferrer">SFHFKeychainUtils</a>.</p>
| 46,019
|
<p>We have an SVN repository running on a Windows server, and I want to link internal documentation, feature changes, bugs and so on to code changes.</p>
<p>We've found WebSVN to be amazingly slow - the repository is too large for it (I think).</p>
<p>The team using it is primarily coding in C#, and while some have experience with other languages I'd really like a tool anyone on the team can maintain.</p>
<p>Most of the tools I've seen are based on PHP, Java, Python, etc. All languages the team could learn, but I'd rather something that uses the skills we already have.</p>
<p>Can you recommend a good web-based repository browser for SVN, ideally one that uses ASP.NET, <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL Server</a> and that runs on <a href="http://en.wikipedia.org/wiki/Internet_Information_Services" rel="nofollow noreferrer">IIS</a>?</p>
|
<p>Have a look at <a href="http://warehouseapp.com" rel="nofollow noreferrer">http://warehouseapp.com</a></p>
<p>It's Mongrel/Ruby/MySQL stack (should work on Windows though)</p>
<blockquote>
<p>but I'm looking to avoid installing
MySQL and Ruby on the server.</p>
</blockquote>
<p>I know (also using C# stack myself), but self-hosted web-based SVN client market is such a small niche that even offering in different language could be considered good enough. MySQL doesn't bite and installation of Ruby is pretty much x-copy command. I understand why you don't want to spoil your server with additional software though, but if are OK to host your SVN repositories with third-party, you get a nice web-based interface without maintenance hassles.</p>
<p>I'm using <a href="http://unfuddled.com" rel="nofollow noreferrer">http://unfuddled.com</a> (they also have some basic API to hook up on if needed).</p>
<blockquote>
<p>Not to promote reinventing the wheel,
but I originally wrote my own web SVN
browser by using the <strong>svn log --xml</strong>
command</p>
</blockquote>
<p>This is actually good idea. I'm also parsing some XML formatted output during my automated build process, but creating our own full-blown SVN browser is kind of overkill because now you have to maintain not one primary project, but also the tool. But then again, we, programmers, love to create tools that will make working on our primary projects easier.</p>
<p><strong>ASP.NET SVN browser sounds like promising open-source idea, anybody willing to start work on it? I would contribute.</strong></p>
|
<p>Not web-based but if your team is using TortoiseSVN there's a great repository browser there. Just right click on your local checkout and select TortoiseSVN / Repo-Browser.</p>
| 3,214
|
<p>I have an iframe inside my main page. There is a modalpopup inside the iframe page. So when the modalpopup is shown, the parent of the modalpopup is the iframe body and the main page parent body. Thus the overlay only covers the iframe and not the entire page.</p>
<p>I tried moving the modalpopup from the iframe to the parent windows body element (or any other element inside the parents body) using jQuery. I am getting an invalid argument error.</p>
<p>How do I show a modalpopup from an page inside iframe and it should cover the entire document, parent document as well?</p>
<p><strong>Update:</strong> </p>
<p>Since few users are interested in achieving the same behavior .. here is the workaround</p>
<p>The best workaround that I would suggest would be to have the modalpopup in the main page .. and then invoke it from the iframe .. say something like this ..</p>
<pre><code>/* function in the main(parent) page */
var _onMyModalPopupHide = null;
function pageLoad(){
// would be called by ScriptManager when page loads
// add the callback that will be called when the modalpopup is closed
$find('MyModalPopupBehaviorID').add_hidden(onMyModalPopupHide);
}
// will be invoked from the iframe to show the popup
function ShowMyModalPopup(callback) {
_onMyModalPopupHide = callback;
$find('MyModalPopupBehaviorID').show();
}
/* this function would be called when the modal popup is closed */
function onMyModalPopupHide(){
if (typeof(_onMyModalPopupHide) === "function") {
// fire the callback function
_onMyModalPopupHide.call(this);
}
}
/* functions in the page loaded in the iframe */
function ShowPopup(){
if(typeof(window.parent.ShowMyModalPopup) === "function") {
window.parent.ShowMyModalPopup.apply(this, [OnPopupClosed]);
}
}
// will be invoked from the parent page .. after the popup is closed
function OnPopupClosed(){
// do something after the modal popup is closed
}
</code></pre>
<p>Hope it helps</p>
|
<p>If you're using the iframe simply for scrollable content you might consider a styled div with <strong>overflow: auto</strong> or <strong>scroll</strong>, instead.</p>
<p>A set up such as this makes it easier to modify the appearance of the entire page since you're not working with multiple documents that each essentially have their own window space inside the page. You can bypass some of the cross-frame communication and it may be easier to keep the information in sync if you need to do that.</p>
<p>This may not be suitable for all situations and may require ajax (or modifying the dom with javascript) to change the div contents instead of just loading a different document in the iframe. Also, some older mobile browsers such as Android Froyo builds don't handle scrollable divs well.</p>
|
<p>You answered your own question in your update. The modal dialog needs to live on the parent page and invoked from the iframe. Your only other option is to use a scrolling div instead of an iframe. </p>
| 37,786
|
<p>I'm having a problem dynamically adding columns to a GridView. I need to change the layout -- i.e. the included columns -- based on the value in a DropDownList. When the user changes the selection in this list, I need to remove all but the first column and dynamically add additional columns based on the selection.</p>
<p>I have only one column defined in my markup -- column 0, a template column, in which I declare a Select link and another application specific LinkButton. That column needs to always be there. When the ListBoxSelection is made, I remove all but the first column and then re-add the desired columns (in this sample, I've simplified it to always add a "Title" column). Here is a portion of the code:</p>
<pre><code>RemoveVariableColumnsFromGrid();
BoundField b = new BoundField();
b.DataField = "Title";
this.gvPrimaryListView.Columns.Add(b);
this.gvPrimaryListView.DataBind();
private void RemoveVariableColumnsFromGrid() {
int ColCount = this.gvPrimaryListView.Columns.Count;
//Leave column 0 -- our select and view template column
while (ColCount > 1) {
this.gvPrimaryListView.Columns.RemoveAt(ColCount - 1);
--ColCount;
}
}
</code></pre>
<p>The first time this code runs through, I see both the static column and the dynamically added "Title" column. However, the next time a selection is made, the first column is generated empty (nothing in it). I see the title column, and I see the first column to its left -- but there's nothing generated within it. In the debugger, I can see that gvPrimaryListView does indeed still have two columns and the first one (index 0) is indeed a template column. In fact, the column even retains it's width which is set as 165px in the markup below (for debugging purposes).</p>
<p>Any ideas?</p>
<pre><code><asp:GridView ID="gvPrimaryListView" runat="server" Width="100%" AutoGenerateColumns="false"
DataKeyNames="Document_ID" EnableViewState="true" DataSourceID="odsPrimaryDataSource"
AllowPaging="true" AllowSorting="true" PageSize="10" OnPageIndexChanging="activeListView_PageIndexChanging"
AutoGenerateSelectButton="False" OnSelectedIndexChanged="activeListView_SelectedIndexChanged"
Visible="true" OnRowDataBound="CtlDocList_RowDataBound" Font-Size="8pt" Font-Names="Helvetica">
<Columns>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton EnableTheming="false" ID="CtlSelectDocRowBtn" runat="server" Text="Select"
CommandName="Select" CssClass="gridbutton" OnClick="RowSelectBtn_Click" />
<asp:ImageButton EnableTheming="false" ID="DocViewBtn" runat="server" ImageUrl="../../images/ViewDoc3.png"
CssClass="gridbutton" CommandName="Select" OnClick="DocViewBtn_Click" />
</ItemTemplate>
<ItemStyle Width="165px" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<asp:Label ID="Label6" runat="server" Text="No rows found." SkinID="LabelHeader"></asp:Label>
</EmptyDataTemplate>
</asp:GridView>
</code></pre>
<hr>
<p>Just some additional information.</p>
<p>It has nothing to do with the fact that it is the first column but everything to do with the fact that it is a TemplateField. If I put a normal column to the left (in the markup) and shift the TemplateField column to the right, the first column renders fine, and the (now second) TemplateField column disappears.</p>
<p>Another strange thing -- the problem doesn't happen the first postback -- OR THE SECOND -- but it starts on the third postback and then continues for subsequent postbacks. I'm stumped.</p>
|
<p>I recently conquered silmilar issues with dynamic columns in gridviews, perhaps this will help. </p>
<p>First turn the viewstate off<br>
Second add the columns programatically in a function fired in the oninit event<br>
Lastly I used the following helper class to cause the checkboxes to instantiate when the RowDataBound event kicked off. Yes some of it is hard coded.</p>
<p>Heck here is all the code. Have at it :) Warrenty as is, blah blah blah...</p>
<p>Finally since I am just getting my feet wet DotNet any tips would be appreciated [IE don't rip me too much :) ]. And yes 'borrowed' the initial code from the web somewhere, sorry I cant remember off the top of my head :(</p>
<p>-- Fire this off in protected override void OnInit</p>
<pre><code> private void GridViewProject_AddColumns()
{
DataSet dsDataSet = new DataSet();
TemplateField templateField = null;
try
{
StoredProcedure sp = new StoredProcedure("ExpenseReportItemType_GetList", "INTRANETWEBDB", Context.User.Identity.Name);
dsDataSet = sp.GetDataSet();
if (sp.RC != 0 && sp.RC != 3000)
{
labelMessage.Text = sp.ErrorMessage;
}
int iIndex = 0;
int iCount = dsDataSet.Tables[0].Rows.Count;
string strCategoryID = "";
string strCategoryName = "";
iStaticColumnCount = GridViewProject.Columns.Count;
// Insert all columns immediatly to the left of the LAST column
while (iIndex < iCount)
{
strCategoryName = dsDataSet.Tables[0].Rows[iIndex]["CategoryName"].ToString();
strCategoryID = dsDataSet.Tables[0].Rows[iIndex]["CategoryID"].ToString();
templateField = new TemplateField();
templateField.HeaderTemplate = new GridViewTemplateExternal(DataControlRowType.Header, strCategoryName, strCategoryID);
templateField.ItemTemplate = new GridViewTemplateExternal(DataControlRowType.DataRow, strCategoryName, strCategoryID);
templateField.FooterTemplate = new GridViewTemplateExternal(DataControlRowType.Footer, strCategoryName, strCategoryID);
// Have to decriment iStaticColumnCount to insert dynamic columns BEFORE the edit row
GridViewProject.Columns.Insert((iIndex + (iStaticColumnCount-1)), templateField);
iIndex++;
}
iFinalColumnCount = GridViewProject.Columns.Count;
iERPEditColumnIndex = (iFinalColumnCount - 1); // iIndex is zero based, Count is not
}
catch (Exception exception)
{
labelMessage.Text = exception.Message;
}
}
</code></pre>
<p>-- Helper Class</p>
<pre><code>public class GridViewTemplateExternal : System.Web.UI.ITemplate
{
#region Fields
public DataControlRowType DataRowType;
private string strCategoryID;
private string strColumnName;
#endregion
#region Constructor
public GridViewTemplateExternal(DataControlRowType type, string ColumnName, string CategoryID)
{
DataRowType = type; // Header, DataRow,
strColumnName = ColumnName; // Header name
strCategoryID = CategoryID;
}
#endregion
#region Methods
public void InstantiateIn(System.Web.UI.Control container)
{
switch (DataRowType)
{
case DataControlRowType.Header:
// build the header for this column
Label labelHeader = new Label();
labelHeader.Text = "<b>" + strColumnName + "</b>";
// All CheckBoxes "Look Up" to the header row for this information
labelHeader.Attributes["ERICategoryID"] = strCategoryID;
labelHeader.Style["writing-mode"] = "tb-rl";
labelHeader.Style["filter"] = "flipv fliph";
container.Controls.Add(labelHeader);
break;
case DataControlRowType.DataRow:
CheckBox checkboxAllowedRow = new CheckBox();
checkboxAllowedRow.Enabled = false;
checkboxAllowedRow.DataBinding += new EventHandler(this.CheckBox_DataBinding);
container.Controls.Add(checkboxAllowedRow);
break;
case DataControlRowType.Footer:
// No data handling for the footer addition row
CheckBox checkboxAllowedFooter = new CheckBox();
container.Controls.Add(checkboxAllowedFooter);
break;
default:
break;
}
}
public void CheckBox_DataBinding(Object sender, EventArgs e)
{
CheckBox checkboxAllowed = (CheckBox)sender;// get the control that raised this event
GridViewRow row = (GridViewRow)checkboxAllowed.NamingContainer;// get the containing row
string RawValue = DataBinder.Eval(row.DataItem, strColumnName).ToString();
if (RawValue.ToUpper() == "TRUE")
{
checkboxAllowed.Checked = true;
}
else
{
checkboxAllowed.Checked = false;
}
}
#endregion
}
</code></pre>
|
<p>I found this little nugget in the documentation, under the DataControlFieldCollection Class. </p>
<p><em>If you are using the GridView or DetailsView control, the DataControlField objects that are automatically created (for example, when the AutoGenerateColumns property is true) are not stored in the publicly accessible fields collection. You can only access and manipulate DataControlField objects that are not automatically generated.</em></p>
<p>I guess the answer is to do all of your column manipulation in code, and then your approach should work fine.</p>
| 29,079
|
<p>I'm coming from a .net background and want to know the accepted way of creating a method that returns a boolean and modifies a string that was passed in via parameter. I understand Strings are immutable in Java so the below snippet will always produce an empty string. I am constrained to return boolean only. Exceptions can't be thrown. If I need to wrap the String class in, say, a StringHolder, what package could I find this in.</p>
<pre><code>public static void DoStuff()
{
String msg = "";
if (GetMessage(msg))
{
System.out.println(msg);
}
}
</code></pre>
|
<p>Use a java.lang.StringBuilder - basically a mutable String. However, it would be safer and more "Java style" to return the modified String.</p>
|
<p><code>
public boolean doStuff(String msg)
{
boolean boolTest = false;
msg += "Appending something to msg";
int msgLength = msg.length();
if ( msgLength > 80 )
{
boolTest = true;
return boolTest;
}
return boolTest;
}
</code></p>
<p>Is this kind of what you're looking for? I'm assuming the boolean test is something like testing if the changed message is too long for a display (greater than 80 length) or something similar, and that you don't need to call another method to change the message string inside of doStuff(). </p>
<p>Could be completely off-base here, though. :-)</p>
| 44,551
|
<p>As of SQL Server 2005, you used to be able to open a flat file in SQL Management Studio off the right click menu for any database table. Once opened, you could add or update records right there in the grid.</p>
<p>Now that SQL Server 2008 is out, Microsoft has hidden that feature, at least from the right-click menu.</p>
<p>Where did it go?</p>
|
<p>It's replaced by "Edit Top 200 Rows". You can change that command in the Tools > Options > SQL Server Object Explorer > Commands.</p>
<p>But once you right-click a table, choose "Edit Top 200 Rows", hunt on the toolbar for a button called "Show SQL Pane". From here you can edit the query so the grid shows a subset of the data that you want.</p>
<p>They did this because people were accidentally opening huge tables with the old Open Table command. This method seems to work pretty well, though in general I find that the 2008 version is pretty wonky when talking to 2005 databases, but that's another matter....</p>
|
<p>You could sett the default value of "Edit Top 200 Rows" too "0"</p>
<p>In the Tools Menu -> Options... under SQL server Object Explorer\Table and view options\Value Edit Top Rows Command. Change the default value 200 too "0".</p>
<p>You should now have the option "Edit All Rows" instead of "Edit Top 200 Rows" as a default and if you know it is a laaarge table use the "Select Top 1000 Rows" as a rewiew of the table.</p>
| 46,733
|
<p>I'm currently using <code>.resx</code> files to manage my server side resources for .NET.</p>
<p>the application that I am dealing with also allows developers to plugin JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings? </p>
<p>Ideally, I would like to store the strings in the <code>.resx</code> files to keep them with the rest of the localized resources.</p>
<p>I'm open to suggestions.</p>
|
<p>A basic JavaScript object is an associative array, so it can easily be used to store key/value pairs. So using <a href="http://www.json.org" rel="noreferrer">JSON</a>, you could create an object for each string to be localized like this:</p>
<pre><code>var localizedStrings={
confirmMessage:{
'en/US':'Are you sure?',
'fr/FR':'Est-ce que vous êtes certain?',
...
},
...
}
</code></pre>
<p>Then you could get the locale version of each string like this:</p>
<pre><code>var locale='en/US';
var confirm=localizedStrings['confirmMessage'][locale];
</code></pre>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/bb398935.aspx" rel="nofollow noreferrer"><code>MSDN</code> way of doing it</a>, basically is:</p>
<blockquote>
<p>You create a separate script file for each supported language and culture. In each script file, you include an object in JSON format that contains the localized resources values for that language and culture.</p>
</blockquote>
<p>I can't tell you the best solution for your question, but IMHO this is the worst way of doing it. At least now you know how NOT to do it.</p>
| 12,959
|
<p>When debugging my VS2005 project, I get the following error when I attempt to step into the function that returns the <em>vScenarioDescriptions</em> local variable it's struggling with...</p>
<p><em><a href="http://people.ict.usc.edu/~crotchett/images/symbolnotdefined.JPG" rel="nofollow noreferrer">image no longer available http://people.ict.usc.edu/~crotchett/images/symbolnotdefined.JPG</a></em></p>
<p>As I continue to walk through the code and step into functions, it appears I'm getting this error other local variables as well. Any ideas?</p>
<p>Thanks in advance for your help!</p>
|
<p>Is the module compiled with optimizations turned on? </p>
<p>If so, the <code>vScenarioDescription</code> may not actually not actually exist in memory. In VS2008 I don't get a messagebox error, the variable simply doesn't show up in the 'Locals' window, and if I try to watch it, the Watch windows says:</p>
<blockquote>
<p>CXX0017: Error: symbol "name" not found</p>
</blockquote>
<p>I don't have VS2005 installed anymore so I don't know if it pops up a messagebox like you're seeing or behaves like VS2008.</p>
|
<p>It might be a namespace issue. Try adding <code>namespace::</code> before your symbol in the debugger watch window, if the symbols you're trying to watch are inside a namespace.</p>
| 44,010
|
<p>I have a solution in Visual Studio 2005(professional Edition) which in turn has 8 projects.I am facing a problem that even after i set the Command Arguments in the Project settings of the relevant project, it doesnt accept those command line arguments and it shows argc = 1, inspite of me giving more than 1 command arguments. Tried making the settings of this Solution similar to a working solution, but no success.
Any pointers?</p>
<p>-Ajit.</p>
|
<p>Hmm.. Are you sure the specified project is set as the start project (right click > set as startup project) ??</p>
<p>Oh, and obviously you need to be in the correct configuration mode ^_^</p>
<p>(Notice it can be changed to <em>debug | build | all configurations</em> )</p>
|
<p>Are you sure you are setting the command arguments on the same configuration (Debug|Release) you are debugging? As far as I remember command arguments are per configuration.</p>
| 4,956
|
<p>I am making a game in C++ and am having problems with my derived class. I have a base class called GameScreen which has a vitrual void draw() function with no statements. I also have a derived class called MenuScreen which also has a virtual void draw() function and a derived class from MenuScreen called TestMenu which also has a void draw() function. In my program I have a list of GameScreens that I have a GameScreen iterator pass through calling each GameScreens draw() function.</p>
<p>The issue is that I have placed a TestMenu object on the GameScreen list. Instead of the iterator calling the draw() function of TestMenu it is calling the draw() function of the GameScreen class. Does anyone know how I could call the draw() function of TestMenu instead of the one in GameScreen.</p>
<p>Here is the function:</p>
<pre><code>// Tell each screen to draw itself.
//gsElement is a GameScreen iterator
//gsScreens is a list of type GameScreen
void Draw()
{
for (gsElement = gsScreens.begin(); gsElement != gsScreens.end(); gsElement++)
{
/*if (gsElement->ssState == Hidden)
continue;*/
gsElement->Draw();
}
}
</code></pre>
<p>Here are a copy of my classes:</p>
<pre><code>class GameScreen {
public:
string strName;
bool bIsPopup;
bool bOtherScreenHasFocus;
ScreenState ssState;
//ScreenManager smScreenManager;
GameScreen(string strName){
this->strName = strName;
}
//Determine if the screen should be drawn or not
bool IsActive(){
return !bOtherScreenHasFocus &&
(ssState == Active);
}
//------------------------------------
//Load graphics content for the screen
//------------------------------------
virtual void LoadContent(){
}
//------------------------------------
//Unload content for the screen
//------------------------------------
virtual void UnloadContent(){
}
//-------------------------------------------------------------------------
//Update changes whether the screen should be updated or not and sets
//whether the screen should be drawn or not.
//
//Input:
// bOtherScreenHasFocus - is used set whether the screen should update
// bCoveredByOtherScreen - is used to set whether the screen is drawn or not
//-------------------------------------------------------------------------
virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){
this->bOtherScreenHasFocus = bOtherScreenHasFocus;
//if the screen is covered by another than change the screen state to hidden
//else set the screen state to active
if(bCoveredByOtherScreen){
ssState = Hidden;
}
else{
ssState = Active;
}
}
//-----------------------------------------------------------
//Takes input from the mouse and calls appropriate actions
//-----------------------------------------------------------
virtual void HandleInput(){
}
//----------------------
//Draw content on screen
//----------------------
virtual void Draw(){
}
//--------------------------------------
//Deletes screen from the screen manager
//--------------------------------------
void ExitScreen(){
//smScreenManager.RemoveScreen(*this);
}
};
class MenuScreen: public GameScreen{
public:
vector <BUTTON> vbtnMenuEntries;
MenuScreen(string strName):GameScreen(strName){
}
virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){
GameScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen);
for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++){
vbtnMenuEntries[i].IsPressed();
}
}
virtual void Draw(){
GameScreen::Draw();
for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++)
vbtnMenuEntries[i].Draw();
}
};
class testMenu : public MenuScreen{
public:
vector<OBJECT> test;
//OBJECT background3();
// OBJECT testPic(512, 384, buttonHover.png, 100, 40, 100, 40);
// BUTTON x(256, 384, buttonNormal.png, buttonHover.png, buttonPressed.png, 100, 40, test());
bool draw;
testMenu():MenuScreen("testMenu"){
OBJECT background3(1, 1, 0, TEXT("background.png"), 1, 1, 1024, 768);
OBJECT testPic(512, 384,0, TEXT("buttonHover.png"), 1, 1, 100, 40);
test.push_back(background3);
test.push_back(testPic);
//background3.Init(int xLoc, int yLoc, int zLoc, LPCTSTR filePath, int Rows, int Cols, int Width, int Height)
//test.push_back(background3);
// vbtnMenuEntries.push_back(x);
draw = false;
}
void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){
MenuScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen);
//cout << "X" << endl;
/*if(MouseLButton == true){
testMenu2 t;
smManager.AddScreen(t);
}*/
}
void Draw(){
//background3.Draw();
test[0].Draw();
test[1].Draw();
MenuScreen::Draw();
///*if(draw){*/
// testPic.Draw();
//}
}
/*void test(){
draw = true;
}*/
};
</code></pre>
|
<p>If gsScreens is a list of objects instead of a list of pointers (as your code suggests), then you're not storing what you think you're storing in it.</p>
<p>What's happening is that -- instead of putting a TestMenu into the list, you're actually constructing a new MenuScreen using the compiler-generated copy constructor and putting this MenuScreen into the list.</p>
<p>C++ is polymorphic through pointers, so if you don't have a pointer you won't get polymorphic behavior.</p>
|
<p><a href="https://stackoverflow.com/questions/88558/c-derived-class-problems#88620">Curt</a> is absolutely correct, but I'd just like to throw a little more information at it.</p>
<p>This problem (storing base-class objects, rather than pointers) is sometimes called "slicing".</p>
<p>Also, I tend to make use of the following macro:</p>
<pre><code>#define DISALLOW_COPYING(X) \
private: \
X(const X &); \
const X& operator= (const X& x)
</code></pre>
<p>Then you put this somewhere in your class definition:</p>
<pre><code>class Foo {
// ...
DISALLOW_COPYING(Foo);
};
</code></pre>
<p>If another class attempts to copy the object, you'll get a compiler error (because the methods are declared private). If the class itself attempts to copy the object, you'll get a linker error (because the methods have no implementation).</p>
| 11,421
|
<p>I was printing an object and it started to drag so I stopped it.</p>
<p>Went to move the Z-axis up so I could clear the bed and Z-axis would not budge.
I switched the printer off and manually turned the motors to get the Z up.
Cleared the bed, switched on and homed the printer. When it came to home the Z, BLTouch deployed and then nothing. Motors will not turn.</p>
<p>Things I tried:</p>
<ul>
<li>Recompiled the firmware (Marlin 2.0.x)</li>
<li>Different motors - Motors were free from the printer, just resting on a desk so I know it's not binding or anything.</li>
<li>Swapped stepper driver with a known working one.</li>
</ul>
<p>Info about the printer:</p>
<ul>
<li>CR10s</li>
<li>SKR1.4 Turbo board</li>
<li>TMC2208 Steppers</li>
<li>BLTouch</li>
<li>Octopi to control the printer.</li>
</ul>
<p>Output of <code>M122</code> for the Z:</p>
<pre><code>Recv: Z
Recv: Address
Recv: Enabled false
Recv: Set current 1000
Recv: RMS current 994
Recv: MAX current 1402
Recv: Run current 17/31
Recv: Hold current 8/31
Recv: CS actual 8/31
Recv: PWM scale
Recv: vsense 0=.325
Recv: stealthChop true
Recv: msteps 16
Recv: tstep max
Recv: PWM thresh. 0
Recv: [mm/s] -
Recv: OT prewarn false
Recv: triggered
Recv: OTP false
Recv: pwm scale sum 10
Recv: pwm scale auto 0
Recv: pwm offset auto 36
Recv: pwm grad auto 14
Recv: off time 4
Recv: blank time 24
Recv: hysteresis
Recv: -end 2
Recv: -start 1
Recv: Stallguard thrs
Recv: uStep count 40
Recv: DRVSTATUS Z
Recv: sg_result
Recv: stst
Recv: olb
Recv: ola
Recv: s2gb
Recv: s2ga
Recv: otpw
Recv: to
Recv: 157C
Recv: 150C
Recv: 143C
Recv: 120C
Recv: s2vsa
Recv: s2vsb
Recv: Driver registers:
Recv: Z 0xC0:08:00:00
Recv:
Recv:
Recv: Testing Z connection... OK
</code></pre>
|
<p>extruder clicking means you're getting backed up, grinding.</p>
<ul>
<li>Make the hotend hotter so you can melt filament 3X faster than expected; most materials have quite a range; aim high.</li>
<li>Slow down the cooling fan; a lot of them can cool the hotend.</li>
<li>You have a silicone boot on the nozzle? that will help some.</li>
<li>Use a larger diameter nozzle to reduce backpressure and allow thicker layers.</li>
<li>Try cranking the feed rate</li>
</ul>
<p>Lastly, consider that you simply might not get acceptable results pushing speed THAT much.</p>
|
<p>Changing "Flow" will affect whole print. So even if it helped for the middle part (I doubt), the next it would ruin the print on sides by overextrusion. However: <strong>if sides are printed ok, then why the middle couldn't?</strong> Because walls are printed slower? Indeed, the under-extrusion may quickly rise along with speed because of plastic deformation between extruder gears under pressure and slight slipping, which actually increases with speed. The video "<a href="https://youtu.be/0xRtypDjNvI?t=301" rel="nofollow noreferrer">How fast can your hotend print?</a>" presents experiment on this phenomena and its outcomes.</p>
<p>Then we go into master question: <strong>300% of what?</strong> Turning the speed knob during print will override all considerations that slicer took into account during calculations - and defintely override <a href="https://help.prusa3d.com/en/article/max-volumetric-speed_127176" rel="nofollow noreferrer">Max volumetric speed</a>, which is key factor to limit <strong>pressure in the nozzle</strong> (vide clicking noise).</p>
<p>The real limit seems to be this middle part of print, and outer part is just cosmetics (probably calculated to print slower because of quality). So if you ensure, that printing these middle surfaces is <strong>planned (in G-Code) with similar speed</strong> as walls, then (at least in theory) you may be able to increase overall speed, playing e.g. only with temperature. (I actually mean the speed of extrusion, so this may not be simple as just setting equal speed for perimeters and infill, but this does not change the conclusion below.)</p>
<p>So I say <strong>all it starts in the slicer</strong> software: increase speed there and re-caclulate. This will ensure to not exceed key limitations. Then you may manipulate maximal values in slicer for further experimentation.</p>
| 1,841
|
<p>The following code was produced by a consultant working for my group. I'm not a C++ developer (worked in many languages, though) but would like some independent opinions on the following code. This is in Visual Studio C++ 6.0. I've got a gut reaction (not a good one, obviously), but I'd like some "gut reactions" from seasoned (or even not so unseasoned) C++ developers out there. Thanks in advance!</p>
<pre><code>// Example call
strColHeader = insert_escape(strColHeader, ',', '\\'); //Get rid of the commas and make it an escape character
</code></pre>
<p>...snip...</p>
<pre><code>CString insert_escape ( CString originalString, char charFind, char charInsert ) {
bool continueLoop = true;
int currentInd = 0;
do {
int occurenceInd = originalString.Find(charFind, currentInd);
if(occurenceInd>0) {
originalString.Insert(occurenceInd, charInsert);
currentInd = occurenceInd + 2;
}
else {
continueLoop = false;
}
} while(continueLoop);
return(originalString);
}
</code></pre>
|
<p>hmm. I think </p>
<pre><code>CString strColHeader;
strColHeader.Replace(",", "\\,")
</code></pre>
<p>would do just as well.</p>
<p>I don't like the code, I tend to break from the while loop instead of having an unnecessary bool 'continue' flag. That goes double when he could have used <code>while (occurenceInd != 0)</code> as his loop control variable instead of the boolean.</p>
<p>Incrementing the counter also relies on "+2" which doesn't seem immediately understandable (not at a quick glance), and lastly (and most importantly) he doesn't seem to do comments.</p>
|
<p>Looks alright, if a bit, I dunno, hack. Better to use the library, but I wouldn't go and rewrite this routine.</p>
| 26,181
|
<p>I have seen some declaration of a union inside a struct as follows. Example code given below.</p>
<p>My questions is does it help in any memory savings(typical use for which a union is used for)? I do not see the benefit. </p>
<pre><code>typedef struct
{
int x1;
unsigned int x2;
ourstruct1 ov1;
ourstruct1 ov2;
union
{
struct
{
mystruct1 v1;
mystruct2 v2;
mystruct3 v3;
int* ctxSC;
mystruct4 v4;
Bool v5;
Long v6;
Long v7;
Long v8;
Long v9;
}mystr;
};
}structvar1;
</code></pre>
<p>-AD</p>
|
<p>Hmm. Well, the example above seems a little strange to me--the usual reason for a union is to have two different symbolic paths into the same storage (by bytes, by words, etc). However, the example you've given has only one member of the union.</p>
<p>The only thing I can think is that the code is written with an eye towards future expansion--I.E. that the union will, in subsequent versions, have additional members.</p>
|
<p>It would seem to me that the union isn't actually used here. I've never seen a lone struct inside a union like that either. Strange.</p>
| 30,999
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.