instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Take a very simple case as an example, say I have this URL:</p>
<pre><code>http://www.example.com/65167.html
</code></pre>
<p>and I wish to serve that content under:</p>
<pre><code>http://www.example.com/about
</code></pre>
<p><strong>UPDATE</strong>: Note that the 'bad' URL is the canonical one (it's produced by a CMS which uses it internally for linking), so <code>"/about"</code> is just a way of polishing it.</p>
<p>I have two broad options: a server-side redirect or a client-side one. I always thought that server-side would be preferable since it's more efficient, i.e. HTTP traffic is approximately halved. However, SEO techniques tend to favour a single URL for a resource, thus client-side is to be preferred.</p>
<p>How do you resolve this conflict, and are there other factors I've omitted?</p>
|
<p>Apache HTTPD's mod_rewrite can leave a browser showing a SEO-friendly URL in its location bar while redirecting to a numeric URL on the server:</p>
<pre><code>RewriteEngine on
RewriteRule ^/about$ /65167.html [L]
</code></pre>
|
<p>I'm pretty sure Google understands <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2" rel="nofollow noreferrer">301 Moved Permanently</a>.</p>
| 33,695
|
<p>I began an iPhone project the other day with a silly development code name, and now I want to change the name of the project since it's nearly finished. </p>
<p>But I'm not sure how to do this with Xcode, trying the obvious of changing the application's name in the info.plist file, causes the signing process to go wrong (I think...) and my app won't launch giving me a Launcher error.</p>
<p>I guess I could make a new project and copy paste everything over, but it seems so primitive that I'm hoping for a more civilized solution.</p>
|
<ol>
<li>Go to <code>Targets</code> in <code>Xcode</code>.</li>
<li><code>Build Settings</code> on your project's target (your current development name).</li>
<li>Search for <code>Product Name</code> under <code>Packaging</code>. Change its value to what you want your new project name to be.</li>
</ol>
<p><a href="https://i.stack.imgur.com/B4rZt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/B4rZt.png" alt="ProductName" /></a></p>
|
<p>Use <em>Target</em> → <em>Build Setting</em> → <em>Product name</em>.</p>
| 29,565
|
<p><a href="http://thedailywtf.com/Articles/nice_num,-mean_programmer.aspx" rel="nofollow noreferrer">The Daily WTF</a> for 2008-11-28 pillories the following code:</p>
<pre><code>static char *nice_num(long n)
{
int neg = 0, d = 3;
char *buffer = prtbuf;
int bufsize = 20;
if (n < 0)
{
neg = 1;
n = -n;
}
buffer += bufsize;
*--buffer = '\0';
do
{
*--buffer = '0' + (n % 10);
n /= 10;
if (--d == 0)
{
d = 3;
*--buffer = ',';
}
}
while (n);
if (*buffer == ',') ++buffer;
if (neg) *--buffer = '-';
return buffer;
}
</code></pre>
<p>How would you write it?</p>
|
<p>If you're a seasoned C programmer, you'll realize this code isn't actually that bad. It's relatively straightforward (for C), and it's blazingly fast. It has three problems:</p>
<ol>
<li>It fails on the edge case of LONG_MIN (-2,147,483,648), since negating this number produces itself in twos-complement
<ul>
<li>It assumes 32-bit integers - for 64-bit longs, a 20-byte buffer is not big enough</li>
<li>It's not thread-safe - it uses a global static buffer, so multiple threads calling it at the same time will result in a race condition</li>
</ul></li>
</ol>
<p>Problem #1 is easily solved with a special case. To address #2, I'd separate the code into two functions, one for 32-bit integers and one for 64-bit integers. #3 is a little harder - we have to change the interface to make completely thread-safe.</p>
<p>Here is my solution, based on this code but modified to address these problems:</p>
<pre><code>static int nice_num(char *buffer, size_t len, int32_t n)
{
int neg = 0, d = 3;
char buf[16];
size_t bufsize = sizeof(buf);
char *pbuf = buf + bufsize;
if(n < 0)
{
if(n == INT32_MIN)
{
strncpy(buffer, "-2,147,483,648", len);
return len <= 14;
}
neg = 1;
n = -n;
}
*--pbuf = '\0';
do
{
*--pbuf = '0' + (n % 10);
n /= 10;
if(--d == 0)
{
d = 3;
*--pbuf = ',';
}
}
while(n > 0);
if(*pbuf == ',') ++pbuf;
if(neg) *--pbuf = '-';
strncpy(buffer, pbuf, len);
return len <= strlen(pbuf);
}
</code></pre>
<p>Explanation: it creates a local buffer on the stack and then fills that in in the same method as the initial code. Then, it copies it into a parameter passed into the function, making sure not to overflow the buffer. It also has a special case for INT32_MIN. The return value is 0 if the original buffer was large enough, or 1 if the buffer was too small and the resulting string was truncated.</p>
|
<p>In pure C:</p>
<pre><code>#include <stdio.h>
#include <limits.h>
static char *prettyNumber(long num, int base, char separator)
{
#define bufferSize (sizeof(long) * CHAR_BIT)
static char buffer[bufferSize + 1];
unsigned int pos = 0;
/* We're walking backwards because numbers are right to left. */
char *p = buffer + bufferSize;
*p = '\0';
int negative = num < 0;
do
{
char digit = num % base;
digit += '0';
*(--p) = digit;
++pos;
num /= base;
/* This the last of a digit group? */
if(pos % 3 == 0)
{
/* TODO Make this a user setting. */
#ifndef IM_AMERICAN
# define IM_AMERICAN_BOOL 0
#else
# define IM_AMERICAN_BOOL 1
#endif
/* Handle special thousands case. */
if(!IM_AMERICAN_BOOL && pos == 3 && num < base)
{
/* DO NOTHING */
}
else
{
*(--p) = separator;
}
}
} while(num);
if(negative)
*(--p) = '-';
return p;
#undef bufferSize
}
int main(int argc, char **argv)
{
while(argc > 1)
{
long num = 0;
if(sscanf(argv[1], "%ld", &num) != 1)
continue;
printf("%ld = %s\n", num, prettyNumber(num, 10, ' '));
--argc;
++argv;
};
return 0;
}
</code></pre>
<p>Normally I'd return an alloc'd buffer, which would need to be free'd by the user. This addition is trivial.</p>
| 42,398
|
<p>trying to implement a dialog-box style behaviour using a separate div section with all the stuff inside it.</p>
<p>When the "dialog box" needs to be shown, it has to display at the center of the WINDOW, not in the center of the page, that is, REGARDLESS of the scroling position. Furthermore, the correct solution will not move the "dialog box" if the user scrolls the page.</p>
<p>In Chrome and FF this works using position='fixed' and centering the div in the intuitive way.</p>
<p>This does not seem to work in IE6 (apparently fixed is not supported there). </p>
<p>Any ideas?</p>
|
<p>If I were you I would do it using jQuery and I would suggest you try it out too. This should fit perfectly for jQuery based solution [jQuery Version][1] or try out</p>
<pre><code>body {
font: 80% verdana, arial, helvetica, sans-serif;
text-align: center; /* for IE */
}
#container {
margin: 0 auto; /* align for good browsers */
text-align: left; /* counter the body center */
border: 2px solid #000;
width: 80%;
}
</code></pre>
|
<p>Use <code>overflow-y</code> and absolute positioning to emulate fixed positioning in IE6 using the following steps:</p>
<ol>
<li><p>Create an absolutely positioned div and give it the desired top and left coordinates on the page</p></li>
<li><p>Set <code>html {overflow-y: }</code> to be hidden or visible instead of the default auto or scroll to eliminate the scrollbar for the absolutely positioned div</p></li>
<li><p>Set <code>body{overflow-y: }</code> to be auto or scroll to insert a new scrollbar for the body content</p></li>
<li><p>Set <code>body { margin:0; height:100% }</code> to make sure the content scrollbar goes the length of the page</p></li>
<li><p>Set top and left margins on the body to separate the content from the absolutely positioned div </p></li>
<li><p>Make sure the doctype is set to trigger Standards Mode in IE</p></li>
<li><p>Set the absolutely positioned div to <code>top:50%; left:50%;</code></p></li>
<li><p>Add <code>position:relative</code> and the desired opacity to the container div</p></li>
</ol>
<p>If the doctype is not set, move the html rules to the body tag, and the body rules to a wrapper div</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<style>
body { margin:0; margin-left: 14em; }
#fixedbox { position: fixed; top: 1em; left: 1em; width: 10em; }
#fixedbox { padding: 0.5em; border: 1px solid #000; }
#container { height: 2000px; }
@media,
{
html { _overflow-y: visible; *overflow-y: auto; }
body { _overflow-y: auto; _height: 100%; }
#container { _position: relative; }
#fixedbox { _position: absolute; _top:50%; _left: 50%; }
}
</style>
</head>
<body>
<div id="container">
Fixed box
</div>
<div id="fixedbox">
Homer
</div>
</body>
</html>
</code></pre>
| 41,248
|
<p>When debugging in Internet Explorer, I first get an alert box with extremely limited if not useless information (sorry IE) and choose to debug it. After selecting yes, I get another option <em>every time</em> to choose between 'New instance of Microsoft script debugger' and 'New instance of Visual Studio'. I'm fed up with having to click the yes button again after having clicked it once already on the alert box.</p>
<p>Update: I found that you can disable the Microsoft script debugger from within its own options; just disabling the JIT debugger from Tools -> Options, and JIT. This stops it appearing on the menu but now I get the dialog box asking me which one to choose and it only displays the Visual Studio - WHY? If there's only one option and you've already asked me if I want to debug, why ask again?!?! Bleh.</p>
<p>Can you tell I'm getting sick of clicking, "yes" twice? Lol.</p>
|
<p>Apparently the problem happens if you do not uninstall the old (crappy) Microsoft Script Debugger before you install the newer Microsoft Script Editor.</p>
<p>You would think that all you need to do is to uninstall the old debugger - however, according to a blog posting (which I can't recall at the moment), if you uninstall the Microsoft Script Debugger at this point, it will mess up the MSE and you will have to reinstall the MSE again. I am on a tight schedule now so I don't have the time to fix the problem properly - just living with it as best as I can.</p>
|
<p>Maybe not the complete solution, but you could try to set the default script debugger can be set <strong>in the registry</strong> directly. To do so, follow these steps:</p>
<ul>
<li>Click Start, Run and type regedit.exe</li>
<li>Navigate to the following branch:</li>
</ul>
<p>HKEY_CLASSES_ROOT \ CLSID \ {834128A2-51F4-11D0-8F20-00805F2CD064} \ LocalServer32</p>
<ul>
<li>Backup the branch by exporting it to a file</li>
<li><p>In the above key, double-click (default) and set its value data to: </p>
<p>"C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"</p>
<p>(or whatever your path to devenv.exe is)</p></li>
<li><p>Exit the Registry Editor. </p></li>
</ul>
| 27,811
|
<p>I am adding some user controls dynamically to a PlaceHolder server control. My user control consists of some labels and some textbox controls. </p>
<p>When I submit the form and try to view the contents of the textboxes (within each user control) on the server, they are empty.</p>
<p>When the postback completes, the textboxes have the data that I entered prior to postback. This tells me that the text in the boxes are being retained through ViewState. I just don't know why I can't find them when I'm debugging. </p>
<p>Can someone please tell me why I would not be seeing the data the user entered on the server?</p>
<p>Thanks for any help.</p>
|
<p>This is based on .NET v1 event sequence, but it should give you the idea:</p>
<ul>
<li>Initialize (Init event)</li>
<li>Begin Tracking View State (checks if postback)
<ul>
<li>Load View State (if postback)</li>
<li>Load Postback Data (if postback)</li>
</ul></li>
<li>Load (Load event)
<ul>
<li>Raise Changed Events (if postback)</li>
<li>Raise Postback Events (if postback)</li>
</ul></li>
<li>PreRender (PreRender event)</li>
<li>Save View State</li>
<li>Render</li>
<li>Unload (Unload event)</li>
<li>Dispose</li>
</ul>
<p>As you can see, the loading of ViewState data back to the controls happen before the Load event. So in order for your dynamically-added controls to "retain" those values, they have to be <em>present</em> for the ASP.NET page to reload the values in the first place. You would have to re-create those controls at the Init stage, before Load View State occurs.</p>
|
<p>You have to create your controls in the Page_PreInit event handler. The ASP.NET server control model is tricky; you have to fully understand the <a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="nofollow noreferrer">page lifecycle</a> to do it right.</p>
| 12,807
|
<p>I have an NSView subclass which has property which I want to be bindable. I've implemented the following in the subclass:</p>
<p>myView.h:</p>
<pre><code>@property (readwrite, retain) NSArray *representedObjects;
</code></pre>
<p>myView.m:</p>
<pre><code>@synthesize representedObjects;
+(void)initialize
{
[self exposeBinding: @"representedObjects"];
}
-(void)bind:(NSString *)binding toObject:(id)observableController withKeyPath:(NSString *)keyPath options:(NSDictionary *)options
{
if ([binding isEqualToString:@"representedObjects"]) {
[observableController addObserver: self forKeyPath:@"arrangedObjects" options:NSKeyValueChangeNewKey context:nil];
} else {
[super bind: binding toObject:observableController withKeyPath:keyPath options: options];
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"arrangedObjects"]) {
[self setRepresentedObjects: [object arrangedObjects]];
}
}
</code></pre>
<p>I then create the binding to an arrayController in <code>-[AppController awakeFromNib]</code>:</p>
<pre><code>[myView bind:@"representedObjects" toObject:arrayController withKeyPath:@"arrangedObjects" options: nil];
</code></pre>
<p>Is this the correct way of implementing binding? It involves a lot of boiler plate code which makes me think that I'm doing something wrong.</p>
<p>I thought that NSObject would automagically implement what I have done manually in <code>-bind:toObject:withKeyPath:options:</code> but this doesn't seem to be the case. If I comment out my <code>-bind:toObject:withKeyPath:options:</code> the setRepresentedObjects method is never called.</p>
<p>Additional info:
I've done some more investigating and have reached the conclusion that my original approach is correct and you do have to over ride <code>-bind:toObject:withKeyPath:options:</code>. Here's a quote from <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaBindings/Concepts/HowDoBindingsWork.html#//apple_ref/doc/uid/20002373" rel="nofollow noreferrer">Cocoa Bindings Programming Topics: How Do Bindings Work?</a>:</p>
<blockquote>
<p>In its bind:toObject:withKeyPath:options: method an object must as a minimum do the following:</p>
<ul>
<li>Determine which binding is being set</li>
<li>Record what object it is being bound to using what keypath and with what options</li>
<li>Register as an observer of the keypath of the object to which it is bound so that it receives notification of changes</li>
</ul>
<p>The code sample in Listing 2 shows a partial implementation of Joystick’s bind:toObject:withKeyPath:options: method dealing with just the angle binding.</p>
<p>Listing 2 Partial implementation of the bind:toObject:withKeyPath:options method for the Joystick class:</p>
<blockquote>
<pre><code>static void *AngleBindingContext = (void *)@"JoystickAngle";
- (void)bind:(NSString *)binding
toObject:(id)observableObject
withKeyPath:(NSString *)keyPath
options:(NSDictionary *)options
{
// Observe the observableObject for changes -- note, pass binding identifier
// as the context, so you get that back in observeValueForKeyPath:...
// This way you can easily determine what needs to be updated.
if ([binding isEqualToString:@"angle"])
{
[observableObject addObserver:self
forKeyPath:keyPath
options:0
context:AngleBindingContext];
// Register what object and what keypath are
// associated with this binding
observedObjectForAngle = [observableObject retain];
observedKeyPathForAngle = [keyPath copy];
// Record the value transformer, if there is one
angleValueTransformer = nil;
NSString *vtName = [options objectForKey:@"NSValueTransformerName"];
if (vtName != nil)
{
angleValueTransformer = [NSValueTransformer
valueTransformerForName:vtName];
}
}
// Implementation continues...
</code></pre>
</blockquote>
</blockquote>
<p>This clearly shows that the Joystick class (which is an NSView subclass) needs to override <code>-bind:toObject:withKeyPath:options:</code>.</p>
<p>I find this surprising. I was skeptical of this conclusion as I have found no other code samples that do this. However, as the offical Apple documentation says I should over ride <code>-bind:toObject:withKeyPath:options:</code> I conclude that it is the correct approach.</p>
<p>I would be very happy if someone could prove me wrong!</p>
|
<p>No, you shouldn’t need that glue code.</p>
<p>What do you mean by “doesn’t seem to be the case”? What happens if you omit it?</p>
|
<p>You definitely DO need to implement <code>-bind:toObject:withKeyPath:options:</code> in a custom view if you want to implement bindings in that view. Your implementation in myView.m is pretty much spot on.</p>
| 47,896
|
<p>C# novice here, when the int 'max' below is 0 I get a divide by zero error, I can see why this happens but how should I handle this when max is 0? position is also an int.</p>
<pre><code> private void SetProgressBar(string text, int position, int max)
{
try
{
int percent = (100 * position) / max; //when max is 0 bug hits
string txt = text + String.Format(". {0}%", percent);
SetStatus(txt);
}
catch
{
}
}
</code></pre>
|
<pre><code>int percent = 0
if (max != 0) percent = (100*position) / max
</code></pre>
|
<p>Well, if max is zero, then there is no progress to be made. Try catching the exception where this is called. That is probably the place to decide whether there is a problem or if the progress bar should be set at zero or at 100%.</p>
| 19,366
|
<p>With SQLServer, it seems to be generally accepted that adding a SELECT SCOPE_IDENTITY() to the end of your insert is the best way to return the PK of the newly-inserted record, assuming you're using an auto-increment field for the pk. </p>
<p>However, I can't seem to find the equivalent for Oracle. </p>
<p>Best practice seems to be to use a sequence to generate the PK, but there are different options for how to implement even that. Do you leave it up to the developer to insert sequence.nexval, or use a trigger?</p>
<p>In either case, getting the new ID back seems to be a common problem.</p>
<p>Suggestions and solutions I've run across include:</p>
<ul>
<li>creating a stored proc that returns the PK</li>
<li>running a select id from seq.nextval, then passing that to the insert </li>
<li>select max(id) after insert (Note: Don't do this!) </li>
<li>add a RETURNING clause to the insert</li>
</ul>
<p>What should the "best practice" solution be for this situation?</p>
|
<p>You can use the RETURNING clause to do this in Oracle stored procs.</p>
<p>For example:</p>
<p>TABLEA has NAME and EMP_ID. EMP_ID is populated internally when records are inserted.</p>
<p>INSERT INTO TABLEA(NAME) VALUES ('BOB') RETURNING EMP_ID INTO o_EMP_ID;</p>
<p>That's assuming that line is in a stored proc with an output parameter of o_EMP_ID.</p>
<p>Hope that helps... if not, here's a more detailed example:</p>
<p><a href="http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/returninginto_clause.htm" rel="nofollow noreferrer">http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/returninginto_clause.htm</a></p>
|
<p>The RETURNING clause is intended for just this kind of usage, so I would call it a best practice to use it.</p>
<p>An alternative would be to select seq.CURRVAL after the insert. That returns the last value obtained from the sequence by <strong>this</strong> session.</p>
| 19,182
|
<p>I am writing a Browser Helper Object for ie7, and I need to detect DOM modification (i.e. via AJAX).
So far I couldn't find any feasible solution.</p>
|
<p>You want to use <a href="http://msdn.microsoft.com/en-us/library/aa703624(VS.85).aspx" rel="nofollow noreferrer">IMarkupContainer2::CreateChangeLog</a>.</p>
|
<p>The best thing I could recommend is the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=E59C3964-672D-4511-BB3E-2D5E1DB91038&displaylang=en" rel="nofollow noreferrer">Internet Explorer Developer Toolbar</a> which allow you to view changes in the DOM.</p>
| 5,485
|
<p>Is there a side effect in doing this:</p>
<p>C code:</p>
<pre><code>struct foo {
int k;
};
int ret_foo(const struct foo* f){
return f.k;
}
</code></pre>
<p>C++ code:</p>
<pre><code>class bar : public foo {
int my_bar() {
return ret_foo( (foo)this );
}
};
</code></pre>
<p>There's an <code>extern "C"</code> around the C++ code and each code is inside its own compilation unit.</p>
<p>Is this portable across compilers?</p>
|
<p>This is entirely legal. In C++, classes and structs are identical concepts, with the exception that all struct members are public by default. That's the only difference. So asking whether you can extend a struct is no different than asking if you can extend a class.</p>
<p>There is one caveat here. There is <em>no guarantee</em> of layout consistency from compiler to compiler. So if you compile your C code with a different compiler than your C++ code, you may run into problems related to member layout (padding especially). This can even occur when using C and C++ compilers from the same vendor.</p>
<p>I <em>have</em> had this happen with gcc and g++. I worked on a project which used several large structs. Unfortunately, g++ packed the structs significantly looser than gcc, which caused significant problems sharing objects between C and C++ code. We eventually had to manually set packing and insert padding to make the C and C++ code treat the structs the same. Note however, that this problem can occur regardless of subclassing. In fact we weren't subclassing the C struct in this case.</p>
|
<p>I don't get why you don't simply make ret_foo a member method. Your current way makes your code awfully hard to understand. What is so difficult about using a real class in the first place with a member variable and get/set methods? </p>
<p>I know it's possible to subclass structs in C++, but the danger is that others won't be able to understand what you coded because it's so seldom that somebody actually does it. I'd go for a robust and common solution instead.</p>
| 15,488
|
<p>We need to provide a solution to do performance testing for our Web Services residing in our development environment. We were planning to create the test scripts using the object model of Microsoft Web Application Stress Tool. I have researched and not been able to find any examples. </p>
<p>Can anyone, who may have perhaps used this same tool for a similar solution, to please provide any advise and/or examples? Also, please provide any suggestions if a different tool can provide a more convenient solution.</p>
<p>Any help would be much appreciated.</p>
<p>Thank You</p>
|
<p>So a year or two back I had the same problem and was able to apply my experience with the grinder to the problem:
<a href="http://grinder.sourceforge.net/" rel="nofollow noreferrer">http://grinder.sourceforge.net/</a></p>
<p>Others in my environment reported success using ACT:
<a href="http://en.wikipedia.org/wiki/Application_Center_Test" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Application_Center_Test</a></p>
|
<p>You may have to stress test IIS itself since it's webservice, just loop open 5000 request.</p>
| 18,693
|
<p>How do I apply the MarshalAsAttribute to the return type of the code below?</p>
<pre><code>public ISomething Foo()
{
return new MyFoo();
}
</code></pre>
|
<p>According to <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx</a>:</p>
<pre><code>[return: MarshalAs(<your marshal type>)]
public ISomething Foo()
{
return new MyFoo();
}
</code></pre>
|
<pre><code>[return:MarshalAs]
public ISomething Foo()
{
return new MyFoo();
}
</code></pre>
| 15,953
|
<p>Is there a way in MySQL to select rows which fall on a specific day, as in Mondays, using a date column?</p>
|
<p>MySQL <a href="http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_dayofweek" rel="nofollow noreferrer">DAYOFWEEK</a> function.</p>
<p>E.g. to select Mondays:</p>
<pre><code>SELECT * FROM foo WHERE DAYOFWEEK(bar) = 2
</code></pre>
|
<p>I assume you mean a specific Week Day Name, yes there is:</p>
<p>In mysql you can use <strong>DAYOFWEEK()</strong> - <a href="http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html" rel="nofollow noreferrer">check the manual</a></p>
<p>In PHP you can use getdate() and for example do:</p>
<p>$date = getdate();
$weekday = $date[weekday]; - <a href="http://www.php.net/getdate" rel="nofollow noreferrer">check the manual</a></p>
| 38,071
|
<p>I'm writing some disposable Haskell scripts to solve some of the <a href="http://projecteuler.net" rel="nofollow noreferrer">Project Euler</a> problems. I don't really want to have to compile them because of the number of changes I'm constantly having to make, but in a few cases I've found that I've run out of stack space.</p>
<p>The documentation for <code>runhaskell</code> says that the following syntax should increase the stack space:</p>
<pre><code>runhaskell +RTS -K5M -RTS Script.hs
</code></pre>
<p>This never, ever works (in any permutation I've tried). The stack size always remains 8,388,608. This is maddening, and I haven't found much help on Google.</p>
<p>Any suggestions? What am I doing wrong?</p>
|
<p>I'm guessing you're using GHC. Chapter 4 of the User's Guide of the newly released 6.10.1 says: </p>
<blockquote>
<p>The only runghc flag currently is -f
/path/to/ghc, which tells runghc which
GHC to use to run the program.</p>
</blockquote>
<p>I don't see a bug logged at <a href="http://hackage.haskell.org/trac/ghc" rel="noreferrer">http://hackage.haskell.org/trac/ghc</a> . Seems pretty lame to me. I'd suggest asking on irc #ghc, or the cvs-ghc mailing list.</p>
<p>Of the other Haskell compilers/interpreters, only nhc98 seems allow you to set the max stack size. Depending on your OS, nhc98 could be an option. </p>
|
<p>Just compile it.</p>
<p>Problem123.hs:</p>
<pre><code>module Main where
main = do
print solution
solution = ...
</code></pre>
<p>Short and sweet command line:</p>
<pre><code>ghc --make -O3 Problem123.hs
./Problem123
</code></pre>
<p>Final note: I'm not sure I would call them "scripts".</p>
| 34,693
|
<p>I've worked out how to interact with IIS 6.0, but I can't find anything on the net about how to talk to IIS 5.0 - if indeed it's even possible?</p>
<p>I would like to write a script to create a temporary application, so I can copy some ASP.NET files there, build them, and then remove the temporary application.</p>
<p>If needs be I am happy to call a third-party VBScript instead.</p>
|
<p>There use to be some installers on the ASP.NET downloads that would setup a project in IIS 5.0. I think it was the old ASP.NET Forums software. I know this wasn't an answer to your question. </p>
<p>If I was a betting man I would say they probably created a batch file that used the VBScripts. Because I remember a black window popping up to compile and deploy. </p>
<p>As far as PowerShell goes, I don't think there is any solution for integration with IIS 5.</p>
|
<p><a href="https://stackoverflow.com/questions/371207/can-i-automate-creating-a-net-web-application-virtual-directory-in-iis-5#371264">Can I automate creating a .NET web application / virtual directory in IIS 5?</a></p>
| 48,969
|
<p>Given that indexing is so important as your data set increases in size, can someone explain how indexing works at a database-agnostic level?</p>
<p>For information on queries to index a field, check out <a href="https://stackoverflow.com/questions/1156/">How do I index a database column</a>.</p>
|
<p><strong>Why is it needed?</strong></p>
<p>When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously.</p>
<p>Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires <code>(N+1)/2</code> block accesses (on average), where <code>N</code> is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at <code>N</code> block accesses.</p>
<p>Whereas with a sorted field, a Binary Search may be used, which has <code>log2 N</code> block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial.</p>
<p><strong>What is indexing?</strong></p>
<p>Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it.</p>
<p>The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed.</p>
<p><strong>How does it work?</strong></p>
<p>Firstly, let’s outline a sample database table schema;</p>
<pre>
Field name Data type Size on disk
id (Primary key) Unsigned INT 4 bytes
firstName Char(50) 50 bytes
lastName Char(50) 50 bytes
emailAddress Char(100) 100 bytes
</pre>
<p><strong>Note</strong>: char was used in place of varchar to allow for an accurate size on disk value.
This sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the <em>id</em> (a sorted key field) and one using the <em>firstName</em> (a non-key unsorted field).</p>
<p><em><strong>Example 1</strong></em> - <em>sorted vs unsorted fields</em></p>
<p>Given our sample database of <code>r = 5,000,000</code> records of a fixed size giving a record length of <code>R = 204</code> bytes and they are stored in a table using the MyISAM engine which is using the default block size <code>B = 1,024</code> bytes. The blocking factor of the table would be <code>bfr = (B/R) = 1024/204 = 5</code> records per disk block. The total number of blocks required to hold the table is <code>N = (r/bfr) = 5000000/5 = 1,000,000</code> blocks.</p>
<p>A linear search on the id field would require an average of <code>N/2 = 500,000</code> block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of <code>log2 1000000 = 19.93 = 20</code> block accesses. Instantly we can see this is a drastic improvement.</p>
<p>Now the <em>firstName</em> field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact <code>N = 1,000,000</code> block accesses. It is this situation that indexing aims to correct.</p>
<p>Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the <em>firstName</em> field is outlined below;</p>
<pre>
Field name Data type Size on disk
firstName Char(50) 50 bytes
(record pointer) Special 4 bytes
</pre>
<p><strong>Note</strong>: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table.</p>
<p><em><strong>Example 2</strong></em> - <em>indexing</em></p>
<p>Given our sample database of <code>r = 5,000,000</code> records with an index record length of <code>R = 54</code> bytes and using the default block size <code>B = 1,024</code> bytes. The blocking factor of the index would be <code>bfr = (B/R) = 1024/54 = 18</code> records per disk block. The total number of blocks required to hold the index is <code>N = (r/bfr) = 5000000/18 = 277,778</code> blocks.</p>
<p>Now a search using the <em>firstName</em> field can utilize the index to increase performance. This allows for a binary search of the index with an average of <code>log2 277778 = 18.08 = 19</code> block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to <code>19 + 1 = 20</code> block accesses, a far cry from the 1,000,000 block accesses required to find a <em>firstName</em> match in the non-indexed table.</p>
<p><strong>When should it be used?</strong></p>
<p>Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index.</p>
<p>Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space.</p>
|
<p>Just think of Database Index as Index of a book.</p>
<p>If you have a book about dogs and you want to find an information about let's say, German Shepherds, you could of course flip through all the pages of the book and find what you are looking for - but this of course is time consuming and not very fast. </p>
<p>Another option is that, you could just go to the Index section of the book and then find what you are looking for by using the Name of the entity you are looking ( in this instance, German Shepherds) and also looking at the page number to quickly find what you are looking for. </p>
<p>In Database, the page number is referred to as a pointer which directs the database to the address on the disk where entity is located. Using the same German Shepherd analogy, we could have something like this (“German Shepherd”, 0x77129) where <code>0x77129</code> is the address on the disk where the row data for German Shepherd is stored. </p>
<p>In short, an index is a data structure that stores the values for a specific column in a table so as to speed up query search.</p>
| 2,354
|
<p>Has anyone seen a tool that will integrate code coverage results with SCM/VCS to attribute untested lines of code to developers?
For example, is there a tool that will take NCover's Coverage.Xml, combine it with SVN blame, and produce a report that tells me things like developer who commits most untested code?</p>
|
<p>Try:</p>
<pre><code>WScript.Quit n
</code></pre>
<p>Where n is the ERRORLEVEL you want to return</p>
|
<p>Try:</p>
<pre><code>WScript.Quit n
</code></pre>
<p>Where n is the ERRORLEVEL you want to return</p>
| 22,646
|
<p>I need to be able to display some data in Eclipse in a grid/table control... I need things like paging, multiple column sorting, column choosing, etc. There is an SWT Table and the <a href="http://www.eclipse.org/nebula/widgets/grid/grid.php" rel="nofollow noreferrer">Nebula project has a grid in alpha</a>.</p>
<p>Does what I need exist? 3rd party maybe? Doesn't have to be free, we can pay for the functionality.</p>
|
<p>I haven't seen those features implemented in a reusable widget that I can think of, they are more application-level features.</p>
<p><strong>Paging:</strong>
If you were to use the JFace-type viewers (SWT Table or <a href="http://www.eclipse.org/nebula/widgets/grid/grid.php" rel="nofollow noreferrer">Nebula Grid</a> both support this style of MVC architecture, as do some others mentioned in <a href="https://stackoverflow.com/questions/115766/a-more-advanced-table-spreadsheet-swt-implementation">this question</a>), it should be possible to implement paging in the content provider, just by setting some custom offset into your dataset and then refreshing the grid.</p>
<p><strong>Multiple Column Sorting:</strong>
You can do this, it just needs an implementation of the correct table sorting interface. You get passed two rows to compare, and you can compare whichever columns you like in the sorting algorithm. Again though, the interface for actually choosing which columns to sort is down to you.</p>
<p><strong>Column Choosing:</strong>
This requires a grid control with cell selection. Nebula is one, SWT Table isn't. If cell selection is available, this is just a matter of catching the correct selection event (clicking on a header probably) and iterating over your rows to select the correct cells.</p>
|
<p>You could use the facilities of table presentation offered by the <a href="http://www.eclipse.org/birt/phoenix/intro/" rel="nofollow noreferrer">BIRT plugin</a>, that is if you are really advance <a href="http://java.sys-con.com/node/295339/print" rel="nofollow noreferrer">table layout needs</a>.<br>
<a href="https://i.stack.imgur.com/SmJFN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SmJFN.png" alt="alt text"></a><br>
<sub>(source: <a href="http://www.theserverside.com/tt/articles/content/EclipseBRT/Images/templ_use.png" rel="nofollow noreferrer">theserverside.com</a>)</sub> </p>
<p>(otherwise the classic SWT <a href="http://www.richclient2.eu/2006_07_28/tableviewer-with-eclipse-32-sorter-filter-and-sort-indicator/" rel="nofollow noreferrer">TableViewer</a> offers already some of the feature you are after <a href="https://i.stack.imgur.com/0RsaJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0RsaJ.png" alt="alt text"></a><br>
<sub>(source: <a href="http://www.richclient2.eu/wp-content/uploads/2006/07/table_fract.png" rel="nofollow noreferrer">richclient2.eu</a>)</sub> )</p>
| 38,480
|
<p>I want to do something like this:</p>
<pre><code><MyTemplate>
<span><%# Container.Title %></span>
<MySubTemplate>
<span><%# Container.Username %></span>
</MySubTemplate>
</MyTemplate>
</code></pre>
<p>Assuming I have a list of Titles that each have a list of Usernames.. If this is a correct approach how can I do this or what is a better way?</p>
|
<p>If you have a list of titles, that each have their own list of UserNames, it seems like you want to do something with nested repeaters (or other controls), not templates...</p>
<pre><code> <asp:Repeater ID="rptTitle" runat="server" >
<ItemTemplate>
<%# Eval("Title") %>
<asp:Repeater ID="rptUsers" runat="server" >
<ItemTemplate>
<%# Eval("UserName") %>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</code></pre>
<p>And then bind the rptUsers during the ItemDataBound event of rptTitle...</p>
|
<p>You can do it this way. You can also use:</p>
<ul>
<li>Labels</li>
<li>Span runat="server" and add them programmatically</li>
<li>(ghetto) string.replace</li>
</ul>
| 33,835
|
<p>I'm sure there is a quick and easy way to calculate the sum of a column of values on Unix systems (using something like <code>awk</code> or <code>xargs</code> perhaps), but writing a shell script to parse the rows line by line is the only thing that comes to mind at the moment.</p>
<p>For example, what's the simplest way to modify the command below to compute and display the total for the SEGSZ column (70300)?</p>
<pre><code>ipcs -mb | head -6
IPC status from /dev/kmem as of Mon Nov 17 08:58:17 2008
T ID KEY MODE OWNER GROUP SEGSZ
Shared Memory:
m 0 0x411c322e --rw-rw-rw- root root 348
m 1 0x4e0c0002 --rw-rw-rw- root root 61760
m 2 0x412013f5 --rw-rw-rw- root root 8192
</code></pre>
|
<pre><code>ipcs -mb | tail +4 | awk '{ sum += $7 } END { print sum }'
</code></pre>
<p>Or without tail:</p>
<pre><code>ipcs -mb | awk 'NR > 3 { sum += $7 } END { print sum }'
</code></pre>
<p>Using awk with bc to have arbitrary long results (credits to <code>Jouni K.</code>):</p>
<pre><code>ipcs -mb | awk 'NR > 3 { print $7 }' | paste -sd+ | bc
</code></pre>
|
<p>Thanks for the Python one-liner above!. It helped me to easy check the used space on my drive.
Here is a mixed shell / Python one-liner, that do this - counts used space on the device /dev/sda in megabytes. It took me some time, before I found it out, so, maybe someone finds this useful too.</p>
<pre><code>df -h -B 1M | grep dev/sda | tr -s ' '| cut -d' ' -f3 |python -c "import sys; print sum([int(num) for num in sys.stdin.readlines()])"
</code></pre>
<p>or more Python / less shell:</p>
<pre><code> df -h -B 1M | python -c "import sys; print sum([int(l.split()[2]) for l in sys.stdin.readlines() if '/dev/sda' in l])"
</code></pre>
<p>Thanks again!</p>
| 37,818
|
<p>Our company (xyz) is moving a lot of our Flash code to Python.</p>
<p>In Flash, we have a shared library between our Flash apps - package xyz. We can make changes to the package without fear of breaking other apps when they are deployed because Flash compiles their code and includes the contents of the library. We deploy the final SWF via RPM, and we're done. Updates to App1 and App2 won't ever break App3.</p>
<p>How would you approach this in Python, the shared library dependency. </p>
<p>App1, App2 and App3, could all require xyz-lib.rpm, and all use the same library files, but an updated xyz-lib.rpm would have to be explicitly tested against App1,2,3 <em>every time</em> there was a new library, and this is just onerous.</p>
<p>My current favorite solution - I could make app1.rpm include the library from when it was packaged - effectively some sort of static linking of the library. This, however, feels inelegant. (although the only additional cost is hard drive space == cheap.)</p>
<p>I know that solid management of the shared library is probably the best solution, but I keep trying to factor in that all the developers are human, and will make mistakes. We're going to make mistakes, and I don't want a deployment of app1 to break app2 and app3 - it's just a lot more to test and debug for.</p>
|
<p>"explicitly tested against App1,2,3 every time there was a new library" actually isn't that onerous.</p>
<p>Two things.</p>
<ul>
<li><p>You need a formal set of API unit tests that the library <em>must</em> pass. This is just the API, not every nuance of functionality. If this passes, then your changes are good to go. If this fails, your changes broke the API.</p></li>
<li><p>You also need a set of unit tests for functionality, separate from the API. This is bigger, and might be classified as "onerous".</p></li>
</ul>
<p>Once you start unit testing, you get addicted. Once you have reasonably complete tests, this problem is easy to manage.</p>
|
<p>I've used variations of this <a href="http://code.activestate.com/recipes/497000/" rel="nofollow noreferrer">cookbook entry</a> to distribute python apps. Basically it involves zipping all your python sources up into a zip file, then concatenating it with a shell script to import the source files.</p>
<p>This can be helpful if you need to give an app its own version of the library.</p>
| 44,516
|
<p>Say I am declaring a class <code>C</code> and a few of the declarations are very similar. I'd like to use a function <code>f</code> to reduce code repetition for these declarations. It's possible to just declare and use <code>f</code> as usual:</p>
<pre><code>>>> class C(object):
... def f(num):
... return '<' + str(num) + '>'
... v = f(9)
... w = f(42)
...
>>> C.v
'<9>'
>>> C.w
'<42>'
>>> C.f(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with C instance as first argument (got int instance instead)
</code></pre>
<p>Oops! I've inadvertently exposed <code>f</code> to the outside world, but it doesn't take a <code>self</code> argument (and can't for obvious reasons). One possibility would be to <code>del</code> the function after I use it:</p>
<pre><code>>>> class C(object):
... def f(num):
... return '<' + str(num) + '>'
... v = f(9)
... del f
...
>>> C.v
'<9>'
>>> C.f
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'C' has no attribute 'f'
</code></pre>
<p>But what if I want to use <code>f</code> again later, after the declaration? It won't do to delete the function. I could make it "private" (i.e., prefix its name with <code>__</code>) and give it the <code>@staticmethod</code> treatment, but invoking <code>staticmethod</code> objects through abnormal channels gets very funky:</p>
<pre><code>>>> class C(object):
... @staticmethod
... def __f(num):
... return '<' + str(num) + '>'
... v = __f.__get__(1)(9) # argument to __get__ is ignored...
...
>>> C.v
'<9>'
</code></pre>
<p>I have to use the above craziness because <code>staticmethod</code> objects, which are descriptors, are not themselves callable. I need to recover the function wrapped by the <code>staticmethod</code> object before I can call it.</p>
<p>There has got to be a better way to do this. How can I cleanly declare a function in a class, use it during its declaration, and also use it later from within the class? Should I even be doing this?</p>
|
<p>Quite simply, the solution is that f does not need to be a member of the class. I am assuming that your thought-process has gone through a Javaish language filter causing the mental block. It goes a little something like this:</p>
<pre><code>def f(n):
return '<' + str(num) + '>'
class C(object):
v = f(9)
w = f(42)
</code></pre>
<p>Then when you want to use f again, just use it</p>
<pre><code>>>> f(4)
'<4>'
</code></pre>
<p>I think the moral of the tale is "In Python, you don't <em>have</em> to force everything into a class". </p>
|
<p>Let's begin from the beginning.</p>
<p>"declare a function in a class, use it during its declaration, and also use it later from within the class"</p>
<p>Sorry. Can't be done. "In a class" contradicts "used during declaration".</p>
<ul>
<li>In a class means created as part of the declaration.</li>
<li>Used during declaration means it exists outside the class. Often as a meta class. However, there are other ways.</li>
</ul>
<p>It's not clear what C.w and C.v are supposed to be. Are they just strings? If so, an external function <code>f</code> is the best solution. The "not clutter the namespace" is a bit specious. After all, you want to use it again.</p>
<p>It's in the same module as C. That's why Python has modules. It binds the function and class together.</p>
<pre><code>import myCmod
myCmod.C.w
myCmod.C.v
myCmod.f(42)
</code></pre>
<p>If w and v aren't simple strings, there's a really good solution that gives a lot of flexibility.</p>
<p>Generally, for class-level ("static") variables like this, we can use other classes. It's not possible to completely achieve the desired API, but this is close.</p>
<pre><code>>>> class F(object):
def __init__( self, num ):
self.value= num
self.format= "<%d>" % ( num, )
>>> class C(object):
w= F(42)
v= F(9)
>>> C.w
<__main__.F object at 0x00C58C30>
>>> C.w.format
'<42>'
>>> C.v.format
'<9>'
</code></pre>
<p>The advantage of this is that F is a proper, first-class thing that can be extended. Not a "hidden" thing that we're trying to avoid exposing. It's a fact of life, so we might as well follow the Open/Closed principle and make it open to extension.</p>
| 39,157
|
<p>One thing that bugs me about IE is that when it goes to load a page with an iframe it will wait until the iframe has finished loading before it will render the page. Firefox by contrast will render all the other page elements while the iframe is loading which is really nice if the iframe takes a long time to load because it gives the user some feedback that the page is progressing. It also allows you to do things like display a "iframe loading" messege while the frame loads and swap it out onload of the iframe.</p>
<p>So, I am wondering if anyone has found a workaround for this. Ideally, I'd like to see a cross browser solution that shows a progess bar as an iframe loads on the page. Short of that I'd take a method of implementing an iframe that forces IE to first render the page then load the iframe.</p>
<p>I have seen a couple of interesting jquery progress bars like:
<a href="http://plugins.jquery.com/project/jQueryProgressBar" rel="nofollow noreferrer">http://plugins.jquery.com/project/jQueryProgressBar</a></p>
<p>But...(and correct me if I'm wrong here cause my understanding is shaky)...it seems to me the jquery bars only render after the DOM has loaded. In IE the iframe content is not shown until after the DOM is loaded so showing a progress bar at that point is irrelevant.</p>
<p>I've also tried setting the iframe src to loading.htm and then onload switch the src to the content I want. Sadly IE still will not render the page until the final content page comes up (seems strange to me).</p>
<p>Help me stackoverflow, you're my only hope.</p>
|
<p>What if you were to load the page with an XmlHttpRequest and then replace the contents of the document as/when it loads?</p>
<pre><code><!-- jQuery example: -->
<div id='content'>Loading...</div>
<script type='text/javascript'>
$("#content").load(url);
</script>
</code></pre>
|
<p>You could set the location of your iframe using JavaScript after the parent window has loaded.</p>
<pre><code><body onload="document.getElementById('myIframe').location='someurl';">
<iframe id="myIframe">
</body>
</code></pre>
<p>Would be the most rudimentary way to do it. </p>
| 37,936
|
<p>Having a strange issue with some C# code - the Getter method for a property is showing up as virtual when not explicitly marked.</p>
<p>The problem exhibits with the DbKey property on this class (code in full):</p>
<pre><code>public class ProcessingContextKey : BusinessEntityKey, IProcessingContextKey
{
public ProcessingContextKey()
{
// Nothing
}
public ProcessingContextKey(int dbKey)
{
this.mDbKey = dbKey;
}
public int DbKey
{
get { return this.mDbKey; }
set { this.mDbKey = value; }
}
private int mDbKey;
public override Type GetEntityType()
{
return typeof(IProcessingContextEntity);
}
}
</code></pre>
<p>When I use reflection to inspect the DbKey property, I get the following (unexpected) result:</p>
<pre><code>Type t = typeof(ProcessingContextKey);
PropertyInfo p = t.GetProperty("DbKey");
bool virtualGetter = p.GetGetMethod(true).IsVirtual; // True!
bool virtualSetter = p.GetSetMethod(true).IsVirtual; // False
</code></pre>
<p>Why does virtualGetter get set to True? I expected false, given that the property is neither <strong>abstract</strong> nor <strong>virtual</strong>.</p>
<p>For completeness - and for the remote possibilty they are relevant, here are the declarations for BusinessEntityKey, IProcessingContextKey, and IBusinessEntityKey:</p>
<pre><code>public abstract class BusinessEntityKey : IBusinessEntityKey
{
public abstract Type GetEntityType();
}
public interface IProcessingContextKey : IBusinessEntityKey
{
int DbKey { get; }
}
public interface IBusinessEntityKey
{
Type GetEntityType();
}
</code></pre>
<p>Thanks in advance for your help.</p>
<p><strong>Clarification</strong> - why does this matter to me?</p>
<p>We're using NHibernate and traced some issues with lazy loading to properties that were only half overridable - virtual getter but private setter. After fixing these up, we added a Unit test to catch any other places where this could occur:</p>
<pre><code>public void RequirePropertiesToBeCompletelyVirtualOrNot()
{
var properties
= typeof(FsisBusinessEntity).Assembly
.GetExportedTypes()
.Where(type => type.IsClass)
.SelectMany(
type =>
type.GetProperties(
BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic))
.Where(property => property.CanRead
&& property.CanWrite)
.Where(property =>
property.GetGetMethod(true).IsVirtual
!= property.GetSetMethod(true).IsVirtual);
Assert.That(
properties.Count(),
Is.EqualTo(0),
properties.Aggregate(
"Found : ",
(m, p) => m + string.Format("{0}.{1}; ",
p.DeclaringType.Name,
p.Name)));
}
</code></pre>
<p>This unit test was failing on the DbKey property mentioned above, and I didn't understand why.</p>
|
<p>It's virtual because it implements an interface method. Interface implementation methods are always virtual as far as the CLR is concerned.</p>
|
<p>The DbKey property getter is virtual in the IL because it is in an interface. The setter is not virtual because it is not part of the interface but part of the concrete class. </p>
<p><a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm" rel="nofollow noreferrer">ECMA-335: Common Language Infrastructure</a> Section 8.9.4 notes that:</p>
<blockquote>
<p>Interfaces can have static or virtual methods, but shall not have instance methods.</p>
</blockquote>
<p>Therefore the getter defined by your interface will be marked virtual when implemented in a derived class.</p>
| 41,691
|
<p>I have loaded image into a new, initialized Oracle ORDImage object and am processing it by PL/SQL. I can read its properties, but cannot process it with the process() method. </p>
<pre><code>vLocalImage ORDImage := ORDImage.init();
...
vLocalImage.source.localdata := PORTAL.wwdoc_admin.get_document_blob_content(pFile);
vLocalImage.setProperties();
...
if vLocalImage.width > lMaxWidth
then
vLocalImage.process('maxScale 534 401');
end if;
</code></pre>
<p>This should scale the image down, conserving aspect ratio, so that it is no more than 534 px wide and no more than 401 px high. </p>
<p>However, I get the following error stack:</p>
<pre><code>Internal error: ORA-29400: data cartridge error
IMG-00710: unable to write to destination image
ORA-01031: insufficient privileges
</code></pre>
<p>Trying other operations (like 'rotate 90') gives same errors.</p>
|
<p>Even though the documentation states that it should be possible to edit an ORDImage "in-place", I was unable to make it work. </p>
<p>Instead, I created a new ORDImage object and used processCopy:</p>
<pre><code> vNewImage ORDImage;
...
vLocalImage.processCopy('maxScale 534 401', vNewImage);
</code></pre>
|
<p>Can you please show the select statement you use to get l_ordimage? The main cause of this error seems to be if you don't have "for update" in your select statement, but I can't get intermedia going at the moment to test.</p>
| 11,053
|
<p>I've been coding alot of web-stuff all my life, rails lately. And i can always find a website to code, but i'm kind of bored with it. Been taking alot of courses of Java and C lately so i've become a bit interested in desktop application programming.</p>
<p>Problem: I can't for the life of me think of a thing to code for desktop. I just can't think of anything i can code that isn't already out there for download. So what do i do?
I need some project suggestions that i can set as a goal.</p>
|
<p>I would say you should roam through github or some other open source site and find an existing young or old project that you can contribute to. Maybe there is something that is barely off the ground, or maybe there is a mature project that could use some improvement.</p>
|
<p>If you could make a Ruby <a href="http://en.wikipedia.org/wiki/ANSI_art" rel="nofollow noreferrer">ANSI</a> (and <a href="http://en.wikipedia.org/wiki/XBIN" rel="nofollow noreferrer">xbin</a>, and idf, and adf...) Editor, I would love you. Because that means you would have written ANSI parsing routines that I can hope you release to the open source community.</p>
<p>... but that is a selfish answer. Oh, and a cross-platform editor would be nice as well (although <a href="http://sourceforge.net/projects/tundradraw/" rel="nofollow noreferrer">TundraDraw</a> somewhat takes care of that).</p>
| 11,403
|
<p>We need to move off traditional FTP for security purposes (it transmits it's passwords unencrypted). I am hearing SSH touted as the obvious alternative. However I have been driving FTP from an ASP.NET program interface to automate my web-site development, which is now quite a highly web-enabled process. </p>
<p>Can anyone recommend a secure way to transfer files around which has a program interface that I can drive from ASP.NET?</p>
|
<p>the question has three subquestions:</p>
<p>1) choosing the secure transfer protocol</p>
<p>The secure version of old FTP exists - it's called FTP/SSL (plain old FTP over SSL encrypted channel). Maybe you can still use your old deployment infrastructure - just check whether it supports the FTPS or FTP/SSL.</p>
<p>You can check details about FTP, FTP/SSL and SFTP differences at <a href="http://www.rebex.net/secure-ftp.net/" rel="nofollow noreferrer">http://www.rebex.net/secure-ftp.net/</a> page.</p>
<p>2) SFTP or FTP/SSL server for Windows</p>
<p>When you choose whether to use SFTP or FTPS you have to deploy the proper server. For FTP/SSL we use the Gene6 (<a href="http://www.g6ftpserver.com/" rel="nofollow noreferrer">http://www.g6ftpserver.com/</a>) on several servers without problems. There is plenty of FTP/SSL Windows servers so use whatever you want. The situation is a bit more complicated with SFTP server for Windows - there is only a few working implementations. The Bitvise WinHTTPD looks quite promising (<a href="http://www.bitvise.com/winsshd" rel="nofollow noreferrer">http://www.bitvise.com/winsshd</a>).</p>
<p>3) Internet File Transfer Component for ASP.NET</p>
<p>Last part of the solution is secure file transfer from asp.net. There is several components on the market. I would recommend the <a href="http://www.rebex.net/file-transfer-pack/" rel="nofollow noreferrer">Rebex File Transfer Pack</a> - it supports both FTP (and FTP/SSL) and SFTP (SSH File Transfer).</p>
<p>Following code shows how to upload a file to the server via SFTP. The code is taken from our <a href="http://www.rebex.net/sftp.net/tutorial-sftp.aspx#upload-download" rel="nofollow noreferrer">Rebex SFTP tutorial page</a>.</p>
<pre><code>// create client, connect and log in
Sftp client = new Sftp();
client.Connect(hostname);
client.Login(username, password);
// upload the 'test.zip' file to the current directory at the server
client.PutFile(@"c:\data\test.zip", "test.zip");
// upload the 'index.html' file to the specified directory at the server
client.PutFile(@"c:\data\index.html", "/wwwroot/index.html");
// download the 'test.zip' file from the current directory at the server
client.GetFile("test.zip", @"c:\data\test.zip");
// download the 'index.html' file from the specified directory at the server
client.GetFile("/wwwroot/index.html", @"c:\data\index.html");
// upload a text using a MemoryStream
string message = "Hello from Rebex SFTP for .NET!";
byte[] data = System.Text.Encoding.Default.GetBytes(message);
System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
client.PutFile(ms, "message.txt");
</code></pre>
<p>Martin</p>
|
<p>G'day,</p>
<p>You might like to look at <a href="http://www.proftpd.org/" rel="nofollow noreferrer">ProFPD</a>.</p>
<p>Heavily customisable. Based on Apache module structure.</p>
<p>From their web site:</p>
<blockquote>
<p>ProFTPD grew out of the desire to have a secure and configurable FTP server, and out of a significant admiration of the Apache web server.</p>
</blockquote>
<p>We use our adapted version for large scale transfer of web content. Typically 300,000 updates per day.</p>
<p>HTH</p>
<p>cheers,</p>
<p>Rob</p>
| 6,012
|
<p>As a function argument I get a <code>vector<double>& vec</code> (an output vector, hence non-const) with unknown length and values. I want to initialise this vector to a specific length n with all zeroes.</p>
<p>This will work </p>
<pre><code>vec.clear();
vec.resize( n, 0.0 );
</code></pre>
<p>And this will work as well:</p>
<pre><code>vec.resize( n );
vec.assign( n, 0.0 );
</code></pre>
<p>Is the second more efficient (because no memory deallocation/allocation is involved)? Is there a more efficient way to do this? </p>
|
<pre><code>std::vector<double>(n).swap(vec);
</code></pre>
<p>After this, vec is guaranteed to have size and capacity n, with all values 0.0.</p>
<p>Perhaps the more idiomatic way since C++11 is</p>
<pre><code>vec.assign(n, 0.);
vec.shrink_to_fit();
</code></pre>
<p>with the second line optional. In the case where <code>vec</code> starts off with more than <code>n</code> elements, whether to call <code>shrink_to_fit</code> is a trade-off between holding onto more memory than is required vs performing a re-allocation.</p>
|
<p>Well let's round out the ways to do this :)</p>
<pre><code>vec.swap(std::vector<double>(n));
std::vector<double>(n).swap(vec);
std::swap(vector<double>(n), vec);
std::swap(vec, vector<double>(n));
</code></pre>
| 20,967
|
<p>Testing:</p>
<pre><code>return request.getCookies() == null;
</code></pre>
<p>is not an appropriate way test. Is there another way?</p>
|
<p>You generally want to use JavaScript to determine if the client's browser has cookies enabled:</p>
<pre><code><script type="text/javascript">
var cookieEnabled=(navigator.cookieEnabled)? true : false
//if not IE4+ nor NS6+
if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){
document.cookie="testcookie"
cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false
}
//if (cookieEnabled) //if cookies are enabled on client's browser
//do whatever
</script>
</code></pre>
|
<p>You generally want to use JavaScript to determine if the client's browser has cookies enabled:</p>
<pre><code><script type="text/javascript">
var cookieEnabled=(navigator.cookieEnabled)? true : false
//if not IE4+ nor NS6+
if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){
document.cookie="testcookie"
cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false
}
//if (cookieEnabled) //if cookies are enabled on client's browser
//do whatever
</script>
</code></pre>
| 41,233
|
<p>I really enjoy Chrome, and the sheer exercise of helping a port would boost my knowledge-base.</p>
<p>Where do I start?</p>
<p>What are the fundamental similarities and differences between the code which will operated under Windows and Linux?</p>
<p>What skills and software do I need?</p>
<hr />
<h3>Note:</h3>
<p>The official website is Visual Studio oriented!<br />
Netbeans or Eclipse are my only options.<br />
I will not pay Microsoft to help an Open Source project.</p>
|
<p>EDIT: (2/6/10)</p>
<p>A Beta version of Chrome has been released for Linux. Although it is labeled beta, it works great on my Ubuntu box. You can download it from Google:</p>
<p><a href="http://www.google.com/chrome?platform=linux" rel="nofollow noreferrer">http://www.google.com/chrome?platform=linux</a></p>
<p>EDIT: (5/31/09)</p>
<p>Since I answered this question, there have been more new developments in Chrome (actually "Chromium") for Linux: An alpha build has been released. This means it's not fully functional.</p>
<p>If you use Ubuntu, you're in luck: add the following lines to your /etc/apt/sources.list</p>
<pre><code>deb http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main
deb-src http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main
</code></pre>
<p>Then, at the command line:</p>
<pre><code>aptitude update
aptitude install chromium-browser
</code></pre>
<p>Don't forget to s/jaunty/yourUbuntuVersion/ if necessary. Also, you can s/aptitude/apt-get/, if you insist.</p>
<p>And.... <strong>Yes</strong>, it works. I'm typing this in my freshly installed Chromium browser right now!</p>
<p>The build is hosted by launchpad, and gave me some security warnings upon install, which I promptly ignored. Here's the website: <a href="https://launchpad.net/~chromium-daily/+archive/ppa" rel="nofollow noreferrer">https://launchpad.net/~chromium-daily/+archive/ppa</a></p>
<p><strong><em>The original answer:</em></strong></p>
<p><a href="http://code.google.com/p/chromium/wiki/LinuxBuildInstructions" rel="nofollow noreferrer">Linux Build Instructions</a></p>
|
<p>Read this article on Chrome and Open Source on Linux:</p>
<p><a href="http://arstechnica.com/journals/linux.ars/2008/09/02/google-unveils-chrome-source-code-and-linux-port" rel="noreferrer">http://arstechnica.com/journals/linux.ars/2008/09/02/google-unveils-chrome-source-code-and-linux-port</a></p>
<p>The Google V8 JavaScript Engine is also open source and available here if you want to contribute;</p>
<p><a href="http://code.google.com/p/v8/" rel="noreferrer">http://code.google.com/p/v8/</a></p>
<p>If you want to contribute on Chronium, here are the instructions:</p>
<p><a href="http://dev.chromium.org/developers/contributing-code" rel="noreferrer">http://dev.chromium.org/developers/contributing-code</a></p>
<blockquote>
<p><a href="http://dev.chromium.org/Home" rel="noreferrer">Chromium</a> is an open-source browser
project that aims to build a safer,
faster, and more stable way for all
Internet users to experience the web.
This site contains design documents,
architecture overviews, testing
information, and more to help you
learn to build and work with the
Chromium source code.</p>
</blockquote>
<p>Here is how you can get started:</p>
<p><a href="http://dev.chromium.org/developers/how-tos/getting-started" rel="noreferrer">http://dev.chromium.org/developers/how-tos/getting-started</a></p>
<hr>
<p>EDIT: Two more questions was added to the original question.</p>
<p>Building on Linux requires the following software:</p>
<ul>
<li>Subversion >= 1.4 </li>
<li>pkg-config >= 0.20</li>
<li>Python >= 2.4</li>
<li>Perl >= 5.x</li>
<li>gcc/g++ >= 4.2</li>
<li>bison >= 2.3</li>
<li>flex >= 2.5.34</li>
<li>gperf >= 3.0.3</li>
<li>libnss3-dev >= 3.12</li>
</ul>
<p>On Ubuntu 8.04, you can fetch all of the above as follows:</p>
<pre><code>$ sudo apt-get install subversion pkg-config python perl g++ bison flex gperf libnss3-dev
</code></pre>
<blockquote>
<p><strong>Note</strong>: There is no working
Chromium-based browser on Linux.
Although many Chromium submodules
build under Linux and a few unit tests
pass, all that runs is a command-line
"all tests pass" executable.</p>
</blockquote>
| 7,060
|
<p>In my current application I have a form that requires the user to enter TONS of data. There are about 30 Textboxes and it happens that during development new ones get introduced or old ones get kicked out.</p>
<p>One Requirement by my customer is that they are all navigable through pressing Tab, and so I'm currently at the mercy of the TabIndex property if I see that correctly.</p>
<p>At the beginning I set those properties manually, but that required me to re-index them whenever I changed something.</p>
<p>I already tried to counter that problem by adding all FormDesigner generated controls to a List and loop through that list while setting the tabindex for the controls in that list.</p>
<p>Still, it doesn't work. Some of my controls still get focused out of order. I haven't really found a workaround, but will find one.</p>
<p>My question now is, why in the heck am I doing something like that in the first place?
Is there some better way to handle tab-indexes or is this really how it's going to be? I mean, I was spending hours with that stupid designer setting tabindexes!</p>
|
<p>When the forms designer is open go to View -> Tab Order this will allow you to set the tab order in a very simple and easy way.</p>
|
<p>Here is something you might want to give a try. From <a href="http://www.codeproject.com/KB/dotnet/TabOrderManager.aspx" rel="nofollow noreferrer">Code project</a>. This will organize your tab index by 2 logicals ways.</p>
<p><img src="https://www.codeproject.com/KB/dotnet/TabOrderManager/TabOrderManager.gif" alt="alt text"></p>
| 40,559
|
<pre>
<code>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Calling a Web Service Using XmlHttpRequest</title>
<script type="text/javascript" language="javascript">
var xmlhttp;
var XMLContent='<XML ID="Transaction"><Transaction>'+
'<LoginDetails>'+
'<Email>artur</Email>'+
'<Password>demos2</Password>'+
'</LoginDetails>'+
'<JobDetails>'+
'<JobId>40170978</JobId>'+
'<JobRefNo>prod84</JobRefNo>'+
'<JobTitle>'+
'<![CDATA[ Director of R&D Software product (Multimedia)]]>'+
'</JobTitle>'+
'<JobExpiry>30</JobExpiry>'+
'<JobContactName>'+
'<![CDATA[ Brian Mc Fadden]]>'+
'</JobContactName>'+
'<JobContactEmail>brian.mcfadden@recruiters.ie</JobContactEmail>'+
'<JobShortDesc>'+
'<![CDATA[ Director of R&D Software product concepts Multimedia Web 2.0]]> '+
'</JobShortDesc>'+
'<JobDetDesc><![CDATA[ <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt; mso-margin-top-alt: auto; mso-margin-bottom-alt: auto"><STRONG>Director of R&D Software product concepts to</STRONG> build a the new prototyping team and processes from the ground up, utilizing an agile development model, manage the R&D team develop a strong vision and be able to clearly articulate the direction the group will take in terms of methodologies and tools in technologies such as J2EE, .NET, Flash, AJAX, DHTML, JavaScript, take marketing requirements from the principal investigators and write functional requirement documents, manage budget for R&D development, manage the projects developed by the internal team and vendors. </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt; mso-margin-top-alt: auto; mso-margin-bottom-alt: auto">To get this new role you will have a degree in IT / Software and over 5 years plus doing cutting edge development in R&D/ prototyping and leading cutting edge development teams in a software production / product environment, project management and process management skills (AGILE) and demonstrated experience working on product innovation and releases. You may be working in educational gaming, social networking, Web 2.0 applications, mobile technologies, learning management systems, online courseware or shareware. </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt; mso-margin-top-alt: auto; mso-margin-bottom-alt: auto"> </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt">The package is to €105K + Bonus + VHI + Pension + relocation package where applicable + stock options may be negotiated. There are great career advancement opportunities. To discuss this and other opportunities please send an up-to-date resume to <A href="mailto:brian.mcfadden@recruiters.ie">brian.mcfadden@recruiters.ie</A> or call +353 1 6489113 in confidence. Your details will not be sent to any third party without your consent. </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"> </P>]]>'+
'</JobDetDesc>'+
'<JobSalary>90000</JobSalary>'+
'<JobSalaryMax>105000</JobSalaryMax>'+
'<JobQues1><![CDATA[ ]]>'+
'</JobQues1>'+
'<JobQues2><![CDATA[ ]]>'+
'</JobQues2>'+
'<JobQues3><![CDATA[ ]]>'+
'</JobQues3>'+
'<JobType>0|0</JobType>'+
'<JobAddnlBens>17,14,23,1,5,9,12,10</JobAddnlBens>'+
'<JobLocations>96,98,97</JobLocations>'+
'<JobEducations>8</JobEducations>'+
'<JobExperiences>10</JobExperiences>'+
'<JobCategories>1043,1050</JobCategories>'+
'<JobSubcategories>69896,69869</JobSubcategories>'+
'</JobDetails>'+
'</Transaction>'+
'</XML>';
function on_click()
{
if(window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (ex)
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
}
else if (window.XMLHttpRequest)
{
xmlhttp = new window.XMLHttpRequest();
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
}
var xmlToSend = '<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
'<soap:Body>'+
'<InsertXML xmlns="http://recpushdata.cyndigo.com/">'+
'<Jobs>'+XMLContent+'</Jobs>'+
'</InsertXML>'+
'</soap:Body>'+
'</soap:Envelope>';
var szUrl;
szUrl = 'http://recpushdata.cyndigo.com/Jobs.asmx?op=InsertXML';
xmlhttp.onreadystatechange = state_Change;
xmlhttp.open("Post", szUrl, true);
xmlhttp.setRequestHeader ("SOAPAction", "http://recpushdata.cyndigo.com/InsertXML");
xmlhttp.setRequestHeader ("Content-Type", "text/xml");
xmlhttp.send(xmlToSend);
}
function state_Change()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4)
{
// if "OK"
if (xmlhttp.status==200)
{
alert("OK"+xmlhttp.responseText);
}
else
{
alert("Problem retrieving XML data "+xmlhttp.responseText);
}
}
}
</script>
</head>
<body>
<div>
<h1>
Click the button to call the web service</h1>
<input type="button" onclick="return on_click();" value="OK" />
</div>
<div id="responseDiv">
</div>
</body>
</html>
</code>
</pre>
|
<p>XmlHttpRequest can only be used to call services local to the domain/server from where the page is being served.</p>
<p>Thus, if you're serving a page from:</p>
<pre><code>http://www.example.com/page1
</code></pre>
<p>You cannot make an XmlHttpRequest to:</p>
<pre><code>http://www.sample.com/webservice
</code></pre>
|
<p>Since you're setting <code>Content-type</code>, you need to also set it to use <code>UTF-8</code>. And I think it's supposed to be <code>application/xml</code> (<a href="http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest" rel="nofollow noreferrer">source</a>).</p>
<pre><code>xmlhttp.setRequestHeader("Content-Type", "application/xml; charset=utf-8");
</code></pre>
<p>Otherwise, have you verified that the XML is properly formatted? Try saving it as a complete XML file and open it in your browser.</p>
| 46,305
|
<p>I'm trying to load javascript code with a user web control into a page via a the Page.LoadControl method during an asyncron post back of an update panel.</p>
<p>I've tried the specially for that scenario designed methods of the scriptmanager, but the javascript just doens't get returned to the user.</p>
<p>To explain my scenario a bit better:</p>
<p>Master Page has the script manager and one page loads the user control via Page.LoadControl-method during an async post back. The custom control injects in the pre-render event handler the javascript. Is that a matter of timing to inject the js or is it just not possible to do so?</p>
|
<p>For that you can do</p>
<pre><code>string scr;
scr = "<script src='/scripts/myscript.js'></script>"
Page.ClientScript.RegisterStartupScript(GetType(Page), "key", scr, false)
</code></pre>
<p>HTH</p>
|
<p>Putting the RegisterStartupScript in the Page_PreRender event may not work if your control is nested in an asp.net modal popup. Instead, put it in the Page_Load when IsPostBack = False.</p>
| 38,678
|
<p>Does someone knows if it's possible to dynamically create a call chain and invoke it?</p>
<p>Lets say I have two classes A & B:</p>
<pre><code>public class A
public function Func() as B
return new B()
end function
end class
public class B
public function Name() as string
return "a string";
end function
end class
</code></pre>
<p>I want to be able to get <em>MethodInfo</em> for both <em>Func()</em> & <em>Name()</em> and invoke them dynamically so that I can get a call similar to <em>A.Func().Name()</em>.</p>
<p>I know I can use <em>Delegate.CreateDelegate</em> to create a delegate I can invoke from the two <em>MethodInfo</em> objects but this way I can only call the two functions separately and not as part of a call chain.</p>
<p>I would like two solutions one for .NET 3.5 using expression tree and if possible a solution that is .NET 2.0 compatible as well</p>
|
<p>Are you using .NET 3.5? If so, it should be relatively straightforward to build an expression tree to represent this. I don't have enough expression-tree-fu to easily write the relevant tree without VS open, but if you confirm that it's an option, I'll get to work in notepad (from my Eee... hence the lack of VS).</p>
<p>EDIT: Okay, as an expression tree, you want something like (C# code, but I'm sure you can translate):</p>
<pre><code>// I assume you've already got fMethodInfo and nameMethodInfo.
Expression fCall = Expression.Call(null, fMethodInfo);
Expression nameCall = Expression.Call(fCall, nameMethodInfo);
Expression<Func<string>> lambda = Expression.Lambda<Func<string>>(nameCall, null);
Func<string> compiled = lambda.Compile();
</code></pre>
<p>This is untested, but I think it should work...</p>
|
<p>You need t add this line before the 1st expression:</p>
<pre><code>Expression ctorCall = Expression.Constructor(A)
</code></pre>
<p>And pass that expression as the 1st parameter when creating fCall</p>
<p>Otherwise we're missing a starting point for the chain and we'll get an exception when running the code</p>
| 45,564
|
<p>Is there a <code>Python</code> module for converting <code>wiki markup</code> to other languages (e.g. <code>HTML</code>)?</p>
<p>A similar question was asked here, <a href="https://stackoverflow.com/questions/45991/whats-the-easiest-way-to-convert-wiki-markup-to-html">What's the easiest way to convert wiki markup to html</a>, but no <code>Python</code> modules are mentioned.</p>
<p>Just curious. :) Cheers.</p>
|
<p><a href="https://github.com/pediapress/mwlib" rel="nofollow noreferrer">mwlib</a> provides ways of converting MediaWiki formatted text into HTML, PDF, DocBook and OpenOffice formats.</p>
|
<p>with python-creole you can convert html to creole and creole to html... So you can convert other markups to html and then to creole...</p>
<p><a href="https://code.google.com/p/python-creole/" rel="nofollow">https://code.google.com/p/python-creole/</a></p>
| 18,689
|
<p>I have been playing with Haml recently and really like the way the resulting code looks to me...the developer. I'm also not too worried about a designer being able to consume or change it...we're a small team. </p>
<p>That said, beginning work on a project we believe will generate quite a bit of traffic (who doesn't?). I'm concerned that there are things I just don't know about haml. Is there anything erb can do that haml can't? Does haml have a negative effect as a project grows? Are there other things that should be considered?</p>
<p>And finally...how does Haml compare speedwise to erubis? I see that it supposedly beats erb and eruby now...</p>
<p>Thanks!</p>
|
<p>Haml rocks. I haven't seen any recent performance numbers but it is pretty close to erb these days. I think that it might be faster than erb if you turn on ugly mode (which prevents the pretty indentation) We're doing 2.8 million pageviews a day with Haml.</p>
<p>There is a benchmarker checked into the Haml source tree:
<a href="http://github.com/nex3/haml/tree/master/test" rel="noreferrer">http://github.com/nex3/haml/tree/master/test</a></p>
<p><strong>Update November 2009</strong></p>
<p>Nathan (Haml's main developer) <a href="http://nex-3.com/posts/87-haml-benchmark-numbers-for-2-2" rel="noreferrer">published some Haml 2.2 benchmarks</a> on his blog. You can see the exact numbers there but in short:</p>
<ul>
<li>Normal (pretty printing) mode = 2.8 times slower than ERB</li>
<li>Ugly mode (no pretty tabs added) = equal to ERB</li>
</ul>
<p>You can enable ugly mode by placing <code>Haml::Template::options[:ugly] = true</code> in an initializer or environment file. Note that ugly mode isn't really that ugly - the resulting HTML is actually much prettier than ERB - it's just not indented nicely.</p>
|
<p>Well, Haml performance continues to improve with each release. Is it at an acceptable place at the current time? That's for you to decide (I'm inclined to say "Yes", but it's your choice based on your needs). If you like the templates and the readability they provide, then the performance drop (however negligible) should really be the final factor in your decision.</p>
<p>One of the other tools you should consider using in conjunction with Haml is make_resourceful, another gem by the maintainer of Haml (Nathan Weizenbaum) that simplifies a lot of the RESTful things in a Rails app.</p>
<p>If you have any further, more specific questions about Haml (and m_r), I'm sure Nathan would be more than happy to answer them. He can be reached via Jabber/XMPP and email. His contact information can be found <a href="http://nex-3.com/about" rel="nofollow noreferrer">here</a>.</p>
| 12,133
|
<p>I'm a rookie designer having a few troubles with this page: <a href="http://www.resolvegroup.co.nz/javasurvey.php" rel="nofollow noreferrer">http://www.resolvegroup.co.nz/javasurvey.php</a></p>
<p>There are problems with the javascript operation of the expanded questions. For Internet Explorer (Version 7) the first question when expanded gets partly hidden under question 2. This happens to varying degrees with all questions, at times making the next question completely hidden and other problems.</p>
<p>Firefox (Version 3.03) does not have the problem as above, but you cannot get access to the explanations or select next question as in IE7.</p>
<p>Does anyone know what's going on with this, and how to fix it?</p>
|
<p>I'd recommend looking at using a pre-built Accordion script, like that built into the jQuery UI library: <a href="http://docs.jquery.com/UI/Accordion" rel="nofollow noreferrer">http://docs.jquery.com/UI/Accordion</a></p>
<hr>
<p>Also, there's a few things I could suggest. This code of yours:</p>
<pre><code>$(".score-list").slideUp(speed);
$(".score-list").removeClass("open");
$("a.open-answer").removeClass("hidden");
$(this).parent().children(".score-list").slideDown(speed);
$(this).parent().children(".score-list").toggleClass("open");
$(this).toggleClass("hidden");
</code></pre>
<p>could be made a lot more efficient by storing the results from a jQuery query, as well as taking advantage of jQuery's chaining abilities: quite a lot of jQuery's functions return the jQuery object itself, which means you can call a number of functions in a row without having to reference the object again and again. Here's what I mean:</p>
<pre><code>$(".score-list") // my own preference is to split the calls onto
.slideUp(speed) // multiple lines to make it easier to read.
.removeClass("open")
;
$("a.open-answer").removeClass("hidden");
var $this = $(this); // store the result from a query in an object so you
// don't have to go through that again.
$this
.parent()
.children(".score-list")
.slideDown(speed);
.toggleClass("open")
;
$this.toggleClass("hidden");
</code></pre>
|
<p>If I'm not mistaken, your CSS has some wonkiness. ".question-container h3" and ".question-container h3 span" have relative and absolute positioning, respectively. Internet Explorer does not handle out-of-flow positioning very well. In result, it gets confused and tries to place these elements in weird places.</p>
<p>Construct the accordion without relative or absolute positioning and it should work fine.</p>
| 28,771
|
<p>I am writing some G-code for my DIY 3D printer. From what I understand, <code>G4</code> is dwell and its expressed in milliseconds. So my extruder takes about 30 seconds to heat up. Do I just type </p>
<pre><code>G04 30000
</code></pre>
|
<p>You are correct about needing to specify the dwell value in milliseconds. However, the RepRap Wiki indicates that you need to use the <code>Pn</code> argument, and not just an unadorned number as the argument to the command. To adapt the Wiki's own example, you will need to use:</p>
<pre><code>G4 P30000
</code></pre>
<p>This should cause the firmware to dwell (pause) for 30 seconds.</p>
<p><a href="http://reprap.org/wiki/G-code#G4:_Dwell" rel="nofollow noreferrer">RepRap Wiki: G4: Dwell</a></p>
|
<p>Depending on your G-code flavor you may be able to use <a href="https://reprap.org/wiki/G-code#M109:_Set_Extruder_Temperature_and_Wait" rel="nofollow noreferrer"><code>M109</code></a> (heat and wait) instead. If supported M109 will wait until the target temperature is achieved.</p>
| 716
|
<p>I am writing PHP code where I want to pass the session id myself using POST. I don't want a cookie to store the session, as it should get lost when the user gets out of the POST cycle.</p>
<p>PHP automatically sets the cookie where available. I learned it is possible to change this behaviour by setting <code>session.use_cookies</code> to 0 in <code>php.ini</code>. Unfortunately, I don't have access to that file and I also wouldn't want to break the behaviour of other scripts running on the same server.</p>
<p>Is there a way to disable or void the session cookie inside the PHP script?</p>
<p><strong>EDIT:</strong> As the proposed solutions don't work for me, I used $_SESSION = array() at positions in the code where I found the session should be invalidated.</p>
|
<p>Use <a href="http://php.net/ini_set" rel="noreferrer">ini_set()</a>:</p>
<pre><code>ini_set('session.use_cookies', '0');
</code></pre>
<p>Or in your php.ini file:</p>
<pre><code>session.use_cookies = 0
</code></pre>
|
<p>The way to do it is to setup sessions yourself.</p>
<p>In the central include file that all your other files are including (you do have one of those, right?), you need to do a few things as early as is practical. </p>
<pre><code>if( !array_key_exists('sessionid', $_POST) ) {
// recreate the sessionid
$sessionid = md5(rand().' '.microtime()); // Or something
} else {
$sessionid = $_POST['sessionid'];
session_id($sessionid);
session_start();
</code></pre>
<p>Now you have to remember that as soon as you start the form, you need to include:</p>
<pre><code><input type='hidden' name='sessionid'><?= session_id() ?></input>
</code></pre>
| 29,920
|
<p>I'm hearing that some people believe storing info on the server in a session is a bad idea, that its not secure.<br><br>
As a result, in a multi-page business process function, the application is writing data to a db, then retrieving the info when its needed.
Is there something necessarily unsafe about storing private info in a session?</p>
|
<p>There's not a security risk in storing attributes in a Session, as long as the session itself is safe from <a href="http://www.owasp.org/index.php/Session_hijacking_attack" rel="noreferrer">hijacking</a>. </p>
<p>There are some serious issues involving concurrency and sessions. Since its extremely common for multiple threads to be making requests concurrently for a single session, you have to make sure that the objects you store in a Session are thread safe. Either make them immutable, or make them thread safe with memory barriers like synchronization. I highly recommend an <a href="http://www.ibm.com/developerworks/library/j-jtp09238.html" rel="noreferrer">article on the subject by Brian Goetz</a>.</p>
|
<p>As well as performance and concurrency issues, you should also think about usability. Do multiple open pages, the back button work, bookmarks, linking to your site, etc., work? I've ended up booking a flight on the wrong day on <code>aerlingus.ie</code> and almost booking the wrong hotel on <code>lastminute.com</code> because of their dismal web sites.</p>
| 44,089
|
<p>I want to create a <strong>List</strong> of <strong>KeyValuePair</strong>s in a managed C++ project. Here is the syntax I'm using</p>
<pre><code>List<KeyValuePair<String^, String^>^>^ thing;
</code></pre>
<p>but I'm getting the following error:</p>
<blockquote>
<p>error C3225: generic type argument for 'T' cannot be 'System::Collections::Generic::KeyValuePair ^', it must be a value type or a handle to a reference type</p>
</blockquote>
<p>I basically want to do this (C#)</p>
<pre><code>List<KeyValuePair<string, string>> thing;
</code></pre>
<p>but in managed C++. Oh and in .Net 2.0. Any takers?</p>
|
<blockquote>
<p>KeyValuePair does not itself need to be a handle. Duh.</p>
</blockquote>
<p>Because it's a value type, not a reference type (i.e. <code>struct</code> instead of <code>class</code> in C#).</p>
|
<p>Figured it out:</p>
<pre><code>List<KeyValuePair<String^, String^>>^ thing;
</code></pre>
<p>KeyValuePair does not itself need to be a handle. Duh.</p>
| 44,388
|
<p>I just saw a really cool WPF twitter client that I think is developed by the Herding Code podcast guys <a href="http://www.herdingcode.com/" rel="noreferrer">HerdingCode</a> called <a href="http://code.google.com/p/wittytwitter/" rel="noreferrer">Witty</a>. (or at least, I see a lot of those guys using this client). This project is currently posted up on Google Code.</p>
<p>Many of the projects on Google Code use Subversion as the version control system (including Witty). Having never used Subversion, I'm not sure what to do to download the code. </p>
<p>On the source page for this project (<a href="http://code.google.com/p/wittytwitter/source/checkout" rel="noreferrer">google code witty source</a>) it gives the following instruction:</p>
<p><strong>Non-members may check out a read-only working copy anonymously over HTTP.</strong> <br>
<strong><em>svn checkout <a href="http://wittytwitter.googlecode.com/svn/trunk/" rel="noreferrer">http://wittytwitter.googlecode.com/svn/trunk/</a> wittytwitter-read-only</em></strong> </p>
<p>I'm confused as to where I am supposed to enter the above command so that I can download the code.</p>
<p>I have installed SVN and Tortoise (which I know almost nothing about). </p>
<p>Thanks for any help or simply pointing me in the right direction.</p>
<p>...Ed (@emcpadden)</p>
|
<p>After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for <code>SVN Checkout</code>. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".</p>
|
<p>The manual explains how to checkout code: </p>
<p><a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-checkout.html" rel="nofollow noreferrer">http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-checkout.html</a></p>
| 6,315
|
<p>I'm interested in selectively parsing Mediawiki XML markup to generate a customized HTML page that's some subset of the HTML produced by the actual PHP Mediawiki render engine.</p>
<p>I want it for BzReader, an offline Mediawiki compressed dump reader written in C#. So a C# parser would be ideal, but any good code would help.</p>
<p>Of course, if no one has done it before, I guess it's time to start a project maintaining a free and separate Mediawiki parser, based on Mediawiki's own parser, but less tightly integrated with Mediawiki itself.</p>
<p>So, does anyone know of any base I could begin with, that would be better than hacking from the Mediawiki PHP code?</p>
|
<p>There is a list of parsers on <a href="http://www.mediawiki.org/wiki/Alternative_parsers" rel="noreferrer">http://www.mediawiki.org/wiki/Alternative_parsers</a>, but a c# parser is not included there...</p>
|
<p>I had some words to say about Mediawiki templates <a href="http://hewgill.com/journal/entries/343-the-abomination-of-mediawiki-templates" rel="nofollow noreferrer">here</a>. Interesting that there's a list of alternative parsers now, I'll have to investigate that.</p>
| 42,055
|
<p>I have a table <code>UserAliases</code> (<code>UserId, Alias</code>) with multiple aliases per user. I need to query it and return all aliases for a given user, the trick is to return them all in one column.</p>
<p>Example:</p>
<pre><code>UserId/Alias
1/MrX
1/MrY
1/MrA
2/Abc
2/Xyz
</code></pre>
<p>I want the query result in the following format:</p>
<pre><code>UserId/Alias
1/ MrX, MrY, MrA
2/ Abc, Xyz
</code></pre>
<p>Thank you.</p>
<p>I'm using SQL Server 2005.</p>
<p>p.s. actual T-SQL query would be appreciated :)</p>
|
<p>You can use a function with COALESCE.</p>
<pre><code>CREATE FUNCTION [dbo].[GetAliasesById]
(
@userID int
)
RETURNS varchar(max)
AS
BEGIN
declare @output varchar(max)
select @output = COALESCE(@output + ', ', '') + alias
from UserAliases
where userid = @userID
return @output
END
GO
SELECT UserID, dbo.GetAliasesByID(UserID)
FROM UserAliases
GROUP BY UserID
GO
</code></pre>
|
<p>group_concat() sounds like what you're looking for.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat</a></p>
<p>since you're on mssql, i just googled "group_concat mssql" and found a bunch of hits to recreate group_concat functionality. here's one of the hits i found:</p>
<p><a href="http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html" rel="nofollow noreferrer">http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html</a></p>
| 14,964
|
<p>I have a page that contains a user control that is just a personalized dropdown list . I assign to each item the attribute <code>onClick=__doPostBack('actrl',0)</code>.</p>
<p>when I click the page postback fine and I got the expected results. However in IE6 my page doesn't change to the new values loaded from the server.</p>
<p>The weird thing is that when I shift + click on the link The page reload fine with all changes. </p>
<p>I tried to disable caching on the page but no luck.</p>
<p>using all this code</p>
<pre><code>Response.CacheControl = "no-cache"
Response.AddHeader("Pragma", "no-cache")
Response.Expires = -1
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1))
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Page.Response.Cache.SetExpires(DateTime.Now.AddDays(-30))
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Page.Response.Cache.SetNoServerCaching()
Page.Response.Cache.SetNoStore()
Response.Cache.SetNoStore()
</code></pre>
<p>Also when I debug the application I can see that the generated html to be rendered is correct, but it is not rendered.</p>
<p>This problem happens only in IE6.</p>
|
<p>This is a known IE6 bug (#223) with magical HTTP get requests.</p>
<p>See the bug here:
<a href="http://webbugtrack.blogspot.com/2007/09/bug-223-magical-http-get-requests-in.html" rel="nofollow noreferrer">http://webbugtrack.blogspot.com/2007/09/bug-223-magical-http-get-requests-in.html</a></p>
<p>It happens when an inline event handler causes a page change in IE6.</p>
|
<p>The problem is that IE6 is not reloading the page from the server (its just grabbing the cached copy), however on a form post IE6 SHOULD reload. Why are you adding the _doPostBack as an attribute, those should be autogenerated on any asp.net control that needs to post back.</p>
| 25,310
|
<p>Is it possible (by using the stock c# TreeView) to have Multiline TreeNodes? </p>
<p>Also, is it possible to add control characters to TreeNode's text e.g. '\t'? This same effect could also be achieved by adding columns to the TreeNode. is this possible?</p>
|
<p>I do not believe this is possible using WinForms, at least without drawing your own nodes. You may be able to use an "owner-drawn" treenode to accomplish this in WinForms, though, I don't know. </p>
<p>This is natively supported with WPF, though.</p>
|
<p>It is not possible to use the tabulator effectively inside a TreeNode.
Anyways, I have a workaround:</p>
<p>The Font "Consolas" has equal space of each letter so you can space easily with blanks. The method GetEmptyInfoByIndex returns a custom lenght string of spaces to fill the gap until a specified length. Here = 20.</p>
<pre><code>mynode.NodeFont = new System.Drawing.Font("Consolas", 9,FontStyle.Regular);
string displaytext = String.Format(CultureInfo.InvariantCulture, "{0}{2} = {1}", mystringOfDifferentLenght, myresult, GetEmptyInfoByIndex(mystringOfDifferentLength, 20));
mynode.Text = displaytext;
rootnode.Nodes.Add(mynode);
private string GetEmptyInfoByIndex(string _string, int maxLength)
{
string retstr = string.Empty;
for (int i = 0; i < maxLength - _string.Length; i++)
{
retstr += " ";
}
return retstr;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/fWCAx.jpg" rel="nofollow noreferrer">Proof here!</a></p>
| 38,697
|
<p>Code I'm working on collects performance data (eg CPU usage) from the operating system. I'm wondering if I should bother to attempt to unit test this code. It seems that to unit test code, you need to design code that is isolated into units. My code is so closely tied to the OS though that if I isolated the code out that interacts with the OS into a wrapper that I could mock out, there wouldn't be much left to test.</p>
<p>So, I'm thinking unit testing won't work here. Am I misunderstanding how I should use unit tests? Everybody in blogs I read preaches that they're good, but I'm not sure they're useful for all application domains.</p>
<p>Eg, if I move this code to a different version of the OS, I'm sure there will be lots of bugs, but I can't see how unit tests could help me find them.</p>
<p>Have you found the same problem? Should I even attempt to write unit tests for this?</p>
|
<p>Do you have any business logic? Calculations? or are you just grabbing and displaying data?</p>
<p>Unit testing is useful for, well, testing units. In other words are the any parts of you app that can work in isolation? If not, then theres not really anything to unit test.</p>
<p>Functional tests are another story...</p>
|
<p>Sounds like you could benefit from some basic tests, like: "Does this entire module squirt any out any data when I port it to another operating system?", but beyond that, be pragmatic.</p>
<p>If doing it doesn't actually help you, don't do it. Tests for testing sake is an easy way to waste time to little avail.</p>
| 44,535
|
<p>I want to use typed parameters in the web methods. But when visual studio 2005 creates the web reference on for the client it automatically creates it's own types. I am using a .net web service and a .net client.</p>
<p>For example:</p>
<p>< WebMethod > _
Public Function Foo() as ServerNamespace.Bar
...
End Function</p>
<p>at the client the method becomes
WebServiceInstance.Foo() as ClientNamespace.Webservice.Bar</p>
<p>returning a different type.</p>
<p>I started writing my own serialization helper class to convert the type, but I would have thought there would be a better way....</p>
|
<p>If you can upgrade to .Net 3.0, I would suggest switching to WCF for your client proxy. Svcutil.exe is the tool to generate a WCF client proxy from the web service; it has an option /reference, which takes an assembly and reuses any shared types from it. (I would also suggest switchnig the service to WCF if it's under your control :-))</p>
<p>If you can't upgrade, wsdl.exe has an option /sharetypes which might help you, although I am not sure how to do it exactly.</p>
|
<p>I've asked the same question before, so the answers I got might be of help:</p>
<p><a href="https://stackoverflow.com/questions/216884/force-net-webservice-to-use-local-object-class-not-proxy-class">Force .NET webservice to use local object class, not proxy class</a></p>
| 27,733
|
<p><strong>Is there any way that I can remove the Print item from the context menu when you right-click on an email with VBA?</strong></p>
<p>I am forever right-clicking to reply to an email, only to accidentally click <code>Print</code> and have Outlook send it directly to the printer quicker than I can stop it.</p>
<p><img src="https://farm4.static.flickr.com/3221/2882658372_496d6e7a11_o.jpg" alt="alt text"></p>
<p><strong>NB:</strong> I am using Outlook 2007.</p>
|
<p>Based on the link TcKs provide, that was pretty simple.
In the example below I check the type of the item so that it only affects e-mails and not calendar items.
To enter the code in outlook, Type Alt + F11, then expand the Microsoft Office Outlook Objects in the Project pane. Then double click the ThisOutlookSession. Then paste this code into the code window. I don't like to check captions like this as you can run into issues with internationalization. But I didn't see an ActionID or anything on the Command. There was a FaceID but that is just the id of the printer icon.</p>
<pre class="lang-vb prettyprint-override"><code>Private Sub Application_ItemContextMenuDisplay(ByVal CommandBar As Office.CommandBar, ByVal Selection As Selection)
Dim cmdTemp As Office.CommandBarControl
If Selection.Count > 0 Then
Select Case TypeName(Selection.Item(1))
Case "MailItem"
For Each cmdTemp In CommandBar.Controls
If cmdTemp.Caption = "&Print" Then
cmdTemp.Delete
Exit For
End If
Next cmdTemp
Case Else
'Debug.Print TypeName(Selection.Item(1))
End Select
End If
End Sub
</code></pre>
|
<p>Thera is sample how to programaticly working with Outlook:
<a href="http://msdn.microsoft.com/en-us/library/bb176426.aspx" rel="noreferrer">How to: Customize an Item Context Menu</a></p>
| 14,812
|
<p>So most Java resources when speaking of packages mention a <code>com.yourcompany.project</code> setup. However, I do not work for a company, and don't have a website. Are there any naming conventions that are common? An email address, perhaps?</p>
|
<p>Use a top-level domain like 'bernard' or something else unique. The important part is that the domain is unique so that you avoid clashes, and not that it starts with a real Internet top-level domain like org or com. E.g.</p>
<pre><code>import java.util.*;
import bernard.myProject.*;
import org.apache.commons.lang.*;
</code></pre>
|
<p>For my own personal work when I don't have a namespace, I go for something simple like <code>org.<myname>.*</code></p>
| 20,051
|
<p>I need to create a really basic Adobe Illustrator file on the clipboard that I can paste in Adobe Illustrator or Expression Design. I'm looking for code samples on how to programmatically generate Adobe Illustrator Files, preferably from C# or some other .NET language (but at the moment any language goes).</p>
<p>I have found the Adobe Illustrator 3 File Format documentation online but it's allot to digest for this simple scenario.</p>
<p>I don't want to depend on the actual Adobe Illustrator program (COM interop for instance) to generate my documents. Must be pure code.</p>
<p>The code is for an Expression Studio addin, and I need to be able to create something on the clipboard I can paste into Expression Design. After looking at the formats Expression Design puts on the clipboard when copying a basic shape I've concluded that ADOBE AI3 i the best one to use (the others are either rendered images, or cfXaml that you cannot paste INTO Design).</p>
<p>So based on this I can't use SWG which would probably been easier.</p>
<p>Another idea might be to use a PDF component as the AI and PDF format is supposed to be compatible? I'm also finding some references to a format called "Adobe Illustrator Clipboard Format" (AICB), but can't find allot of documentation about it.</p>
|
<p>I know that Inkscape is free and open source and can edit .ai files.</p>
<p>This might be a place to start.
<a href="http://www.inkscape.org/" rel="noreferrer">http://www.inkscape.org/</a></p>
<p>Also, I think Illustrator can handle standard svg files, so maybe generating those would be a lot easier. (They are XML based)
<a href="http://www.w3.org/Graphics/SVG/" rel="noreferrer">http://www.w3.org/Graphics/SVG/</a></p>
|
<p>SVG is probably the way to go.</p>
| 13,819
|
<p>There's an option to hide the version so it will display only nginx, but is there a way to hide that too so it will not show anything or change the header?</p>
|
<p>Like Apache, this is a quick edit to the source and recompile. From <a href="https://calomel.org/nginx.html" rel="noreferrer">Calomel.org</a>:</p>
<blockquote>
<p>The Server: string is the header which
is sent back to the client to tell
them what type of http server you are
running and possibly what version.
This string is used by places like
Alexia and Netcraft to collect
statistics about how many and of what
type of web server are live on the
Internet. To support the author and
statistics for Nginx we recommend
keeping this string as is. But, for
security you may not want people to
know what you are running and you can
change this in the source code. Edit
the source file
<code>src/http/ngx_http_header_filter_module.c</code>
at look at lines 48 and 49. You can
change the String to anything you
want.</p>
</blockquote>
<pre><code>## vi src/http/ngx_http_header_filter_module.c (lines 48 and 49)
static char ngx_http_server_string[] = "Server: MyDomain.com" CRLF;
static char ngx_http_server_full_string[] = "Server: MyDomain.com" CRLF;
</code></pre>
<p><strong>March 2011 edit:</strong> Props to Flavius below for pointing out a new option, replacing Nginx's standard <a href="http://wiki.nginx.org/HttpHeadersModule" rel="noreferrer">HttpHeadersModule</a> with the forked <a href="http://wiki.nginx.org/HttpHeadersMoreModule" rel="noreferrer">HttpHeadersMoreModule</a>. Recompiling the standard module is still the quick fix, and makes sense if you want to use the standard module and won't be changing the server string often. But if you want more than that, the HttpHeadersMoreModule is a strong project and lets you do all sorts of runtime black magic with your HTTP headers.</p>
|
<p>Are you asking about the Server header value in the response? You can try changing that with an add_header directive, but I'm not sure if it'll work. <a href="http://wiki.codemongers.com/NginxHttpHeadersModule" rel="nofollow noreferrer">http://wiki.codemongers.com/NginxHttpHeadersModule</a></p>
| 30,554
|
<p>I want to write a command that specifies "the word under the cursor" in VIM. For instance, let's say I have the cursor on a word and I make it appear twice. For instance, if the word is "abc" and I want "abcabc" then I could type: </p>
<pre><code>:s/\(abc\)/\1\1/
</code></pre>
<p>But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef": </p>
<pre><code>:s/\(def\)/\1\1/
</code></pre>
<p>How can I write the command in the commandline so that it does this?</p>
<pre><code>:s/\(*whatever is under the commandline*\)/\1\1
</code></pre>
|
<p><code><cword></code> is the word under the cursor (:help <code><cword></code>).</p>
<p>Sorry, I should have been more complete in this answer.</p>
<p>You can nmap a command to it, or this series of keystrokes for the lazy will work:</p>
<pre><code>b #go to beginning of current word
yw #yank to register
</code></pre>
<p>Then, when you are typing in your pattern you can hit <code><control-r>0<enter></code> which will paste in your command the contents of the 0-th register.</p>
<p>You can also make a command for this like:</p>
<pre><code>:nmap <leader>w :s/\(<c-r>=expand("<cword>")<cr>\)/
</code></pre>
<p>Which will map hitting '\' and 'w' at the same time to replace your command line with</p>
<pre><code>:s/\(<currentword>\)/
</code></pre>
|
<pre><code>" count word (case sensitive)
nmap <F4> :%s/\(<c-r>=expand("<cword>")<cr>\)//gn<cr>
</code></pre>
| 7,111
|
<p>For reasons that we won't discuss, I have determined that MAMP is a pile of crap that haunts my system, and unless I remove it fully, I will live in shame.</p>
<p>I've done the obvious thing and removed the MAMP directory from my Applications folder, however, I don't like wandering files, and I have an itching feeling that MAMP put some .sock files somewhere, or otherwise made a mess in my file system.</p>
<p><strong>What files does MAMP add to a system when it's installed, and where are they?</strong></p>
<p><em>If you have proof that MAMP doesn't actually put files anywhere (besides the /MAMP dir), then that's as good an answer as any!</em></p>
|
<p>From their <a href="http://www.mamp.info/en/help.html" rel="noreferrer">help page</a>: </p>
<blockquote>
<p>To "uninstall" MAMP, you only have to
delete the MAMP directory and
everything returns to the original
state (MAMP does not alter anything on
the "normal" OS X).</p>
</blockquote>
|
<p>AppZapper is a great tool that solves this problem. Search Google for it, it's free for the first 5 time you use it.</p>
| 30,672
|
<p>One of the web apps I'm working on has a fairly small web store / shopping cart. As the client company is physically located in CA and has a physical location there, they're required to collect CA sales tax on all orders shipped to locations in California.</p>
<p>For those who don't know, CA has some fairly complex sales tax rules where, essentially, any local group can create a "tax district" and leverage an extra few cents worth of sales tax on top of the state-wide base of 7.25%. (Usually less than 1% extra.) These districts don't have to map to any other legislative borders, so you can end up with half a city paying an extra .25% sales tax, for example.</p>
<p>Technically, the law only requires that you charge the sales tax rate in your location as a seller - so, if I have a store here in Sacramento, I only need to charge Sacramento sales taxes on all orders shipped.</p>
<p>However, for various accounting and tax declaration reasons, it's actually easier to charge the sales tax of the location the order is being shipped <em>to</em>. (Which means a different sales tax, potentially, on every single order.)</p>
<p>So - my question. Is anyone aware of any slick ways to calculate this? The data you need to actually do the work is all available in a variety of semi-useful formats at the state Board of Equalization website, and we're knocking together a widget that tries to figure out sales tax based on things like city name and zip code. But, I was wondering if anyone has come across any cool tools out there for solving this problem. (Or any tools at all, for that matter.)</p>
<p>(We're using VB and ASP.net, but I'd be interested in solutions for any language, mainly because I'm fascinated to see how other people have solved this.)</p>
<p>Addendum - answering some questions from below:</p>
<p>Tim asks how this can possibly be "easier." I'm told that doing sales tax this way makes filling out your tax return simpler. I'm bleary on the details, but as I understand it, if you don't charge the rate for the shipping location, you have to justify why you didn't for every single order at the end of the year - namely, you have to attest that no, we live <em>here</em> and not <em>there</em>, so we charge the rate <em>here.</em></p>
<p>Whereas if you always charge the destination rate, you can (apparently) just put down the total amount of sales tax you collected for the whole year on one line, and say "sales tax was this much.</p>
<p>It would seem the state doesn't care which you do. So, by "easier," I really mean "easier for the accountants" - which is of course in no way easier for us here on the programming team.</p>
<p>Also, Schnapple's Texas story is a potential solution. (In fact, I pitched this very idea this morning.) CA really doesn't care if you overcharge sales tax, as long as you don't undercharge and hand over everything you collect. The problem here is, unlike Texas (apparently) vast swathes of CA are not in a special tax district. So, while we <em>could</em> charge the highest level for everyone (which I think is 8.75 at the moment), most of the customers would mind not playing their normal rate of 7.25. And I guess I can't blame them.</p>
|
<p>Texas does something similar - the state tax is 6.25%, then there's a local tax (like, County-specific or something) of 1% and an additional "mass transit" tax of 1%. The net effect is that when you go somewhere in Texas you pay 8.25% sales tax. And 8.25% was the maximum. In theory there could be some districts that don't charge a local tax but I've never run into any. Also in theory the local tax could be more than 1% and cause the mass transit tax to be less than 1% but again I've never seen it.</p>
<p>Years ago when I was a small business co-owner and we sold stuff online (downloadable data files) I went to a small seminar put on by the state to explain taxes to us. Since this was a small town I was in at the time, the local TV news came to cover the event (it was that boring of a town).</p>
<p>Either I or someone else asked at one point "You know, since it's complicated to figure out all this tax stuff, and it tends to be 8.25%, can't we just charge everyone 8.25% and send you that?.</p>
<p>The man running the seminar asked the film crew, "Is that thing filming?"</p>
<p>Once the film crew said no, he said "yeah, you can do that, we won't have any problem with it"</p>
<p>The form to submit sales tax at the time wasn't specific enough to part out where the items went in the state so we just charged 8.25% to everyone in Texas, nothing to everyone outside of Texas, and everyone was happy.</p>
<p>So you might be breaking your back over something California doesn't really care about anyway...</p>
|
<p>There are third-party resources that are just about indispensible for these sorts of ever-changing rules.</p>
<p><a href="http://www.avalara.com" rel="nofollow noreferrer">Here's one.</a> that's SaaS.</p>
| 38,890
|
<p>I have a 'foreach' macro I use frequently in C++ that works for most STL containers:</p>
<pre><code>#define foreach(var, container) \
for(typeof((container).begin()) var = (container).begin(); \
var != (container).end(); \
++var)
</code></pre>
<p>(Note that 'typeof' is a gcc extension.) It is used like this:</p>
<pre><code>std::vector< Blorgus > blorgi = ...;
foreach(blorgus, blorgi) {
blorgus->draw();
}
</code></pre>
<p>I would like to make something similar that iterates over a map's values. Call it "foreach_value", perhaps. So instead of writing</p>
<pre><code>foreach(pair, mymap) {
pair->second->foo();
}
</code></pre>
<p>I would write</p>
<pre><code>foreach_value(v, mymap) {
v.foo();
}
</code></pre>
<p>I can't come up with a macro that will do this, because it requires declaring two variables: the iterator and the value variable ('v', above). I don't know how to do that in the initializer of a for loop, even using gcc extensions. I could declare it just before the foreach_value call, but then it will conflict with other instances of the foreach_value macro in the same scope. If I could suffix the current line number to the iterator variable name, it would work, but I don't know how to do that.</p>
|
<p>You can do this using two loops. The first declares the iterator, with a name which is a function of the container variable (and you can make this uglier if you're worried about conflicts with your own code). The second declares the value variable.</p>
<pre><code>#define ci(container) container ## iter
#define foreach_value(var, container) \
for (typeof((container).begin()) ci(container) = container.begin(); \
ci(container) != container.end(); ) \
for (typeof(ci(container)->second)* var = &ci(container)->second; \
ci(container) != container.end(); \
(++ci(container) != container.end()) ? \
(var = &ci(container)->second) : var)
</code></pre>
<p>By using the same loop termination condition, the outer loop only happens once (and if you're lucky, gets optimized away). Also, you avoid calling ->second on the iterator if the map is empty. That's the same reason for the ternary operator in the increment of the inner loop; at the end, we just leave var at the last value, since it won't be referenced again.</p>
<p>You could inline ci(container), but I think it makes the macro more readable.</p>
|
<p>You could define a template class that takes the type of mymap as a template parameter, and acts like an iterator over the values by overloading * and ->.</p>
| 10,414
|
<p>This simple code is not producing any sound on a couple of machines that I've used to test it. I'm running the code from within Eclipse, but I've also tried using the command line to no avail. </p>
<pre><code>public static void main(String[] args)
{
try {
Synthesizer synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
MidiChannel[] channels = synthesizer.getChannels();
channels[0].noteOn(60, 60);
Thread.sleep(200);
channels[0].noteOff(60);
synthesizer.close();
} catch (Exception e)
{
e.printStackTrace();
}
}</code></pre>
<p>I am able to successfully get sound by getting a Sequencer, adding MIDI events to the sequence, and playing the sequence, but I'm trying to do some real-time music effects, which the sequencer does not support.</p>
<p>Any ideas?</p>
<p><strong>EDIT WITH SOLUTION:</strong> It turns out the problem is that, by default, the JRE doesn't come with a soundbank (interesting, then, that using the Sequencer worked, but using the Synthesizer didn't). Thanks, <a href="https://stackoverflow.com/users/54787/thejmc">thejmc</a>!</p>
<p>To solve the problem, I <a href="http://java.sun.com/products/java-media/sound/soundbanks.html" rel="nofollow noreferrer">downloaded a soundbank from java.sun.com</a> and placed it in (on WinXP) C:\Program Files\jre1.6.0_07\lib\audio (had to make the audio folder).</p>
|
<p>Some installs of the JRE do not include the JavaSound soundbank.gm (in order to save space) so your code would not have a sound source to trigger on those machines. </p>
<p>Check for the existence of the soundbank on the machines that don't work. You can also put the soundbank in the same directory as your .class file and it will find it.</p>
<p>It is possible to add the soundbank or to upgrade the Java install on those machine - the pain of inconsistency, I know :)</p>
|
<p>Have you tried to use different channel ?
May be <a href="http://forums.sun.com/thread.jspa?threadID=5237086" rel="nofollow noreferrer">this discusson</a> will get you closer to a solution...</p>
| 49,812
|
<p>I arrive to output a string on multiple lines inside a retangle but haven't find a way to reduce or enlarge the line spacing.
How to do that?</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/xwf9s90b.aspx" rel="noreferrer">This MSDN</a> should help you. Line spacing is a result of the Font you are using. You may need to break your DrawString commands up into multiple calls if you need custom line spacing.</p>
|
<p>This Microsoft forum posting may be helpful:</p>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1507414&SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1507414&SiteID=1</a></p>
<p>This shows how MeasureString can be used to determine how much of your text will fit on each line, then using this to progressively render the entire rectangle's contents line by line. Unfortunately I don't think there's a built-in line spacing property, so you'll have to go for the manual approach. The post's author uses the font's Height * 1.5.</p>
<p>It's also worth researching StringFormatFlags - you'll need to make sure both your DrawString and MeasureString calls use the same StringFormat so the rendering and measurement are consistent:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.drawing.stringformatflags.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.drawing.stringformatflags.aspx</a></p>
| 44,491
|
<p>A coworker has been struggling with this problem.</p>
<p>The desired result is an installable plugin for Notes that will add a button emails with attachments that will let users save the attachment to a document management system.</p>
<p>Finding documentation on doing this for Notes has been an uphill battle to say the least.</p>
<p>Writing the actual java to do the work isn't a problem, but figuring out how to extend Notes is.</p>
<p>So, is there a way to add a button/icon to the toolbar, or is it just a matter of adding a new toolbar? If we add a new toolbar then can we make it only visible (or just grey it out otherwise) when no email is open?</p>
|
<p>Both Lotus Notes 8+ and Lotus Symphony use the IBM Lotus Expeditor Toolkit. </p>
<p>If you get the Lotus Symphony SDK <a href="http://symphony.lotus.com/software/lotus/symphony/developers.nsf/home" rel="nofollow noreferrer">here</a>.</p>
<p>Their are one or two examples dealing with adding button's to the symphony toolbar. </p>
<p>They should translate almost identically to Notes. </p>
<p>Good Luck,</p>
<p>Brian Gianforcaro</p>
|
<p>I had to do this once in Notes for a plugin I was developing. What I ended up doing was editing the Notes template in the designer, and then writing some LotusScript behind it that called a .NET class via a DLL. So when you clicked the button, it triggered the event in the LotusScript, and then called the DLL, and passed the item information to it.</p>
<p>I should also note that it was a freakin' bear to figure out because Notes documentation is terrible.</p>
| 12,944
|
<p>I do my php work on my dev box at home, where I've got a rudimentary LAMP setup. When I look at my website on my home box, any numbers I echo are automatically truncated to the least required precision. Eg 2 is echoed as 2, 2.2000 is echoed as 2.2.</p>
<p>On the production box, all the numbers are echoed with at least one unnecessary zero, eg 100 becomes 100.0. On both boxes, the PHP version is 5.2.5. Does anyone know offhand if there is a setting I can change which will force PHP to automatically remove any unnecessary zeroes? I don't want to have to go to every place in my code where I output a number and replace echo with printf or something like that.</p>
<p>Muchas gracias.</p>
|
<p>And when you can't rely on the PHP configuration, don't forget about <a href="http://us.php.net/manual/en/function.number-format.php" rel="noreferrer">number_format()</a> which you can use to define how a number is returned, ex:</p>
<pre><code>// displays 3.14 as 3 and 4.00 as 4
print number_format($price, 0);
// display 4 as 4.00 and 1234.56 as 1,234.56 aka money style
print number_format($int, 2, ".", ",");
</code></pre>
<p>PS: and try to avoid using money_format(), as it won't work on Windows and some other boxes</p>
|
<p>Just to rule out other possible causes: Where are the numbers coming from? Does it do this with literal values?</p>
<p>It doesn't seem likely that the precision setting alone could cause this. Check also if anything might be interfering with the output via things like <code>auto_prepend_file</code> or <code>output_handler</code>.</p>
| 46,566
|
<p>I want to write a word addin that does some computations and updates some ui whenever the user types something or moves the current insertion point. From looking at the MSDN docs, I don't see any obvious way such as an TextTyped event on the document or application objects.</p>
<p>Does anyone know if this is possible without polling the document?</p>
|
<p>As you've probably discovered, <a href="http://msdn.microsoft.com/en-us/library/aa269681(office.10).aspx" rel="nofollow noreferrer">Word has events</a>, but they're for really coarse actions like a document open or a switch to another document. I'm guessing MS did this intentionally to prevent a crappy macro from slowing down typing.</p>
<p>In short, there's no great way to do what you want. <a href="http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.office.developer.com.add_ins&tid=4c3e438e-d9ab-4384-b29c-105175fd252e&cat=&lang=&cr=&sloc=&p=1" rel="nofollow noreferrer">A Word MVP confirms that in this thread.</a></p>
|
<p>As you've probably discovered, <a href="http://msdn.microsoft.com/en-us/library/aa269681(office.10).aspx" rel="nofollow noreferrer">Word has events</a>, but they're for really coarse actions like a document open or a switch to another document. I'm guessing MS did this intentionally to prevent a crappy macro from slowing down typing.</p>
<p>In short, there's no great way to do what you want. <a href="http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.office.developer.com.add_ins&tid=4c3e438e-d9ab-4384-b29c-105175fd252e&cat=&lang=&cr=&sloc=&p=1" rel="nofollow noreferrer">A Word MVP confirms that in this thread.</a></p>
| 7,957
|
<p>In a VB.Net Windows Service I'm currently pooling units of work with: </p>
<pre><code>ThreadPool.QueueUserWorkItem(operation, nextQueueID)
</code></pre>
<p>In each unit of work (or thread I'll use for ease of understanding), it will make a couple MSSQL operations like so: </p>
<pre><code> Using sqlcmd As New SqlCommand("", New SqlConnection(ConnString))
With sqlcmd
.CommandType = CommandType.Text
.CommandText = "UPDATE [some table]"
.Parameters.Add("@ID", SqlDbType.Int).Value = msgID
.Connection.Open()
.ExecuteNonQuery()
.Connection.Close() 'Found connections not closed quick enough'
End With
End Using
</code></pre>
<p>When running a <code>netstat -a -o</code> on the server I'm seeing about 50 connections to SQL server sitting on <code>IDLE</code> or <code>ESTABLISHED</code>, this seems excessive to me especially since we have much larger Web Applications that get by with 5-10 connections. </p>
<p>The connection string is global to the application (doesn't change), and has <code>Pooling=true</code> defined as well. </p>
<p>Now will each of these threads have their own <code>ConnectionPool</code>, or is there one <code>ConnectionPool</code> for the entire .EXE process?</p>
|
<p>From the MS Docs -</p>
<p>"Connections are pooled per process, per application domain, per connection string and when integrated security is used, per Windows identity"</p>
<p><a href="http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx</a></p>
<p>Are you experiencing errors such as -</p>
<p><em>Exception Details: System.InvalidOperationException: Timeout expired. The timeout
period elapsed prior to obtaining a connection from the pool. This may have occurred
because all pooled connections were in use and max pool size was reached.</em></p>
<p>Also how many work items are being queued in the service?</p>
|
<p>If the number of open connections offends you, take control in the <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx" rel="nofollow noreferrer">connection string</a></p>
<p>Notice: MinPoolSize and MaxPoolSize.</p>
| 15,902
|
<p>Our web application sends e-mails. We have lots of users, and we get lots of bounces. For example, user changes company and his company e-mail is no longer valid.</p>
<p>To find bounces, I parse SMTP log file with log parser. The logs come from Microsoft SMTP server.</p>
<p>Some bounces are great, like <code>550+#5.1.0+Address+rejected+user@domain.com</code>. There is <code>user@domain.com</code> in bounce.</p>
<p>But some do not have e-mail in error message, like <code>550+No+such+recipient</code>.</p>
<p>I have created simple Ruby script that parses logs (uses log parser) to find which mail caused something like <code>550+No+such+recipient</code>.</p>
<p>I am just surprised that I could not find a tool that does it. I have found tools like Zabbix and Splunk for log analysis, but they look like overkill for such simple task.</p>
<p>Anybody knows a tool that would parse SMTP logs, find bounces and e-mails that cause them?</p>
|
<p>This <a href="http://scriptolog.blogspot.com/2007/08/smtp-log-parsing.html" rel="noreferrer">article</a> is exactly what you are looking for. It is based on the great tool <a href="http://www.microsoft.com/technet/scriptcenter/tools/logparser/default.mspx" rel="noreferrer">log parser</a>.</p>
<blockquote>
<p>Log parser is a powerful, versatile
tool that provides universal query
access to text-based data such as log
files, XML files and CSV files, as
well as key data sources on the
Windows® operating system such as the
Event Log, the Registry, the file
system, and Active Directory®. You
tell Log Parser what information you
need and how you want it processed.
The results of your query can be
custom-formatted in text based output,
or they can be persisted to more
specialty targets like SQL, SYSLOG, or
a chart. Most software is designed to
accomplish a limited number of
specific tasks. Log Parser is
different... the number of ways it can
be used is limited only by the needs
and imagination of the user. The
world is your database with Log
Parser.</p>
</blockquote>
|
<p>I based a bounce counter program on this post, only to find out later that this method doesn't actually work for high-volume senders because SMTP logs are not in sequential order. There's more about it in my blog post: <a href="http://phreakhead.livejournal.com/74871.html" rel="nofollow noreferrer">Email Bounce Detection in SMTP Logs and Why It Is Impossible</a>.</p>
| 25,097
|
<p>I have an asp.net server control (with the asp: in its definition). The button has been set to do post back.</p>
<p>On the server side, I have the on click event handler
e.g btnSave_click()</p>
<p>On the client side, I have a javascript function to be invoked on the click event
e.g btnSave.Attributes.Add("onclick","javascript: return CheckIsDirty();")</p>
<p>Am not sure which order these two will be executed. Because I want first on the client side to warn of any data entry fields that are not yet filled-out before actually saving any data.</p>
<p>Any help?</p>
|
<p>First client side, second server-side.</p>
<p>So you can use it.</p>
<p>I also use it in some cases, like:</p>
<pre><code>close.Attributes["OnClick"] = "return confirm('Are you sure?')";
</code></pre>
<p>In this case if the user presses 'No' then the server-side event handler does not even play a role.</p>
|
<p>I think you need a much better understanding of what it means client side and what it means server side and how they all relate together. I've seen more and more developers make a mess of it.</p>
<p>Of course the client side will execute first in your case. Actually there's no way to execute it after the server code is executed (except if you do something manually). I'll try to give a brief explanation:</p>
<p>Whatever you have in your server, will generate some HTML on the client and the user is always interacting on the client. So you have a html button that the user is clicking. What the browser will do is execute the javascript associated with it or if no javascript is specified and the button is a submit button it will submit the form. if you check the generated html you will see that for the onclick event you will have the script you have added followed by some autogenerated script that actually will submit the form to the server. Your server side code will execute only if the page will be submitted.</p>
| 24,997
|
<p>I'm looking for an open-source SGML parser written in plain C. This is to parse bona-fide SGML, not malformed stuff.</p>
<p>Any ideas?</p>
|
<p>There's OpenSP, which is part of the <a href="http://sourceforge.net/projects/openjade/" rel="noreferrer">OpenJade</a> project, but is implemented in C++. Might be close enough for your needs?</p>
|
<p>This came up on a fast Google search (<a href="http://www.google.com/search?q=sgml+c+parser" rel="nofollow noreferrer">sgml c parser</a>): <a href="http://www.w3.org/Library/src/SGML.html" rel="nofollow noreferrer">http://www.w3.org/Library/src/SGML.html</a>. Does that help? </p>
<p>Or perhaps this one: <a href="http://www.math.utah.edu/pub/sgml/sgmls/" rel="nofollow noreferrer">http://www.math.utah.edu/pub/sgml/sgmls/</a></p>
| 37,558
|
<p>I have an http module on a sharepoint site and this module instantiates a custom class and add it to the session and does other initial things for my site.
However, I'm noticing that the http module is being called for all request types (.aspx, .js, .png, .jpg).</p>
<p>Is there any way to have an http module only be called for .net specific page types?</p>
|
<p>you can also set the :dependent option to :delete_all. :delete_all will issue a single SQL statement to delete all child records. because of this using :delete_all may give you better performance.</p>
<pre><code>has_many :memberships, dependent: :delete_all
</code></pre>
|
<p>It looks like this plugin might give you what you're looking for if you want the cascading deletes reflected in the actual database structure:</p>
<p><a href="http://www.redhillonrails.org/foreign_key_migrations.html" rel="noreferrer">http://www.redhillonrails.org/foreign_key_migrations.html</a></p>
<p>Format for using this in a migration would be something like this:</p>
<pre><code>create_table :orders do |t|
t.column :customer_id, :integer, :on_delete => :set_null, :on_update => :cascade
...
end
</code></pre>
| 42,937
|
<p>This might be a bit weird question, but I'll give it a shot:</p>
<p>HELP, my Visual Studio 2008 / ASP.NET is giving me GERMAN error messages. Besides the fact that translations tend to be not as good as the original text, I can't search for those and find relevant answers to my problems on the internet.</p>
<p>So: How do I switch my German Visual Studio 2008 Standard Edition to English locals?</p>
<hr>
<p>Update - Just to make it clear:</p>
<p>I am a German developer, working with a German Windows Vista... I also have a German version of Visual Studio, so it is not surprising, that everything is German. Is just don't want it that way... There must be a way to install english locals into my Visual Studio, though? Or uninstall german ones, so that default english is used?!?</p>
<p>(BTW: Same thing for SQL Server Management Studio, too. F**k "Sichten". I want "Views". That's how you really call them. No one says "Sichten", not even here in Germany, and not even though it is translated correctly).</p>
|
<p>Go to the Control Panel -> Software.
There are language packs for .NET (for each version one).
Uninstall them.</p>
|
<p>Check your system-wide language preferences - 'Regional and Language Options' in WinXP Control Panel. I have found when using VS that my keyboard would go from UK to US mode or even French because the SHIFT + ALT + F10 keystroke is used by VS for showing some context menus and it is also used by Windows as the keystroke for changing system language.</p>
<p>UPDATE:
Check your system-wide language preferences. If necessary install a language pack, though I can't find any on MS Download Center. Otherwise install an English language verison. I am about to download VS 2008 C# Express and I have the option of English, Chinese, French, German, etc.</p>
| 48,574
|
<p>I am updating a VBA program (excel). At startup the program checks if it can find a directory which is on the office file server using:</p>
<pre><code>FileSystemObject.FolderExists("\\servername\path")
</code></pre>
<p>If this is not found the program switches to offline mode and saves its output to the local hard disk (for later transfer), instead of directly to the fileserver. </p>
<p>This works OK, It's very quick if the computer can reach the path, however it can sometimes take a while (up to one minute) for the call to FolderExists to complete/time-out, especially if there is a network connection open but the required path does not exist (i.e. we are connected to some other LAN).</p>
<p>My Question(s):</p>
<ol>
<li><p>is there a quicker/better way to check for the existence of a network path using VBA?</p></li>
<li><p>is there a way to have the user cancel the search done by FolderExists() when (s)he knows it cannot succeed because they're not in the office. I.e. is there some way to prematurely exit FolderExists() (or any other function call for that matter)</p></li>
</ol>
<p>I want the solution to have as little user input as possible, which is why the check is done automatically, rather than just asking the user if (s)he's in the office or not in the first place.</p>
|
<p><strong>If you're on a domain:</strong></p>
<p>Check the LOGONSERVER environmental variable.</p>
<p>If there are two '\' symbols before the server name, it's connected to active directory and so you should do your check.</p>
<p>Otherwise, it isn't logged into the office network, so you can bypass the check.</p>
<p><strong>If you aren't on a domain:</strong></p>
<p>Probably your best bet is to run a ping against the target server.</p>
<p>If it can't get a ping response, it either isn't connected to the network, isn't connected to YOUR network, or the server is down. You don't want your code to run either way, in those cases.</p>
<p><a href="http://vbnet.mvps.org/index.html?code/internet/ping.htm" rel="nofollow noreferrer">MVPS.ORG</a> and <a href="http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/9a509391-f4e2-4ea7-827a-3370aa203bfb/" rel="nofollow noreferrer">MSDN Forums</a> both have some code samples for that,</p>
|
<p>I use the <code>Dir</code> Command, targeting a shared folder on the server and trapping the error when not found.</p>
<pre><code>Dir("\\Servername\aFolder\", vbDirectory)
</code></pre>
| 31,125
|
<p>In my current 32-bit application, I check (very occasionally) for overflow by doing operations on 64-bit integers.</p>
<p>However, on 64-bit systems there does not seem to be a standard 128-bit integer. Is there a simple way of checking for overflow, or a way of getting 128-bit integers, which works on all OSes and compilers?</p>
<p>I tried using GMP as a more generic solution, but it is a little heavyweight for my requirements.</p>
<p>Efficiency is not too important, no processor specific-ASM is.</p>
|
<p>Much of the discussion in this question applies:</p>
<p><a href="https://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-cc">How to detect integer overflow?</a></p>
<p>Many of the techniques used for 32-bit overflow chacking apply to 64-bits as well (not all of the techniques discussed use the next larger integer type to handle the overflow).</p>
|
<p>One solution would be to create a class around the 64-bit int which overrode the arithmetic operators to check before performing the operation.</p>
<p>I can't remember the operatorX syntax off the top of my head (I switched from C++ to Java a long time ago) but a sample would be:</p>
<pre><code>int64 myint64::add (int64 a, int64 b) {
if (MAX_INT64 - a > b) {
// error condition here.
}
return a + b;
}
int64 myint64::mul (int64 a, int64 b) {
if (MAX_INT64 / a > b) {
// error condition here.
}
return a * b;
}
</code></pre>
<p>Similar for any other arithmetic operation, although this could get very complicated for non-basic functions such as powers, factorials and such.</p>
<p>However, if you build those from the basic arithmetic building blocks, they'll work.</p>
| 25,049
|
<p>I have a 'generic' boiler plate static method for checking for InvokeRequired and invoking an associated action accordingly.</p>
<p>If an unhandled exception is raised by the action, the stack trace isn't much help because it starts from here. I can get information about the control, but that isn't always much help. I was wondering if it is possible to get 'something' useful out of the Action - other that 'Target'. (Note that the Action is often a lambda or anonymous delegate...)</p>
<pre><code> public static void Invoke(Control ctrl, Action action)
{
if (ctrl == null)
throw new ArgumentNullException("ctrl");
if (action == null)
return;
var invokeRequired = ctrl.InvokeRequired;
try
{
if (ctrl.InvokeRequired)
ctrl.Invoke(action);
else
action();
}
catch (Exception ex)
{
throw new Exception(String.Format("Invoke error, ctrl={0}, action Target={1}", ctrl.Name, action.Target), ex);
}
}
</code></pre>
<p>EDIT: In line with this answer, here is the new overload (also slightly improved)</p>
<pre><code>public static void Invoke(Control ctrl, Action action, string context)
{
if (ctrl == null)
throw new ArgumentNullException("ctrl");
if (action == null)
return; //not sure it's worththrowing an exception here...
var invokeRequired = ctrl.InvokeRequired;
try
{
if (invokeRequired)
ctrl.Invoke(action);
else
action();
}
catch (Exception ex)
{
var ps = invokeRequired ? "" : " - has the target control been initialised?";
var errmsg = String.Format("Invoke error, ctrl={0}, action Target={1}, context={2}{3}", ctrl.Name, action.Target, context, ps);
throw new Exception(errmsg, ex);
}
}
</code></pre>
|
<p>You should use WideCharToMultiByte. As an estimate for the output buffer size, you can use the Length field - but do consider the case of true multi-byte strings, in which case it will fail with ERROR_INSUFFICIENT_BUFFER, and you need to start over with a larger buffer. Or, you call it with an output buffer size of 0 first always, so it tells you the necessary size of the buffer.</p>
|
<pre><code>WCHAR* UnicodeStringToNulTerminated(UNICODE_STRING* str)
{
WCHAR* result;
if(str == NULL)
return NULL;
result = (WCHAR*)malloc(str->Length + 2);
if(result == NULL)
// raise?
return NULL;
memcpy(result, str->Buffer, str->Length);
result[str->Length] = L'\0';
return result;
}
</code></pre>
| 32,261
|
<p>In some my project I notice that during executing unit tests under VSTS2008 its VSTestHost's memory consuming grows. As I have very many tests in my solution it leads to OutOfMemroyException eventually.
That looks very strange for me as I was sure that MSTest creates a new AppDomain for each unit test. Otherwise how would it reset static fields?
But if AppDomain is being created for each test than memory shouldn't leak. But it does.</p>
<p>So the question is: Should VS create AppDomain for each test class or not? If yes than how can I check that it does it.
I tried tracing through ProcessExpolorer and Performance snap-in. A value of "Total appdomain unloaded" is always 0 during test run.</p>
|
<p>I don't think the unit test engine creates a new AppDomain for each test. Since creating an AppDomain is a relatively expensive operation, doing so for each test would slow down execution of unit tests considerably!</p>
<p>Visual Studio 2008 uses a seperate executable called vstesthost.exe to run unit tests. VS communicates with vstesthost.exe (how it does this I don't know) to tell it what tests to run. vstesthost.exe returns the execution results to VS which displays those results.</p>
<p>If you are getting OutOfMemoryExceptions when running your unit tests I would say that's a strong indicator that your code under test is actually not cleaning things up. Are you sure that you aren't retaining handles to unmanaged objects/memory? I would recommend running your unit tests under a Performance Analysis (you can do that by finding the unit test under the "Test View", right-clicking on it, and selecting "Create Performance Session"). This might shed some light at least on your object allocations.</p>
|
<p>This does not seem to be solved in MSTest 2010. I am experiencing a lot of similar issues like this. Why does garbage collection not work in unit test?</p>
<p>My understanding was that the UT framework took care of disposing of all executed tests, but this does not seem to be the case with some singleton patterns that we have in code.</p>
| 31,990
|
<p>What’s the best way to capitalize the first letter of each word in a string in SQL Server.</p>
|
<p>From <a href="http://www.sql-server-helper.com/functions/initcap.aspx" rel="noreferrer">http://www.sql-server-helper.com/functions/initcap.aspx</a></p>
<pre><code>CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE @Index INT
DECLARE @Char CHAR(1)
DECLARE @PrevChar CHAR(1)
DECLARE @OutputString VARCHAR(255)
SET @OutputString = LOWER(@InputString)
SET @Index = 1
WHILE @Index <= LEN(@InputString)
BEGIN
SET @Char = SUBSTRING(@InputString, @Index, 1)
SET @PrevChar = CASE WHEN @Index = 1 THEN ' '
ELSE SUBSTRING(@InputString, @Index - 1, 1)
END
IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
BEGIN
IF @PrevChar != '''' OR UPPER(@Char) != 'S'
SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))
END
SET @Index = @Index + 1
END
RETURN @OutputString
END
GO
</code></pre>
<p>There is a simpler/smaller one here (but doesn't work if any row doesn't have spaces, "Invalid length parameter passed to the RIGHT function."): </p>
<p><a href="http://www.devx.com/tips/Tip/17608" rel="noreferrer">http://www.devx.com/tips/Tip/17608</a></p>
|
<pre><code>IF OBJECT_ID ('dbo.fnCapitalizeFirstLetterAndChangeDelimiter') IS NOT NULL
DROP FUNCTION dbo.fnCapitalizeFirstLetterAndChangeDelimiter
GO
CREATE FUNCTION [dbo].[fnCapitalizeFirstLetterAndChangeDelimiter] (@string NVARCHAR(MAX), @delimiter NCHAR(1), @new_delimeter NCHAR(1))
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @result NVARCHAR(MAX)
SELECT @result = '';
IF (LEN(@string) > 0)
DECLARE @curr INT
DECLARE @next INT
BEGIN
SELECT @curr = 1
SELECT @next = CHARINDEX(@delimiter, @string)
WHILE (LEN(@string) > 0)
BEGIN
SELECT @result =
@result +
CASE WHEN LEN(@result) > 0 THEN @new_delimeter ELSE '' END +
UPPER(SUBSTRING(@string, @curr, 1)) +
CASE
WHEN @next <> 0
THEN LOWER(SUBSTRING(@string, @curr+1, @next-2))
ELSE LOWER(SUBSTRING(@string, @curr+1, LEN(@string)-@curr))
END
IF (@next > 0)
BEGIN
SELECT @string = SUBSTRING(@string, @next+1, LEN(@string)-@next)
SELECT @next = CHARINDEX(@delimiter, @string)
END
ELSE
SELECT @string = ''
END
END
RETURN @result
END
GO
</code></pre>
| 7,875
|
<p>I'm trying to use the StringEscapeUtils.escapeXML() function from org.apache.commons.lang...</p>
<p>There are two versions of that function, one which expects (Writer, String) and one which just expects (String)....</p>
<p><a href="http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)" rel="nofollow noreferrer">http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)</a></p>
<p>I'm trying to use the version that just expects the String parameter without the Writer, but Java is complaining that I've not given it a Writer.</p>
<p>How do I use this in my program so that I don't need a Writer?</p>
<pre><code>String escXml = StringEscapeUtils.escapeXml(attr.get());
xml = xml.concat("<"+attr.getID()+">"+escXml+"</"+attr.getID()+">");
</code></pre>
<p>I've also tried just doing it inline in the string itself.</p>
<pre><code>xml = xml.concat("<"+attr.getID()+">"+StringEscapeUtils.escapeXml(attr.get())+"</"+attr.getID()+">");
</code></pre>
<p>Both of these attempts have given me the error about it expecting the Writer though. Can anyone help me with this?</p>
<p>Thanks,
Matt</p>
|
<p>The error message is telling you that you are passing an Object into the method, not a String.</p>
<p>If you are sure that the Object is a String, then you'll need to cast it to a String first.</p>
<p>If this doesn't work, please post the actual code that is giving you trouble.</p>
|
<p>What exactly is the compiler error message?</p>
<p>is it possible that you're using a different version of the commons library that does not have the 1-parameter method?</p>
| 48,568
|
<p>I've been given some code with commenting unlike anything I've come across before:</p>
<pre><code>//{{{ Imports
import imports;
//}}}
</code></pre>
<p>It is the same for each method block, </p>
<pre><code>//{{{ above the code block
//}}} below the code block
</code></pre>
<p>Also see: <a href="http://en.wikipedia.org/wiki/Folding_editor" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Folding_editor</a></p>
|
<p>A quick search for <em>"triple curly" comment</em> suggests it's "<a href="http://www.emacswiki.org/cgi-bin/wiki/FoldingMode" rel="noreferrer">Emacs folding mode</a>".</p>
<p>Or some other code folding marker in any case.</p>
|
<p>Maybe it's to emphasize a code block?</p>
<p><em>shrugs</em></p>
| 23,885
|
<p>I'm looking for a consistent way to structure my use of formatting strings throughout a large web application, and I'm looking for recommendations or best practices on which way to go.</p>
<p>Up until now I've had a static class that does some common formatting e.g.</p>
<p>Formatting.FormatCurrency</p>
<p>Formatting.FormatBookingReference</p>
<p>I'm not convinced that this is the way to go though, I'd prefer to use the standard way of formatting strings within .NET directly and use:</p>
<p>amount.ToString("c")</p>
<p>reference.ToString("000000")</p>
<p>Id use IFormattable and ICustomFormatter for some of our more complicated data structures, but I'm struggling what to do about the more simple existing objects that we need to format (in this case Int32 but also DateTime). </p>
<p>Do I simply define constants for "c" and "000000" and use them consistently around the whole web app or is there a more standard way to do it?</p>
|
<p>One option is to use a helper class with extension methods like</p>
<pre><code>public static class MyWebAppExtensions
{
public static string FormatCurrency(this decimal d)
{
return d.ToString("c");
}
}
</code></pre>
<p>Then anywhere you have a decimal value you do</p>
<pre><code>Decimal d = 100.25;
string s = d.FormatCurrency();
</code></pre>
|
<p>This answer can be combined with GeekyMonkey's answer.</p>
<p>First of all, in ASP.NET you have the possibility to set the culture and UI culture in web.config using the <a href="http://msdn.microsoft.com/en-us/library/hy4kkhe0.aspx" rel="nofollow noreferrer"><code>globalization</code></a> element. The <code>resourceProviderFactoryType</code> attribute is your friend when you have special formatting needs.</p>
<p>Another possibility is to create a subclass of the ASP.NET Page class and override the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.initializeculture.aspx" rel="nofollow noreferrer"><code>InitializeCulture</code></a> method. Here you can change the culture and UI culture which is stored in the current thread handling the HTTP request.</p>
<p>A quick example:</p>
<pre><code>protected override void InitializeCulture()
{
Thread.CurrentThread.CurrentCulture = ...;
Thread.CurrentThread.CurrentUICulture = ...;
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
...
}
</code></pre>
<p>For those worried about ASP.NET doing "random" thread switching:</p>
<blockquote>
<p>ASP.NET ensures that, even if they switch your thread, the CurrentPrincipal and culture properties from the original thread carry forward to the new thread. This is automatic, and you don’t need to worry about losing those values. Whew!</p>
<p>Source: <a href="http://www.lhotka.net/WeBlog/PermaLink,guid,019e3c37-38ed-492e-b769-16e1a57fed0a.aspx" rel="nofollow noreferrer">ASP.NET thread switching</a></p>
</blockquote>
| 37,583
|
<p>Are C-style macro names subject to the same naming rules as identifiers? After a compiler upgrade, it is now emitting this warning for a legacy application:</p>
<pre><code>warning #3649-D: white space is required between the macro name "CHAR_" and its replacement text
#define CHAR_& 38
</code></pre>
<p>This line of code is defining an ASCII value constant for an ampersand.</p>
<pre><code>#define DOL_SN 36
#define PERCENT 37
#define CHAR_& 38
#define RT_SING 39
#define LF_PAR 40
</code></pre>
<p>I assume that this definition (not actually referenced by any code, as far as I can tell) is buggy and should be changed to something like "CHAR_AMPERSAND"?</p>
|
<p>Macro names should only consist of alphanumeric characters and underscores, i.e. <code>'a-z'</code>, <code>'A-Z'</code>, <code>'0-9'</code>, and <code>'_'</code>, and the first character should not be a digit. Some preprocessors also permit the dollar sign character <code>'$'</code>, but you shouldn't use it; unfortunately I can't quote the C standard since I don't have a copy of it.</p>
<p>From the <a href="http://gcc.gnu.org/onlinedocs/cpp/Tokenization.html#Tokenization" rel="noreferrer">GCC documentation</a>:</p>
<blockquote>
<p>Preprocessing tokens fall into five
broad classes: identifiers,
preprocessing numbers, string
literals, punctuators, and other. An
<em>identifier</em> is the same as an
identifier in C: any sequence of
letters, digits, or underscores, which
begins with a letter or underscore.
Keywords of C have no significance to
the preprocessor; they are ordinary
identifiers. You can define a macro
whose name is a keyword, for instance.
The only identifier which can be
considered a preprocessing keyword is
<code>defined</code>. See Defined.</p>
<p>This is mostly true of other languages
which use the C preprocessor. However,
a few of the keywords of C++ are
significant even in the preprocessor.
See C++ Named Operators.</p>
<p>In the 1999 C standard, identifiers
may contain letters which are not part
of the “basic source character set”,
at the implementation's discretion
(such as accented Latin letters, Greek
letters, or Chinese ideograms). This
may be done with an extended character
set, or the <code>'\u'</code> and <code>'\U'</code> escape
sequences. The implementation of this
feature in GCC is experimental; such
characters are only accepted in the
<code>'\u'</code> and <code>'\U'</code> forms and only if
<code>-fextended-identifiers</code> is used.</p>
<p>As an extension, GCC treats <code>'$'</code> as a
letter. This is for compatibility with
some systems, such as VMS, where <code>'$'</code>
is commonly used in system-defined
function and object names. <code>'$'</code> is not
a letter in strictly conforming mode,
or if you specify the <code>-$</code> option. See
Invocation.</p>
</blockquote>
|
<p>The same rules that specify valid identifiers for variable names apply to macro names with the exception that macros may have the same names as keywords. Valid characters in identifier names include <code>digits</code> and <code>non-digits</code> and must not start with a digit. <code>non-digits</code> include the uppercase letters A-Z, the lowercase letters a-z, the underscore, and any implementation defined characters.</p>
| 48,258
|
<p>How would I print a spinning curser in a utility that runs in a terminal using standard C?</p>
<p>I'm looking for something that prints: \ | / - over and over in the same position on the screen?</p>
<p>Thanks </p>
|
<p>You could use the backspace character (<code>\b</code>) like this:</p>
<pre><code>printf("processing... |");
fflush(stdout);
// do something
printf("\b/");
fflush(stdout);
// do some more
printf("\b-");
fflush(stdout);
</code></pre>
<p>etc. You need the <code>fflush(stdout)</code> because normally stdout is buffered until you output a newline.</p>
|
<p>There is no truly "standard" way to do this, since the C Standard Library (<a href="http://members.aol.com/wantondeb/" rel="nofollow noreferrer">http://members.aol.com/wantondeb/</a>) does not provide functions to do raw terminal/console output.</p>
<p>In DOS/Windows console, the standard-ish way to do it is with <a href="http://en.wikipedia.org/wiki/Conio.h" rel="nofollow noreferrer"><code>conio.h</code></a>, while under Unix/Linux the accepted library for this purpose is <a href="http://en.wikipedia.org/wiki/Ncurses" rel="nofollow noreferrer"><code>ncurses</code></a> (<code>ncurses</code> basically encapsulates the control-character behavior that MBCook describes, in a terminal-independent way).</p>
| 24,297
|
<p>We have a situation where users are allowed to upload content, and then separately make some changes, then submit a form based on those changes.</p>
<p>This works fine in a single-server, non-failover environment, however we would like some sort of solution for sharing the files between servers that supports failover.</p>
<p>Has anyone run into this in the past? And what kind of solutions were you able to develop? Obviously persisting to the database is one option, but we'd prefer to avoid that.</p>
|
<p>At a former job we had a cluster of web servers with an F5 load balancer in front of them. We had a very similar problem in that our applications allowed users to upload content which might include photo's and such. These were legacy applications and we did not want to edit them to use a database and a SAN solution was too expensive for our situation.</p>
<p>We ended up using a file replication service on the two clustered servers. This ran as a service on both machines using an account that had network access to paths on the opposite server. When a file was uploaded, this backend service sync'd the data in the file system folders making it available to be served from either web server.</p>
<p>Two of the products we reviewed were <a href="http://www.tgrmn.com/" rel="nofollow noreferrer">ViceVersa</a> and <a href="http://www.peersoftware.com/products/peersync/peersync.aspx" rel="nofollow noreferrer">PeerSync</a>. I think we ended up using PeerSync.</p>
<hr>
|
<p>The best solution for this is usually to provide the shared area on some form of SAN, which will be accessible from all servers and contain failover.</p>
<p>This also has the benefit that you don't have to provide sticky load balancing, the upload can be handled by one server, and the edit by another.</p>
| 4,263
|
<p>How do you open a path in explorer by code in c++. I googled and couldn't find any thing but systems commands to do this, however, i dont want it to block or show the console window.</p>
|
<p>You probably are looking for the <a href="http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx" rel="nofollow noreferrer"><code>ShellExecute()</code></a> function in <code>shellapi.h</code>. It is called with an "action verb", a path, and optional parameters. In your case this will want either "open" or "explore" as follows:</p>
<pre><code>ShellExecuteA(NULL, "open", "C:\\", NULL, NULL, SW_SHOWDEFAULT);
</code></pre>
<p>This will open an unattached explorer window at C:. ShellExecute() will give basically the same action as typing in a command at the Run dialog. It will also handle URLs, so the following will open up the user's default browser:</p>
<pre><code>ShellExecuteA(NULL, "open", "http://www.google.com", NULL, NULL, SW_SHOWDEFAULT);
</code></pre>
<p>Although make sure to pay attention to the note in the documentation that ShellExecute relies on COM (Although your code doesn't have to worry about any COM objects itself).</p>
<pre><code>CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)
</code></pre>
|
<p>I'm now using VS2017, using as follows works:</p>
<pre><code>ShellExecute(NULL, L"open", L"YourFolderPath\\YourFile.xxx", NULL, NULL, SW_RESTORE);
</code></pre>
<p>also reference <a href="https://stackoverflow.com/questions/46558259/shellexecute-to-open-an-exe-in-c">ShellExecute to open an .exe in C++</a></p>
| 46,247
|
<p>I have two tables: <code>foos</code> and <code>bars</code>, and there is a many-to-one relationship between them: each <code>foo</code> can have many <code>bars</code>. I also have a view <code>foobars</code>, which joins these two tables (its query is like <code>select foo.*, bar.id from foos, bars where bar.foo_id=foo.id</code>).</p>
<p>EDIT: You would not be wrong if you said that there's a many-to-many relationship between <code>foo</code>s and <code>bar</code>s. A <code>bar</code>, however, is just a tag (in fact, it is a size), and consists just of its name. The table <code>bars</code> has the same role as a link table would have.</p>
<p>I have a rule on inserting to <code>foobars</code> such that the “foo” part is inserted to <code>foos</code> as a new row, and “bar” part, which consists of a couple of bar-id's separated by commas is split, and for each such part a link between it and the appropriate <code>foo</code> is created (I use a procedure to do that).</p>
<p>This works great for inserts. I have a problem, however, when it comes to updating the whole thing. The <code>foo</code> part of the rule is easy. However, I don't know how to deal with the multiple <code>bar</code>s part. When I try to do something like <code>DELETE FROM bars WHERE foo_id=new.foo_id</code> in the rule, I end deleting everything from the table <code>bars</code>.</p>
<p>What am I doing wrong? Is there a way of achieving what I need? Finally, is my approach to the whole thing sensible?</p>
<p>(I do this overcomplicated thing with the view because the data I get is in the form of “<code>foo</code> and all its <code>bar</code>s”, but the user must see just <code>foobars</code>.)</p>
|
<p>Rysiek, if I understood correctly, you have text column in <code>foos</code> table that is parsed to extract foreign keys pointing to <code>bars</code> table. This approach to building relations may be justified in some cases, however almost every guide/tutorial to database programming would discourage doing so. Why not use standard foreign key in <code>bars</code> that would point to foo in <code>foos</code>? Unless there is a requirement for bars to be assigned to more than one foo. If so, this identifies your relation as many-to-many rather one-to-many. In either situation using standard foreign key based solution seems much more natural for database.</p>
<p>Example db schema for one-to-many relation:</p>
<pre><code>CREATE TABLE foos (
id SERIAL PRIMARY KEY,
....
);
CREATE TABLE bars (
id SERIAL PRIMARY KEY,
foo_id INT REFERENCES bars (id) ON DELETE CASCADE,
...
);
</code></pre>
<p>And the same for many-to-many relation:</p>
<pre><code>CREATE TABLE foos (
id SERIAL PRIMARY KEY,
....
);
CREATE TABLE bars (
id SERIAL PRIMARY KEY,
...
);
CREATE TABLE foostobars (
foo_id INT REFERENCES foos (id) ON DELETE CASCADE,
bar_id INT REFERENCES bars (id) ON DELETE CASCADE
);
</code></pre>
<p>I would also recommend using INNER JOIN instead of table multiplication (SELECT FROM foos, bars).</p>
<pre><code>CREATE VIEW foobars AS
SELECT
foos.id AS foo_id, foos.something,
bars.id AS bar_id, bars.somethingelse
FROM foos
INNER JOIN bars ON bars.foo_id = foo.id;
</code></pre>
<p>The same for many-to-many INNER JOINS</p>
<pre><code>CREATE VIEW foobars AS
SELECT
foos.id AS foo_id, foos.something,
bars.id AS bar_id, bars.somethingelse
FROM foos
INNER JOIN foostobars AS ftb ON ftb.foo_id = foo.id
INNER JOIN bars ON bars.id = ftb.bar_id;
</code></pre>
|
<p>I don't think new.foo_id is correct in the context of a delete.</p>
<p>Shouldn't it be DELETE FROM bars WHERE foo_id=old.foo_id?</p>
| 19,398
|
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p>
<pre><code>500 Internal Server Error
</code></pre>
<p>When I check my error logs I see the message </p>
<pre><code>Premature end of script headers
</code></pre>
<p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine.
"
So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p>
<p>Thanks!</p>
<hr>
<p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p>
<pre><code>#!/usr/local/bin/python
print "Content-type: text/html\n"
print "\n\n"
print "<HTML>"
print "<HEAD>"
print "<TITLE>Test</TITLE>"
print "</HEAD>"
print "<BODY>"
print "<H2>Hi there.</h2>"
print "</BODY>"
print "</HTML>"
</code></pre>
<p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p>
<hr>
<p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p>
<p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
|
<p>This is the exact behavior you would get if your Python script does not have the executable permission set.</p>
<p>Try:</p>
<pre><code>chmod a+x foo.py
</code></pre>
<p>(where foo.py is your script name).</p>
<p>See the <a href="http://httpd.apache.org/docs/1.3/howto/cgi.html#filepermissions" rel="noreferrer">Apache tutorial</a> for more information.</p>
|
<p>This ended up being a <code>dos2unix</code> issue for me. Ran <code>dos2unix test.py test.py</code> and it worked. The <code>\r\n</code> combinations were the problem. Had to <code>yum install dos2unix</code> to get it installed.</p>
| 49,623
|
<p>This is my very first question so I am a bit nervous about it because I am not sure whether I get the meaning across well enough. Anyhow, here we go....</p>
<p>Whenever new milestones in programming have been reached it seems they always have had one goal in common: to make it easier for programmers, well, to program.</p>
<p>Machine language, opcodes/mnemonics, procedures/functions, structs, classes (OOP) etc. always helped, in their time, to plan, structure and code programs in a more natural, understandable and better maintainable way.</p>
<p>Of course functional programming is by no means a novelty but it seems that it has experienced a sort of renaissance in recent years. I also believe that FP will get an enormous boost when Microsoft will add F# to their mainstream programming languages.</p>
<p>Returning to my original question, I believe that ultimately programming will be done in a natural language (English) with very few restrictions or rules. The compiler will be part of an AI/NLP system that extracts information from the code or should I say text and transforms it into an intermediate language which the compiler can compile.</p>
<p>So, does FP take programming closer to natural-language programming or is it rather an obstacle and mainstream OOP will lead us faster to natural-language programming?</p>
<p>This question should not be used to discuss the useability or feasability of natural-language programming because only the future will tell. </p>
|
<p>Sorry, I don't agree at all. Code is ultimately a blueprint for making things (objects), so it <em>has</em> to be very precise and rule-governed in order to function reliably. Natural language won't take over programming any sooner than sketching ideas on napkins will take over mechanical engineering.</p>
|
<p>The current spurt of interest in Functional Programming result primarily of C# 3.0's cool new features is basically to enable parallelism and denotes a shift towards multi-core computing. IMHO, I don't think we can consider this a next step towards 'natural language programming'</p>
| 36,310
|
<p>I have a deceptively simple scenario, and I want a simple solution, but it's not obvious which is "most correct" or "most Java".</p>
<p>Let's say I have a small authenticate(Client client) method in some class. The authentication could fail for a number of reasons, and I want to return a simple boolean for control flow, but also return a String message for the user. These are the possibilities I can think of:</p>
<ul>
<li>Return a boolean, and pass in a StringBuilder to collect the message. This is the closest to a C-style way of doing it.</li>
<li>Throw an exception instead of returning false, and include the message. I don't like this since failure is not exceptional.</li>
<li>Create a new class called AuthenticationStatus with the boolean and the String. This seems like overkill for one small method.</li>
<li>Store the message in a member variable. This would introduce a potential race condition, and I don't like that it implies some state that isn't really there.</li>
</ul>
<p>Any other suggestions?</p>
<p><strong>Edit</strong> Missed this option off</p>
<ul>
<li>Return null for success - Is this unsafe?</li>
</ul>
<p><strong>Edit</strong> Solution:</p>
<p>I went for the most OO solution and created a small AuthenticationResult class. I wouldn't do this in any other language, but I like it in Java. I also liked the suggestion
of returning an String[] since it's like the null return but safer. One advantage of the Result class is that you can have a success message with further details if required.</p>
|
<p>Returning a small object with both the boolean flag and the String inside is probably the most OO-like way of doing it, although I agree that it seems overkill for a simple case like this.</p>
<p>Another alternative is to always return a String, and have null (or an empty String - you choose which) indicate success. As long as the return values are clearly explained in the javadocs there shouldn't be any confusion.</p>
|
<p>How about returning a string. Empty or Null for success. Error Message in case of failure.
Simplest that would work. However not sure if it reads well.</p>
| 46,447
|
<p>Continuing my problem from yesterday, the Silverlight datagrid I have from this <a href="https://stackoverflow.com/questions/74461/silverlight-datagrid-control-selection-changed-event-interfering-with-sorting">issue</a>
is now causing Stack Overflow errors when sorting a column with a large amount of data (Like the text column that contains a where clause for a SQL statment). When you sort, it'll fire the SelectedIndexChanged event for the datagrid and then still try to stort. If you click the header again the stack overflow occours. </p>
<p>Does anyone have an idea on how to stop the sorting on this control for a column? All the other columns sort fine (but still fire that darn SelectedIndexChanged event), but if I could shut off the column for whereClause it'd be perfect.</p>
<p>Does anyone have a better idea at how to get this to work?</p>
|
<p>I'm only familiar with the WPF version of this datagrid, but try this:</p>
<pre><code><data:DataGridTextColumn CanUserSort="False" Header="First Name" Binding="{Binding FirstName}" />
</code></pre>
<p>Add the CanUserSort="False" attribute on each column you don't want sorted.</p>
|
<p>Give this a shot:</p>
<pre><code>dataGridView1.Columns[*Numberofthecolumnyoudontwantsorted*].SortMode
= DataGridViewColumnSortMode.NotSortable;
</code></pre>
| 11,315
|
<p>I'm programming an online game for two reasons, one to familiarize myself with server/client requests in a realtime environment (as opposed to something like a typical web browser, which is not realtime) and to actually get my hands wet in that area, so I can proceed to actually properly design one.</p>
<p>Anywho, I'm doing this in C++, and I've been using winsock to handle my basic, basic network tests. I obviously want to use a framelimiter and have 3D going and all of that at some point, and my main issue is that when I do a send() or receive(), the program kindly idles there and waits for a response. That would lead to maybe 8 fps on even the best internet connection.</p>
<p>So the obvious solution to me is to take the networking code out of the main process and start it up in its own thread. Ideally, I would call a "send" in my main process which would pass the networking thread a pointer to the message, and then periodically (every frame) check to see if the networking thread had received the reply, or timed out, or what have you. In a perfect world, I would actually have 2 or more networking threads running simultaneously, so that I could say run a chat window and do a background download of a piece of armor and still allow the player to run around all at once.</p>
<p>The bulk of my problem is that this is a new thing to me. I understand the <em>concept</em> of threading, but I can see some serious issues, like what happens if two threads try to read/write the same memory address at the same time, etc. I know that there are already methods in place to handle this sort of thing, so I'm looking for suggestions on the best way to implement something like this. Basically, I need thread A to be able to start a process in thread B by sending a chunk of data, poll thread B's status, and then receive the reply, also as a chunk of data., ideally without any major crashing going on. ^_^ I'll worry about what that data actually contains and how to handle dropped packets, etc later, I just need to get that happening first.</p>
<p>Thanks for any help/advice.</p>
<p>PS: Just thought about this, may make the question simpler. Is there a way to use the windows event handling system to my advantage? Like, would it be possible to have thread A initialize data somewhere, then trigger an event in thread B to have it pick up the data, and vice versa for thread B to tell thread A it was done? That would probably solve a lot of my problems, since I don't really need both threads to be able to work on the data at the same time, more of a baton pass really. I just don't know if this is possible between two different threads. (I know one thread can create its own messages for the event handler.)</p>
|
<p><strong>The easiest thing</strong> </p>
<p>for you to do, would be to simply invoke the windows API <strong>QueueUserWorkItem</strong>. All you have to specify is the function that the thread will execute and the input passed to it. A thread pool will be automatically created for you and the jobs executed in it. New threads will be created as and when is required.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms684957(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms684957(VS.85).aspx</a></p>
<p><strong>More Control</strong></p>
<p>You could have a more detailed control using another set of API's which can again manage the thread pool for you - </p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms686980(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms686980(VS.85).aspx</a></p>
<p><strong>Do it yourself</strong></p>
<p>If you want to control all aspects of your thread creation and the pool management you would have to create the threads yourself, decide how they should end , how many to create etc (beginthreadex is the api you should be using to create threads. If you use MFC you should use AfxBeginThread function).</p>
<p><strong>Send jobs to worker threads - Io completion Ports</strong></p>
<p>In this case, you would also have to worry about how to communicate your jobs - i would recommend IoCOmpletionPorts to do that. It is the most scalable notification mechanism that i currently know of made for this purpose. It has the additional advantage that it is implemented in the kernel so you avoid all kinds of dead loack sitautions you would encounter if you decide to handroll something yourself. </p>
<p>This article will show you how with code samples - </p>
<p><a href="http://blogs.msdn.com/larryosterman/archive/2004/03/29/101329.aspx" rel="noreferrer">http://blogs.msdn.com/larryosterman/archive/2004/03/29/101329.aspx</a></p>
<p><strong>Communicate Back - Windows Messages</strong></p>
<p>You could use windows messages to communicate the status back to your parent thread since it is doing the message wait anyway. use the PostMessage function to do this. (and check for errors)</p>
<p>ps : You could also allocate the data that needs to be sent out on a dedicated pointer and then the worker thread could take care of deleting it after sending it out. That way you avoid the return pointer traffic too. </p>
|
<p>See it as a <a href="http://en.wikipedia.org/wiki/Producer-consumer_problem" rel="nofollow noreferrer">producer-consumer problem</a>: when receiving, your network communication thread is the producer whereas the UI thread is the consumer. When sending, it's just the opposite. Implement a simple buffer class which gives you methods like push and pop (pop should be blocking for the network thread and non-blocking for the UI thread).</p>
<p>Rather than using the Windows event system, I would prefer something that is more portable, for example <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref" rel="nofollow noreferrer">Boost condition variables</a>.</p>
| 17,254
|
<p>I wonder if is possible to use FTS with LINQ using .NET Framework 3.5. I'm searching around the documentation that I didn't find anything useful yet.</p>
<p>Does anyone have any experience on this?</p>
|
<p>Yes. However you have to create SQL server function first and call that as by default LINQ will use a like.</p>
<p>This <a href="http://sqlblogcasts.com/blogs/simons/archive/2008/12/18/LINQ-to-SQL---Enabling-Fulltext-searching.aspx" rel="noreferrer">blog post</a> which will explain the detail but this is the extract:</p>
<blockquote>
<p>To get it working you need to create a table valued function that does
nothing more than a CONTAINSTABLE query based on the keywords you pass
in,</p>
<pre><code>create function udf_sessionSearch
(@keywords nvarchar(4000))
returns table
as
return (select [SessionId],[rank]
from containstable(Session,(description,title),@keywords))
</code></pre>
<p>You then add this function to your LINQ 2 SQL model and he presto you
can now write queries like.</p>
<pre><code> var sessList = from s in DB.Sessions
join fts in DB.udf_sessionSearch(SearchText)
on s.sessionId equals fts.SessionId
select s;
</code></pre>
</blockquote>
|
<p>I made a working prototype, for SQL Server's <em>CONTAINS</em> only and no wildcard columns. What it achieves is for you to use <em>CONTAINS</em> like ordinary LINQ functions:</p>
<pre><code>var query = context.CreateObjectSet<MyFile>()
.Where(file => file.FileName.Contains("pdf")
&& FullTextFunctions.ContainsBinary(file.FileTable_Ref.file_stream, "Hello"));
</code></pre>
<h3>You will need:</h3>
<p>1.Function definitions in code and EDMX to support the <em>CONTAINS</em> keyword.</p>
<p>2.Rewrite EF SQL by EFProviderWrapperToolkit/EFTracingProvider, because CONTAINS is not a function and by default the generated SQL treats its result as <em>bit</em>.</p>
<h3>BUT:</h3>
<p>1.Contains is not really a function and you cannot select boolean results from it. It can only be used in conditions.</p>
<p>2.The SQL rewriting code below is likely to break if queries contain non-parameterized strings with special characters.</p>
<h2>Source of my prototype</h2>
<h3>Function Definitions: (EDMX)</h3>
<p>Under edmx:StorageModels/Schema</p>
<pre><code><Function Name="conTAINs" BuiltIn="true" IsComposable="true" ParameterTypeSemantics="AllowImplicitConversion" ReturnType="bit" Schema="dbo">
<Parameter Name="dataColumn" Type="varbinary" Mode="In" />
<Parameter Name="keywords" Type="nvarchar" Mode="In" />
</Function>
<Function Name="conTAInS" BuiltIn="true" IsComposable="true" ParameterTypeSemantics="AllowImplicitConversion" ReturnType="bit" Schema="dbo">
<Parameter Name="textColumn" Type="nvarchar" Mode="In" />
<Parameter Name="keywords" Type="nvarchar" Mode="In" />
</Function>
</code></pre>
<p>PS: the weird cases of chars are used to enable the same function with different parameter types (varbinary and nvarchar)</p>
<h3>Function Definitions: (code)</h3>
<pre><code>using System.Data.Objects.DataClasses;
public static class FullTextFunctions
{
[EdmFunction("MyModel.Store", "conTAINs")]
public static bool ContainsBinary(byte[] dataColumn, string keywords)
{
throw new System.NotSupportedException("Direct calls are not supported.");
}
[EdmFunction("MyModel.Store", "conTAInS")]
public static bool ContainsString(string textColumn, string keywords)
{
throw new System.NotSupportedException("Direct calls are not supported.");
}
}
</code></pre>
<p>PS: <em>"MyModel.Store"</em> is as same as the value in edmx:StorageModels/Schema/@Namespace</p>
<h3>Rewrite EF SQL: (by EFProviderWrapperToolkit)</h3>
<pre><code>using EFProviderWrapperToolkit;
using EFTracingProvider;
public class TracedMyDataContext : MyDataContext
{
public TracedMyDataContext()
: base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(
"name=MyDataContext", "EFTracingProvider"))
{
var tracingConnection = (EFTracingConnection) ((EntityConnection) Connection).StoreConnection;
tracingConnection.CommandExecuting += TracedMyDataContext_CommandExecuting;
}
protected static void TracedMyDataContext_CommandExecuting(object sender, CommandExecutionEventArgs e)
{
e.Command.CommandText = FixFullTextContainsBinary(e.Command.CommandText);
e.Command.CommandText = FixFullTextContainsString(e.Command.CommandText);
}
private static string FixFullTextContainsBinary(string commandText, int startIndex = 0)
{
var patternBeg = "(conTAINs(";
var patternEnd = ")) = 1";
var exprBeg = commandText.IndexOf(patternBeg, startIndex, StringComparison.Ordinal);
if (exprBeg == -1)
return commandText;
var exprEnd = FindEnd(commandText, exprBeg + patternBeg.Length, ')');
if (commandText.Substring(exprEnd).StartsWith(patternEnd))
{
var newCommandText = commandText.Substring(0, exprEnd + 2) + commandText.Substring(exprEnd + patternEnd.Length);
return FixFullTextContainsBinary(newCommandText, exprEnd + 2);
}
return commandText;
}
private static string FixFullTextContainsString(string commandText, int startIndex = 0)
{
var patternBeg = "(conTAInS(";
var patternEnd = ")) = 1";
var exprBeg = commandText.IndexOf(patternBeg, startIndex, StringComparison.Ordinal);
if (exprBeg == -1)
return commandText;
var exprEnd = FindEnd(commandText, exprBeg + patternBeg.Length, ')');
if (exprEnd != -1 && commandText.Substring(exprEnd).StartsWith(patternEnd))
{
var newCommandText = commandText.Substring(0, exprEnd + 2) + commandText.Substring(exprEnd + patternEnd.Length);
return FixFullTextContainsString(newCommandText, exprEnd + 2);
}
return commandText;
}
private static int FindEnd(string commandText, int startIndex, char endChar)
{
// TODO: handle escape chars between parens/squares/quotes
var lvlParan = 0;
var lvlSquare = 0;
var lvlQuoteS = 0;
var lvlQuoteD = 0;
for (var i = startIndex; i < commandText.Length; i++)
{
var c = commandText[i];
if (c == endChar && lvlParan == 0 && lvlSquare == 0
&& (lvlQuoteS % 2) == 0 && (lvlQuoteD % 2) == 0)
return i;
switch (c)
{
case '(':
++lvlParan;
break;
case ')':
--lvlParan;
break;
case '[':
++lvlSquare;
break;
case ']':
--lvlSquare;
break;
case '\'':
++lvlQuoteS;
break;
case '"':
++lvlQuoteD;
break;
}
}
return -1;
}
}
</code></pre>
<h3>Enable EFProviderWrapperToolkit:</h3>
<p>If you get it by nuget, it should add these lines into your app.config or web.config:</p>
<pre><code><system.data>
<DbProviderFactories>
<add name="EFTracingProvider" invariant="EFTracingProvider" description="Tracing Provider Wrapper" type="EFTracingProvider.EFTracingProviderFactory, EFTracingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
<add name="EFProviderWrapper" invariant="EFProviderWrapper" description="Generic Provider Wrapper" type="EFProviderWrapperToolkit.EFProviderWrapperFactory, EFProviderWrapperToolkit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
</DbProviderFactories>
</system.data>
</code></pre>
| 27,734
|
<p>I want to create a stand-alone (i.e. not hosted in IIS) web service in ASP.NET. Is this possible, and if so what's the best way to do it?</p>
|
<p>So, you want to use ASP.NET to generate a web service, but you don't want to host ASP.NET using IIS. (For those reading this, the question was made clearer in an comment to Sir Psycho's response).</p>
<p>Then this article would be a good start:<br />
<a href="http://aspalliance.com/articleViewer.aspx?aId=220&pId=" rel="nofollow noreferrer">http://aspalliance.com/articleViewer.aspx?aId=220&pId=</a></p>
<p>It describes how you can use System.Web.Hosting namespace to process asp.net from the command line, and output the resulting HTML (or in your case XML).</p>
<p>Assuming you want data returned like a normal web request, you will to set up a socket to listen on port 80, interpret the HTTP requests, then use code similar to that in the article to output the results as a response to the web request.</p>
|
<p>I don't know if this answers the question exactly. If you want to create a webservice, is there a reasonable way to not require IIS but not have to handle data at a socket level.?</p>
| 31,468
|
<p>I have an msbuild project which builds a SLN file from visual studio which holds all the projects in (about 70+ project), and a lot of the projects are dependent on each other meaning they need to be build in order - sometimes a developer forgets to set the build order manually in visual studio in the solution file causing the msbuild on a clean solution to fail as something gets built out of order/cant find a dll.</p>
<p>Is there a way for msbuild to take all projects and work out the dependencies and build the projects in order, if there is how do i do this? using an MSBuild task? With current tries it seems to just build in the order it reads the projects in - if i pass in a list of project files+paths.</p>
<p>Currently the only way i can think to solve this is a external app which scans the proj files and references and then manually creates a solution each time.. but this seems overkill for such a simple thing.</p>
<p>Anyone solved / seen this before? </p>
|
<p>How are you calling MSBuild? If you point MSBuild to the solution file, it should be able to work out the dependencies. If you point it to individual project files, then it won't be able to resolve any project references.</p>
<p>If you don't use project references you can still control the dependency order in a solution by using the "Project Dependencies" dialog to manually set the dependencies.</p>
|
<p>While it is correct that MSBuild should observe the build order when you use project dependencies there is one caveat. It doesn't at present observe the reverse build order when building the clean target (as I have blogged about <a href="http://brumlemann.blogspot.com/2008/12/why-it-is-error-for-msbuild-to-build.html" rel="nofollow noreferrer">here</a>). For regular build however it works nicely as described by others here.</p>
| 36,558
|
<p>Similar to <a href="https://stackoverflow.com/questions/216710/call-openfiledialog-from-powershell">this question</a>, after running the following code the browser dialog does appear with all the correct buttons, but the selection area that usally displays available folders is missing:</p>
<pre><code>[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )
$d = New-Object Windows.Forms.FolderBrowserDialog
$d.ShowDialog( )
</code></pre>
|
<p>I encountered this problem a while back and found the following COM workaround on the MSDN forums:</p>
<pre><code>$app = new-object -com Shell.Application
$folder = $app.BrowseForFolder(0, "Select Folder", 0, "C:\")
if ($folder.Self.Path -ne "") {write-host "You selected " $folder.Self.Path}
</code></pre>
<p><a href="http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.dotnet.framework.windowsforms.controls&tid=3607557a-43b3-40bf-8276-be00526e0520&p=1" rel="noreferrer">http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.dotnet.framework.windowsforms.controls&tid=3607557a-43b3-40bf-8276-be00526e0520&p=1</a></p>
|
<p>Just FYI, if you are looking to do Windows Forms stuff, there is one product currently out that will do windows forms for PowerShell (The <a href="http://www.adminscripteditor.com/" rel="nofollow noreferrer">Admin Script Editor</a>) and Sapien is working on a <a href="http://hosted.verticalresponse.com/172892/13e80641d0/176000434/c46cbf224d/" rel="nofollow noreferrer">Forms Designer</a> (announced on the <a href="http://powerscripting.wordpress.com/2008/10/12/episode-45-rockin-roundtable/" rel="nofollow noreferrer">PowerScripting Podcast</a>), which might smooth out some of these issues for your script.</p>
| 26,652
|
<p>Does anyone know how to create a ClickOnce publication for a CD with the publish task in MSBuild?</p>
<p>VS2008 has a 'publish wizard' with a publish to CD radio button choice. It publishes a click once install to a local folder that is suitable for burning to a CD.</p>
<p>We are following a scheduled MSBuild with post processing steps in which we configure it and install it to a given environment, and we'd like to have a scriptable way of producing a CD of the ClickOnce output.</p>
<p>I have been able to make this process work for a web install, and a file share install, but it seems as though the 'publish wizard' does some hidden step that I can't discover.</p>
<p>I'm going out of my mind trying to correlate the various properties in the publish dialogs, the publish wizard, msbuild publish target, mage.exe and mageui.exe. Some items have the same name, some differ between dialogs and properties, some can be set in one area, but not in another.</p>
<p>I can see that automating ClickOnce can be done, but overall, it seems to be a GUI technology, and scripting it seems to go against its grain.</p>
<p>Bill</p>
|
<p>I've done a couple of things to give myself this functionality over the years. I build enterprise applicatons that may be distributed across many servers. I don't want to bury config settings in each services config file or each web server's web.config file. For application specific stuff I usually create an application settings table in the app's database. The table only has two fields. SettingName and SettingValue. I then write a web or wcf service whose sole function it is to retrieve these settings. I write a function called GetSetting where you pass "SettingName" and it returns SettingValue or an empty string if your setting is not found. This way I can store all application settings for all components of the application in one spot. Maintenance and troubleshooting for this is really easy, I'm not hunting through scads of config files spread across a dozen web and app servers.</p>
<p>For larger scale apps I might create a separate AppSettings database where I add a new field to my table mentioned above. ApplicationName. My web or wcf service for this approach has the same method call (GetSetting) only at this scope I pass ApplicationName and SettingName and it returns SettingValue or an empty string.</p>
<p>Doing either of these things allows you to centralize all app settings for any size application or IT shop. It has worked really well for us.</p>
|
<p>Any VCS through a secure channel?</p>
<p>For example, git through ssh (both available in cygwin).</p>
<p>I think the first step is to have the secure channel (if you want the push ability, pulling might be different).</p>
<p>As for managing the "versions" in different "branches", what's better than a version control system?</p>
<p>As it goes for the Microsoft requirement, well the Microsoft sofwares in that exists in that area would suck pretty bad in your case (as in not the best tool for the job).</p>
| 46,054
|
<p>is it possible to create java application that will
work as background process on symbian smartphones?</p>
|
<p>You can approximate it but J2ME (the version of java on mobile phones) may not be the right technology to do this.</p>
<ul>
<li><p>starting a MIDlet (a Java application for mobile phones) when the phone is switched on is tricky at best without coding a small Symbian OS C++ module that will start it for you. If you want to try anyway, look at the PushRegistry class in the MIDP specs
(<a href="http://java.sun.com/javame/reference/apis/jsr118/" rel="nofollow noreferrer">http://java.sun.com/javame/reference/apis/jsr118/</a>). The Content Handling API might provide some way to do it too (<a href="http://java.sun.com/javame/reference/apis/jsr211" rel="nofollow noreferrer">http://java.sun.com/javame/reference/apis/jsr211</a>). When you are ready to give up, do it in C++.</p></li>
<li><p>Backgrounding a MIDlet isn't hard. The phone's "menu" key will do it for you. Programatically, Canvas.setCurrent(null) has a good chance of working. Trying to trick the phone by providing a fully transparent GUI and not handling any keypad activity will absolutely not work. Creating and starting a separate Thread in the MIDlet should allow you to keep something running even after your overload of MIDlet.pauseApp() has been called by the application management system.</p></li>
<li><p>The real issue is that the MIDlet will not have any Inter Process Communication system unless you make one. The usual way of doing that is a loopback socket connection over which you transfer data. Not a nice or efficient way of simulating IPC. Sharing a RMS record can only be done from within the same MIDlet suite (you can package several MIDlets into the same .jar file), I think. The code to create a provider/consumer data flow over a file connection is even uglier and will raise security issues.</p></li>
</ul>
<p>Without any more information about what you want to use it for, my answer is : maybe but you should probably not try.</p>
|
<p>You can approximate it but J2ME (the version of java on mobile phones) may not be the right technology to do this.</p>
<ul>
<li><p>starting a MIDlet (a Java application for mobile phones) when the phone is switched on is tricky at best without coding a small Symbian OS C++ module that will start it for you. If you want to try anyway, look at the PushRegistry class in the MIDP specs
(<a href="http://java.sun.com/javame/reference/apis/jsr118/" rel="nofollow noreferrer">http://java.sun.com/javame/reference/apis/jsr118/</a>). The Content Handling API might provide some way to do it too (<a href="http://java.sun.com/javame/reference/apis/jsr211" rel="nofollow noreferrer">http://java.sun.com/javame/reference/apis/jsr211</a>). When you are ready to give up, do it in C++.</p></li>
<li><p>Backgrounding a MIDlet isn't hard. The phone's "menu" key will do it for you. Programatically, Canvas.setCurrent(null) has a good chance of working. Trying to trick the phone by providing a fully transparent GUI and not handling any keypad activity will absolutely not work. Creating and starting a separate Thread in the MIDlet should allow you to keep something running even after your overload of MIDlet.pauseApp() has been called by the application management system.</p></li>
<li><p>The real issue is that the MIDlet will not have any Inter Process Communication system unless you make one. The usual way of doing that is a loopback socket connection over which you transfer data. Not a nice or efficient way of simulating IPC. Sharing a RMS record can only be done from within the same MIDlet suite (you can package several MIDlets into the same .jar file), I think. The code to create a provider/consumer data flow over a file connection is even uglier and will raise security issues.</p></li>
</ul>
<p>Without any more information about what you want to use it for, my answer is : maybe but you should probably not try.</p>
| 11,910
|
<p>I have a databases table with ~50K rows in it, each row represents a job that need to be done. I have a program that extracts a job from the DB, does the job and puts the result back in the db. (this system is running right now)</p>
<p>Now I want to allow more than one processing task to do jobs but be sure that no task is done twice (as a performance concern not that this will cause other problems). Because the access is by way of a stored procedure, my current though is to replace said stored procedure with something that looks something like this</p>
<pre><code>update tbl
set owner = connection_id()
where available and owner is null limit 1;
select stuff
from tbl
where owner = connection_id();
</code></pre>
<p>BTW; worker's tasks might drop there connection between getting a job and submitting the results. Also, I don't expect the DB to even come close to being the bottle neck unless I mess that part up (~5 jobs per minute)</p>
<p>Are there any issues with this? Is there a better way to do this?</p>
<p>Note: the <a href="http://tripatlas.com/Database_as_an_IPC" rel="noreferrer">"Database as an IPC anti-pattern"</a> is only slightly apropos here because </p>
<ol>
<li>I'm not doing IPC (there is no process generating the rows, they all already exist right now) and </li>
<li>the primary gripe described for that anti-pattern is that it results in unneeded load on the DB as processes wait for messages (in my case, if there are no messages, everything can shutdown as everything is done)</li>
</ol>
|
<p>Here's what I've used successfully in the past:</p>
<p>MsgQueue table schema</p>
<pre><code>MsgId identity -- NOT NULL
MsgTypeCode varchar(20) -- NOT NULL
SourceCode varchar(20) -- process inserting the message -- NULLable
State char(1) -- 'N'ew if queued, 'A'(ctive) if processing, 'C'ompleted, default 'N' -- NOT NULL
CreateTime datetime -- default GETDATE() -- NOT NULL
Msg varchar(255) -- NULLable
</code></pre>
<p>Your message types are what you'd expect - messages that conform to a contract between the process(es) inserting and the process(es) reading, structured with XML or your other choice of representation (JSON would be handy in some cases, for instance). </p>
<p>Then 0-to-n processes can be inserting, and 0-to-n processes can be reading and processing the messages, Each reading process typically handles a single message type. Multiple instances of a process type can be running for load-balancing. </p>
<p>The reader pulls one message and changes the state to "A"ctive while it works on it. When it's done it changes the state to "C"omplete. It can delete the message or not depending on whether you want to keep the audit trail. Messages of State = 'N' are pulled in MsgType/Timestamp order, so there's an index on MsgType + State + CreateTime.</p>
<p>Variations:<br>
State for "E"rror.<br>
Column for Reader process code.<br>
Timestamps for state transitions. </p>
<p>This has provided a nice, scalable, visible, simple mechanism for doing a number of things like you are describing. If you have a basic understanding of databases, it's pretty foolproof and extensible.</p>
<hr>
<p>Code from comments:</p>
<pre><code>CREATE PROCEDURE GetMessage @MsgType VARCHAR(8) )
AS
DECLARE @MsgId INT
BEGIN TRAN
SELECT TOP 1 @MsgId = MsgId
FROM MsgQueue
WHERE MessageType = @pMessageType AND State = 'N'
ORDER BY CreateTime
IF @MsgId IS NOT NULL
BEGIN
UPDATE MsgQueue
SET State = 'A'
WHERE MsgId = @MsgId
SELECT MsgId, Msg
FROM MsgQueue
WHERE MsgId = @MsgId
END
ELSE
BEGIN
SELECT MsgId = NULL, Msg = NULL
END
COMMIT TRAN
</code></pre>
|
<p>You are trying to implement de "Database as IPC" antipattern. Look it up to understand why you should consider redesigning your software properly.</p>
| 38,031
|
<p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time-restricted license file.</p>
<p>If we distribute the <code>.py</code> files or even <code>.pyc</code> files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem?</p>
|
<p>Python, being a byte-code-compiled interpreted language, is very difficult to lock down. Even if you use a exe-packager like <a href="http://py2exe.org" rel="noreferrer">py2exe</a>, the layout of the executable is well-known, and the Python byte-codes are well understood.</p>
<p>Usually in cases like this, you have to make a tradeoff. How important is it really to protect the code? Are there real secrets in there (such as a key for symmetric encryption of bank transfers), or are you just being paranoid? Choose the language that lets you develop the best product quickest, and be realistic about how valuable your novel ideas are.</p>
<p>If you decide you really need to enforce the license check securely, write it as a small C extension so that the license check code can be extra-hard (but not impossible!) to reverse engineer, and leave the bulk of your code in Python.</p>
|
<p>I documented how to obfuscate the python by converting it to .so file, and converting it to a python wheel file:
<a href="https://github.com/UM-NLP/python-obfuscation" rel="nofollow noreferrer">https://github.com/UM-NLP/python-obfuscation</a></p>
| 32,728
|
<p>My asp.net mvc site needs some kind of authorization but it is rather different than the usual concept of users and thus membership.
It will be used more for preferences then for authentication actually. Accounts without any password should be possible (and will initially be the only type) and an account can also be used by multiple users at once. Depending on the user group it could be for example that all users of a certain region get a shared account.
This is a decision from the client('s marketing division) and is not up for discussion.</p>
<p>A certain landing page takes (only) a userId in the url that will load up an account which in turn has some preferences linked to it that can be used throughout the rest of the site.<br>
If a user doesn't start at the landing page or the sent accountId doesn't match a record in the system, he/she will be assigned the default account that has default preferences.</p>
<p>I was thinking of not re-inventing the wheel (somebody should find a new expression for this) and use the asp.net Membership system.
But the whole system is based around required passwords, email and single sessions per user, which are all things I can't provide.
Because the situation is a bit unconventional I thought a custom MembershipProvider etc would be in place. But it seems the gist of this is inheriting from the regular Membership classes. The methods of these classes all require things I am not needing.</p>
<p>Any suggestions</p>
|
<p>You could use the standard Membership provider and using the Built in .Validate() method sending the Username and a Password that is "standard" for all accounts without authentication.</p>
<p>Have 2 different User Controls 1 for "Validated Login with Password" and one for "Share Account without password", each uses Membership-login but the latter needs to have a bit set on the field of the member that says "Public Account = True / 1 "</p>
<p>Good luck, seems like a fun project, would be cool to see the outcome ;)</p>
<p>By the way, you don't need to share the session, or you could, just stored the session in the database and map the session to a user instead of a cookie, might work?</p>
<hr>
<p>As requested i'll elaborate on different user controls. Briefly i would have 2 Controls, one maybe called GlobalLogin and one called UserLogin, where GlobalLogin displays a Form which only has the Username, when submitted this will trigger a function that uses, as i stated before, a function which calls the Validate method in the Membership provider, with a pre-set password.</p>
<p>As a reflection, see all "Not logged in with password"-users as anonymous and treat them the same way, the only thing that is different is that they can access user-specific areas. This control also needs to check that a certain field in the database is set, such as a "Allows Globally Used Account Without Password"-field, where in this case, the bit / boolean needs to be true for this login to be accepted.</p>
<p>Now to the other part, the Control which handles Password Protected Accounts, this requires both Username & Password and this calls the Validate with these settings. Now, remember that when logged in with password, you can change your password, this SHOULD NOT be possible with a Global Account, because then your global password wouldnt work :)</p>
|
<p>There is detailed information on the Membership Provider at <a href="http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx</a>. Basically you need to create new provider, or derive from the existing, and overload the ValidateUser method to always return true.</p>
| 48,914
|
<p>How can I tell if SP1 has been installed on VS2008? e.g. If I'm working on a co-worker's machine - how can I tell if he/she has installed SP1 for VS2008?</p>
|
<p>In Help->About, you can view the installed products. You should see something similar to</p>
<blockquote>
<p>Microsoft Visual Studio Team System
2008 Team Suite - ENU Service Pack 1
(KB945140) KB945140</p>
</blockquote>
<p>in the list of entries.</p>
|
<p>It also puts a little '9' in a white box on the program icon. (Probably not dependable, of course)</p>
| 19,450
|
<p>Not sure what exactly is going on here, but seems like in .NET 1.1 an uninitialized event delegate can run without issues, but in .NET 2.0+ it causes a NullReferenceException. Any ideas why. The code below will run fine without issues in 1.1, in 2.0 it gives a NullReferenceException. I'm curious why does it behave differently? What changed?</p>
<p>Thanks</p>
<p>eg</p>
<pre><code>class Class1
{
public delegate void ChartJoinedRowAddedHandler(object sender);
public static event ChartJoinedRowAddedHandler ChartJoinedRowAdded;
public static DataTable dt;
public static void Main()
{
dt = new DataTable();
dt.RowChanged += new DataRowChangeEventHandler(TableEventHandler);
object [] obj = new object[]{1,2};
dt.Columns.Add("Name");
dt.Columns.Add("Last");
dt.NewRow();
dt.Rows.Add(obj);
}
private static void TableEventHandler(object sender, DataRowChangeEventArgs e)
{
ChartJoinedRowAdded(new object());
}
}
</code></pre>
|
<p>[updated] AFAIK, there was no change here to the fundamental delegate handling; the difference is in how DataTable behaves.</p>
<p>However! Be very careful using static events, especially if you are subscribing from instances (rather than static methods). This is a good way to keep huge swathes of objects alive and not be garbage collected.</p>
<p>Running the code via csc from 1.1 shows that the general delegate side is the same - I think the difference is that the DataTable code that raises RowChanged was swallowing the exception. For example, make the code like below:</p>
<pre><code> Console.WriteLine("Before");
ChartJoinedRowAdded(new object());
Console.WriteLine("After");
</code></pre>
<p>You'll see "Before", but no "After"; an exception was thrown and swallowed by the DataTable.</p>
|
<p>The way events work hasn't really changed from 1.1 to 2</p>
<p>Although the syntax looks like normal aggregation it really isn't:</p>
<pre><code>dt.RowChanged += TableEventHandler;
dt.RowChanged += null;
dt.RowChanged += delegate (object sender, DataRowChangeEventArgs e) {
//anon
};
</code></pre>
<p>Will fire <code>TableEventHandler</code> and then the delegate - the null is just skipped.</p>
<p>You can use null to clear events, but only inside the event firing class:</p>
<pre><code>this.MyEvent = null;
</code></pre>
<p>If nothing subscribes your event will be null - see soraz's answer. The <code>DataTable</code> class will contain a similar check and won't fire the event if there are no subscribers.</p>
<p>The standard pattern is:</p>
<pre><code>//events should just about always use this pattern: object, args
public static event EventHandler<MyEventArgs> ChartJoinedRowAdded;
//inheriting classes can override this event behaviour
protected virtual OnChartJoinedRowAdded() {
if( ChartJoinedRowAdded != null )
ChartJoinedRowAdded( this, new MyEventArgs(...) );
}
</code></pre>
| 21,945
|
<p>In Microsoft IL, to call a method on a value type you need an indirect reference. Lets say we have an ILGenerator named "il" and that currently we have a Nullable on top of the stack, if we want to check whether it has a value then we could emit the following:</p>
<pre><code>var local = il.DeclareLocal(typeof(Nullable<int>));
il.Emit(OpCodes.Stloc, local);
il.Emit(OpCodes.Ldloca, local);
var method = typeof(Nullable<int>).GetMethod("get_HasValue");
il.EmitCall(OpCodes.Call, method, null);
</code></pre>
<p>However it would be nice to skip saving it as a local variable, and simply call the method on the address of the variable already on the stack, something like:</p>
<pre><code>il.Emit(/* not sure */);
var method = typeof(Nullable<int>).GetMethod("get_HasValue");
il.EmitCall(OpCodes.Call, method, null);
</code></pre>
<p>The ldind family of instructions looks promising (particularly ldind_ref) but I can't find sufficient documentation to know whether this would cause boxing of the value, which I suspect it might.</p>
<p>I've had a look at the C# compiler output, but it uses local variables to achieve this, which makes me believe the first way may be the only way. Anyone have any better ideas?</p>
<p>**** Edit: Additional Notes ****</p>
<p>Attempting to call the method directly, as in the following program with the lines commented out, doesn't work (the error will be "Operation could destabilise the runtime"). Uncomment the lines and you'll see that it does work as expected, returning "True".</p>
<pre><code>var m = new DynamicMethod("M", typeof(bool), Type.EmptyTypes);
var il = m.GetILGenerator();
var ctor = typeof(Nullable<int>).GetConstructor(new[] { typeof(int) });
il.Emit(OpCodes.Ldc_I4_6);
il.Emit(OpCodes.Newobj, ctor);
//var local = il.DeclareLocal(typeof(Nullable<int>));
//il.Emit(OpCodes.Stloc, local);
//il.Emit(OpCodes.Ldloca, local);
var getValue = typeof(Nullable<int>).GetMethod("get_HasValue");
il.Emit(OpCodes.Call, getValue);
il.Emit(OpCodes.Ret);
Console.WriteLine(m.Invoke(null, null));
</code></pre>
<p>So you can't simply call the method with the value on the stack because it's a value type (though you could if it was a reference type).</p>
<p>What I'd like to achieve (or to know whether it is possible) is to replace the three lines that are shown commented out, but keep the program working, without using a temporary local.</p>
|
<p>If the variable is already on the stack, you can go ahead and just emit the method call. </p>
<p>It seems that the constructor doesn't push the variable on the stack in a typed form. After digging into the IL a bit, it appears there are two ways of using the variable after constructing it. </p>
<p>You can load the variable that will store the reference onto the evaluation stack before calling the constructor, and then load that variable again after calling the constructor like so:</p>
<pre><code>DynamicMethod method = new DynamicMethod("M", typeof(bool), Type.EmptyTypes);
ILGenerator il = method.GetILGenerator();
Type nullable = typeof(Nullable<int>);
ConstructorInfo ctor = nullable.GetConstructor(new Type[] { typeof(int) });
MethodInfo getValue = nullable.GetProperty("HasValue").GetGetMethod();
LocalBuilder value = il.DeclareLocal(nullable);
// load the variable to assign the value from the ctor to
il.Emit(OpCodes.Ldloca_S, value);
// load constructor args
il.Emit(OpCodes.Ldc_I4_6);
il.Emit(OpCodes.Call, ctor);
il.Emit(OpCodes.Ldloca_S, value);
il.Emit(OpCodes.Call, getValue);
il.Emit(OpCodes.Ret);
Console.WriteLine(method.Invoke(null, null));
</code></pre>
<p>The other option is doing it the way you have shown. The only reason for this that I can see is that the ctor methods return void, so they don't put their value on the stack like other methods. It does seem strange that you can call Setloc if the new object isn't on the stack.</p>
|
<p>Just wrote a class that does what the OP is asking... here's the IL code that C# compiler produces:</p>
<pre><code> IL_0008: ldarg.0
IL_0009: ldarg.1
IL_000a: newobj instance void valuetype [mscorlib]System.Nullable`1<int32>::.ctor(!0)
IL_000f: stfld valuetype [mscorlib]System.Nullable`1<int32> ConsoleApplication3.Temptress::_X
IL_0014: nop
IL_0015: ret
</code></pre>
| 10,187
|
<p>I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?</p>
|
<p>You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript. JSON is not only lighterweight but easier to make in javascript. Check out <a href="http://mike.teczno.com/json.html" rel="noreferrer">JSON-PHP</a> for parsing JSON.</p>
<p>You might want to take a look at <a href="http://extjs.com/learn/Tutorial:Creating_JSON_Data_in_PHP" rel="noreferrer">Creating JSON Data in PHP</a></p>
|
<p>You can create an array and send it, as Meador recommended:
(following code is Mootooled, but similar in other libraries / plain old JS)</p>
<pre><code>myArray.each(function(item, index) myObject.set('arrayItems['+index+']', item);
myAjax.send(myObject.toQueryString());
</code></pre>
<p>That will send to php an array called arrayItems, which can be accessed through $_POST['arrayItems'] </p>
<pre><code>echo $_POST['arrayItems'] ;
</code></pre>
<p>will echo something like: array=>{[0]=>'first thing', [1]=> second thing}</p>
| 38,396
|
<p>I'm creating HTML with a loop that has a column for Action. That column
is a Hyperlink that when the user clicks calls a JavaScript
function and passes the parameters...</p>
<p>example:</p>
<pre><code><a href="#" OnClick="DoAction(1,'Jose');" > Click </a>
<a href="#" OnClick="DoAction(2,'Juan');" > Click </a>
<a href="#" OnClick="DoAction(3,'Pedro');" > Click </a>
...
<a href="#" OnClick="DoAction(n,'xxx');" > Click </a>
</code></pre>
<p>I want that function to call an Ajax jQuery function with the correct
parameters.</p>
<p>Any help?</p>
|
<p>Using POST</p>
<pre><code>function DoAction( id, name )
{
$.ajax({
type: "POST",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
</code></pre>
<p>Using GET</p>
<pre><code>function DoAction( id, name )
{
$.ajax({
type: "GET",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
</code></pre>
<p>EDIT:</p>
<p>A, perhaps, better way to do this that would work (using GET) if javascript were not enabled would be to generate the URL for the href, then use a click handler to call that URL via ajax instead.</p>
<pre><code><a href="/someurl.php?id=1&name=Jose" class="ajax-link"> Click </a>
<a href="/someurl.php?id=2&name=Juan" class="ajax-link"> Click </a>
<a href="/someurl.php?id=3&name=Pedro" class="ajax-link"> Click </a>
...
<a href="/someurl.php?id=n&name=xxx" class="ajax-link"> Click </a>
<script type="text/javascript">
$(function() {
$('.ajax-link').click( function() {
$.get( $(this).attr('href'), function(msg) {
alert( "Data Saved: " + msg );
});
return false; // don't follow the link!
});
});
</script>
</code></pre>
|
<p>Do you want to pass parameters to another page or to the function only?</p>
<p>If only the function, you don't need to add the $.ajax() tvanfosson added. Just add your function content instead.
Like:</p>
<pre><code>function DoAction (id, name ) {
// ...
// do anything you want here
alert ("id: "+id+" - name: "+name);
//...
}
</code></pre>
<p>This will return an alert box with the id and name values.</p>
| 48,382
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.