input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
How well does F# perform compared to C#? <p>Of course both F# and C# compile to IL and the CLR JITter does most of the hard work, however I wanted to know whether there's anything implicit in the F# language or its core libraries which result in lesser performance compared to C#?</p>
<p>Additionally, is there anything in the use of functional programming in the .net framework that might make it slower compared to C#?</p>
<p>I am going to sit down and <em>measure</em> differences of course, as that really is the only real way to know for sure, however I just wondered whether anybody had any broad-stroke knowledge on this topic.</p>
<h1>See Also</h1>
<ul>
<li><a href="http://stackoverflow.com/questions/144227/c-f-performance-comparison">C# / F# Performance comparison</a></li>
<li><a href="http://stackoverflow.com/questions/142985/is-a-program-f-any-more-efficient-execution-wise-than-c">Is a program F# any more efficient (execution-wise) than C#?</a></li>
</ul>
| <p>There is nothing intrinsic that makes one language faster than the other. They both run on the CLR and hence have roughly the same performance characteristics of any language that runs on the CLR. There are features of the respective languages though that do affect performance.</p>
<p>Tail recursion is a great example. If you write an F# app which heavily uses tail recursion, the compiler will attempt to rewrite it as an iterative loop removing the recursion penalty. Additionally F# uses the .tail IL op code in order to ask the CLR to remove the recursion stack penalty where possible. </p>
<p>It's easy to demonstrate this by translating some F# continuation samples to C# and then insert huge data sets. F# will work and C# will eventually crash.</p>
<p><a href="http://blogs.msdn.com/jaredpar/archive/2008/11/13/comparing-continuations-in-c-and-f-part-3-double-wrong.aspx" rel="nofollow">http://blogs.msdn.com/jaredpar/archive/2008/11/13/comparing-continuations-in-c-and-f-part-3-double-wrong.aspx</a></p>
<p>But that is not necessarily a deficiency in C#. C# is not meant to be written with continuations while that is certainly the case in F#. It's in fact not surprising that writing algorithms meant for F# in C# produce not so great results.</p>
<p>Conversely, C# iterators are usually more efficient than F# sequence expressions. The reason is that C# iterators are very efficient state machines vs. F#'s are continuation passing. </p>
<p>In general though, in the abscence of threads, if you use the languages as they are intended to be used they will have similar performance characteristics. </p>
|
Add ADO.NET data tables to a blank MDB file <p>How can I add several data tables that I've built in code, to a blank MDB file that ships with my application?</p>
<p>I find it easy enough to connect to the MDB file via the OledbConnection object, but then I'm at a loss for an easy way to add my tables to it. There it sits, open and empty, but what is next?</p>
<p>I can add my tables to a dataset easily enough, but I still don't see an easy way to map the dataset over to my open MDB file.</p>
<p>Am I missing an easy fix for this? I'd like to avoid using <a href="http://msdn.microsoft.com/en-us/library/ms803875" rel="nofollow">ADOX</a> if possible. I also see that it is very easy to write the dataset out as XML, but I find no similar functionality for writing out an MDB file.</p>
| <p>DataSet intrinsically understands the XML storage, you might think of it (very loosely mind) as its native data store. In fact XML storage is meant for temporary or transistory storage so that a DataSet can be re-constituted between application re-starts or transference between machines.</p>
<p>On the other hand, true persistence stores such as MDB, SQL Server, Oracle or whatever are entirely alien to the Dataset, that's why you need provider specific Adapters to transfer data to and from the Dataset.</p>
<p>Unless you can find a project out in web-land where someone has done this before you are going to need to create your own code to analyse the dataset schema then send DDL to you MDB connection to create the tables.</p>
|
Scenarios where automated testing is unhelpful <p>What are some situations where unit testing and TDD and the like are more trouble than they're worth?</p>
<p>Some things I've come up with are:</p>
<ul>
<li>When generating test data is tricky: Sometimes, being able to come up with valid, non trivial test data is a challenge in itself.</li>
<li>When the only practical way of verifying correctness of the code is to run it.</li>
<li>When you're testing visual elements of the design.</li>
</ul>
<p>What are some other cases?</p>
| <p>I believe your first two points are not valid. </p>
<ul>
<li>Creating test data may be a challenge (in fact, it's <em>usually</em> a major part of writing unit tests), but that's simply something you have to accept, not a reason to give up on unit tests. And it can't be impossible, otherwise how would you ever know your app is working correctly?</li>
<li>Unit tests run the code in order to verify its correctness - I don't see the problem.</li>
</ul>
<p>There certainly are <em>aspects</em> of an application that cannot be unit-tested - visual layout (screen or print) is one such aspect, as is usability in general - things that cannot really be formally specified.</p>
<p>A situation where unit testing may not be applicable is when you're faced with an existing application that was not developed with testability or even modularity in mind (<a href="http://www.laputan.org/mud/" rel="nofollow">Big Ball of Mud</a> Anti-pattern). But even then, if you know you'll have to maintain and extend this beast for a significant length of time, it is nearly always possible and useful to find a way to automatically test at least some parts of the application. Nobody says you have to write a test suite that achieves 100% code coverage before doing anything else.</p>
|
beep in WinCE , it possible ? <p>is it possible to make beep in WinCE ?</p>
<p>i try and i get an error</p>
| <p>The .net framework methods for beeing are not available in the CF version of the framework. The best way to get a beep sound is to PInvoke into the MessageBeep function. The PInvoke signature for this method is pretty straight forward</p>
<pre><code>[DllImport("CoreDll.dll")]
public static extern void MessageBeep(int code);
public static void MessageBeep() {
MessageBeep(-1); // Default beep code is -1
}
</code></pre>
<p>This blog post has an excellent more thorough example: <a href="http://web.archive.org/web/20090601181423/http://blog.digitforge.com/?p=4" rel="nofollow">http://blog.digitforge.com/?p=4 (on archive.org)</a></p>
|
Host files or stream data on a self-hosted WCF (non-IIS) service that uses HTTP? <p>Is it possible to host custom data on self-hosted HTTP-configured WCF services, such as custom HTML or XML files, without involving IIS? Iâm speaking of a ServiceHost instance that instantiates its own EndPoints/listeners.</p>
<p>I have an app that uses a self-hosted WCF service and it has a Windows Forms client but Iâm looking at adding a lightweight Silverilght interface as well, but I donât want to use IIS for the same reason as I didnât want to use full-blown SQL Server -- I'm trying to make the whole thing self-packaged without IIS dependencies. (Yes, I know that not involving IIS isnât best practice as it will make it somewhat less reliable and less flexible, but this feature isnât a major part of this.)</p>
<p>If this is not possible, Iâll have to choose between full-blown IIS on the server or full-blown WPF on the client, I was just curious if anyone had uncovered this before.</p>
<p>Thanks,</p>
<p>Jon </p>
| <p>OK found my answer. The [OperationContract] has a WebGet property that you can assign a URL. The method this attribute is associated with can then return a Stream object.</p>
<p>Example here: <a href="http://blogs.msdn.com/carlosfigueira/archive/2008/03/07/enabling-cross-domain-calls-for-silverlight-apps-on-self-hosted-web-services.aspx" rel="nofollow">exposing cross-policy file as part of WCF service</a>. :)</p>
<p>With this I can then use Cassini on a separate port to serve Silverlight .xap over HTTP, and still point to the WCF service at the original WCF URL. Theoretically, I could perhaps for that matter even host the .xap and containing HTML from a similar WCF interface, dropping the need for a policy file.</p>
|
Using gdb, display multiple vars in one line? <p>How can I ask to <em>display</em> multiple vars in one line? So I want to get output like:</p>
<pre><code>30 if(s[i] != '\0')
5: s[i] = 101 'e'
4: exp = 14
3: val = 123.45
2: sign = 1
1: i = 6
</code></pre>
<p>I've been typing in disp s[i] ENTER disp exp ENTER (etc, etc) and I just know there's got to be a better way to do this in one line of typing.</p>
| <p>To establish multiple active "variable displays" without re-typing each of <code>display i</code>, <code>display s[i]</code>, etc. every time you restart GDB, use a GDB "canned command sequence".</p>
<p>For example, add this to your <code>~/.gdbinit</code>:</p>
<pre><code>define disp_vars
disp i
disp sign
disp val
disp exp
disp s[i]
end
</code></pre>
<p>Now you can add all the displays at once by typing <code>disp_vars</code> at the GDB prompt.</p>
|
How to properly mock and unit test <p>I'm basically trying to teach myself how to code and I want to follow good practices. There are obvious benefits to unit testing. There is also much zealotry when it comes to unit-testing and I prefer a much more pragmatic approach to coding and life in general. As context, I'm currently writing my first "real" application which is the ubiquitous blog engine using asp.net MVC. I'm loosely following the MVC Storefront architecture with my own adjustments. As such, this is my first real foray into mocking objects. I'll put the code example at the end of the question.</p>
<p>I'd appreciate any insight or outside resources that I could use to increase my understanding of the fundamentals of testing and mocking. The resources I've found on the net are typically geared towards the "how" of mocking and I need more understanding of the where, why and when of mocking. If this isn't the best place to ask this question, please point me to a better place.</p>
<p>I'm trying to understand the value that I'm getting from the following tests. The UserService is dependent upon the IUserRepository. The value of the service layer is to separate your logic from your data storage, but in this case most of the UserService calls are just passed straight to IUserRepository. The fact that there isn't much actual logic to test could be the source of my concerns as well. I have the following concerns.</p>
<ul>
<li>It feels like the code is just testing that the mocking framework is working. </li>
<li>In order to mock out the dependencies, it makes my tests have too much knowledge of the IUserRepository implementation. Is this a necessary evil? </li>
<li>What value am I actually gaining from these tests? Is the simplicity of the service under test causing me to doubt the value of these tests. </li>
</ul>
<p>I'm using NUnit and Rhino.Mocks, but it should be fairly obvious what I'm trying to accomplish.</p>
<pre><code> [SetUp]
public void Setup()
{
userRepo = MockRepository.GenerateMock<IUserRepository>();
userSvc = new UserService(userRepo);
theUser = new User
{
ID = null,
UserName = "http://joe.myopenid.com",
EmailAddress = "joe@joeblow.com",
DisplayName = "Joe Blow",
Website = "http://joeblow.com"
};
}
[Test]
public void UserService_can_create_a_new_user()
{
// Arrange
userRepo.Expect(repo => repo.CreateUser(theUser)).Return(true);
// Act
bool result = userSvc.CreateUser(theUser);
// Assert
userRepo.VerifyAllExpectations();
Assert.That(result, Is.True,
"UserService.CreateUser(user) failed when it should have succeeded");
}
[Test]
public void UserService_can_not_create_an_existing_user()
{
// Arrange
userRepo.Stub(repo => repo.IsExistingUser(theUser)).Return(true);
userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
// Act
bool result = userSvc.CreateUser(theUser);
// Assert
userRepo.VerifyAllExpectations();
Assert.That(result, Is.False,
"UserService.CreateUser() allowed multiple copies of same user to be created");
}
</code></pre>
| <p>Essentially what you are testing here is that the methods are getting called, not whether or not they actually work. Which is what mocks are supposed to do. Instead of calling the method, they just check to see if the method got called, and return whatever is in the Return() statement. So in your assertion here:</p>
<pre><code>Assert.That(result, Is.False, "error message here");
</code></pre>
<p>This assertion will ALWAYS succeed because your expectation will ALWAYS return false, because of the Return statement:</p>
<pre><code>userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
</code></pre>
<p>I'm guessing this isn't that useful in this case.</p>
<p>Where mocking is useful is when you want to, for example, make a database call somewhere in your code, but you don't want to actually call to the database. You want to pretend that the database got called, but you want to set up some fake data for it to return, and then (here's the important part) test the logic that does something with the fake data your mock returned. In the above examples you are omitting the last step. Imagine you had a method that displayed a message to the user that said whether the new user was created:</p>
<pre><code>public string displayMessage(bool userWasCreated) {
if (userWasCreated)
return "User created successfully!";
return "User already exists";
}
</code></pre>
<p>then your test would be</p>
<pre><code>userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
Assert.AreEqual("User already exists", displayMessage(userSvc.CreateUser(theUser)))
</code></pre>
<p>Now this has some value, because you are testing some actual behavior. Of course, you could also just test this directly by passing in "true" or "false." You don't even need a mock for that test. Testing expectations is fine, but I've written plenty of tests like that, and have come to the same conclusion that you are reaching - it just isn't that useful.</p>
<p>So in short, mocking is useful when you want to abstract away externalities, like databases, or webservice calls, etc, and inject known values at that point. But it's not often useful to test mocks directly.</p>
|
a simple regexp validator <p>How do a I create a validator, which has these simple rules. An expression is valid if </p>
<p>it must start with a letter<br />
it must end with a letter<br />
it can contain a dash (minus sign), but not at start or end of the expression </p>
| <pre><code>^[a-zA-Z]+-?[a-zA-Z]+$
</code></pre>
<p>E.g.</p>
<pre><code>def validate(whatever)
reg = /^[a-zA-Z]+-?[a-zA-Z]+$/
return (reg.match(whatever)) ? true : false;
end
</code></pre>
|
Adding scripting security to an application <p>Let's say I have an existing application written in Java which I wish to add scripting support to. This is fairly trivial with Groovy (and just as trivial in .Net with any of the Iron range of dynamic languages).</p>
<p>As trivial as adding the support is, it raises a whole host of questions about script execution and security - and how to implement that security.</p>
<p>Has anyone come across any interesting articles/papers or have any insights into this that they'd like to share? In particular I'd be very interested in architectural things like execution contexts, script authentication, script signing and things along those lines... you know, the kind of stuff that prevents users from running arbitrary scripts they just happened to download which managed to screw up their entire application, whilst still allowing scripts to be useful and flexible.</p>
<p><strong>Quick Edit</strong></p>
<p>I've mentioned signing and authentication as different entities because I see them as different aspects of security.</p>
<p>For example, as the developer/supplier of the application I distribute a signed script. This script is legitimately "data destructive" by design. Such as it's nature, it should only be run by administrators and therefore the vast majority of users/system processes should not be able to run it. This being the case it seems to me that some sort of security/authentication context is required based on the actions the script performs and who is running that script.</p>
| <blockquote>
<p>script signing</p>
</blockquote>
<p>Conceptually, that's just reaching into your cryptographic toolbox and using the tools that exist. Have people sign their code, validate the signatures on download, and check that the originator of the signature is trusted.</p>
<p>The hard(er) question is what makes people worthy of trust, and who gets to choose that. Unless your users are techies, they don't want to think about that, and so they won't set good policy. On the other hand, you'll probably <em>have</em> to let the users introduce trust [unless you want to go for an iPhone AppStore-style walled garden, which it doesn't sound like].</p>
<blockquote>
<p>script authentication</p>
</blockquote>
<p>How's this different from signing? Or, is your question just that: "what are the concepts that I should be thinking about here"?</p>
<p>The real question is of course: what do you want your users to be secured against? Is it only in-transit modification, or do you also want to make guarantees about the behavior of the scripts? Some examples might be: scripts can't access the file system, scripts can only access a particular subtree of the file system, scripts can't access the network, etc.</p>
<p>I think it might be possible [with a modest amount of work] to provide some guarantees about how scripts access the outside world if they were done in haskell and the IO monad was broken into smaller pieces. Or, possibly, if you had the scripts run in their own opaque monad with access to a limited part of IO. Be sure to remove access to unsafe functions.</p>
<p>You may also want to look at the considerations that went into the Java (applet) security model.</p>
<p>I hope this gives you something to think about.</p>
|
How to read inline styling of an element? <p>Howdy all. I'd like to know if it's possible to determine what <strong>inline styling</strong> has been attributed to an HTML element. I do not need to retrieve the value, but rather just detect if it's been set inline or not.</p>
<p>For instance, if the HTML were:</p>
<pre><code><div id="foo" style="width: 100px; height: 100px; background: green;"></div>
</code></pre>
<p>How can I determine that "width," "height," and "background" have been explicitly declared, inline?</p>
<p>As far as I can tell, the solution can work two ways. I can ask it if a specific attribute is set and it will tell me true or false, or it can tell me all attributes that have been set. Like so:</p>
<pre><code>var obj = document.getElementById('foo');
obj.hasInlineStyle('width'); //returns true;
obj.hasInlineStyle('border'); //returns false;
//or
obj.getInlineStyles(); //returns array with values:
// 'width' 'height' and 'background'
</code></pre>
<p>I'm not interested in css attributes that are inherited via declarations in a stylesheet, only inline styles. One last thing, I have no control over the HTML source.</p>
<p>Thanks</p>
| <p><strong>Updated to work with IE</strong></p>
<p>You could try something like this</p>
<pre><code>function hasInlineStyle(obj, style) {
var attrs = obj.getAttribute('style');
if(attrs === null) return false;
if(typeof attrs == 'object') attrs = attrs.cssText;
var styles = attrs.split(';');
for(var x = 0; x < styles.length; x++) {
var attr = styles[x].split(':')[0].replace(/^\s+|\s+$/g,"").toLowerCase();
if(attr == style) {
return true;
}
}
return false;
}
</code></pre>
<p>So if you have an element like this:</p>
<pre><code><span id='foo' style='color: #000; line-height:20px;'></span>
</code></pre>
<p>That also has a stylesheet like this:</p>
<pre><code>#foo { background-color: #fff; }
</code></pre>
<p>The function would return...</p>
<pre><code>var foo = document.getElementById('foo');
alert(hasInlineStyle(foo,'color')); // true
alert(hasInlineStyle(foo,'background-color')); // false
</code></pre>
|
Comparing two integers without any comparison <p>Is it possible to find the greatest of two integers without any comparison? I found some solutions: </p>
<pre><code>if(!(a/b)) // if a is less than b then division result will be zero.
{
cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now. check whether they are equal.
{
cout << "a and b are equal";
}
else
cout << "a is greater than b";
</code></pre>
<p>But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.</p>
| <p>Subtract them and check the sign using nasty bit twiddling hacks<br />
<a href="http://graphics.stanford.edu/~seander/bithacks.html">http://graphics.stanford.edu/~seander/bithacks.html</a></p>
<p>Don't do this in production code if the other programmers know where you live.</p>
|
Problems with big query and subquery <p>I thought that I'll be clever and use subquery to get my <a href="http://stackoverflow.com/questions/470992/how-to-count-number-of-different-items-in-sql#471152">report</a> in one go. But after running into problems and reading documentation I saw that my approach does not work in MySQL. My inner query returns ~100 records and outer query scans 20000 records.
When I restricted outer query to 20 records then it run 20 sec - really slow.</p>
<p>I wonder is it possible to restructure it somehow so that inner query wouldn't be run EVERY time for every record in the outer query?</p>
<pre><code>select p1.surname ,p1.name,p1.id,r1.start_date,r1.end_date,c1.short_name
FROM ejl_players p1
left JOIN ejl_registration r1 ON ( r1.player_id = p1.id )
left JOIN ejl_teams t1 ON ( r1.team_id = t1.id )
left JOIN ejl_clubs c1 ON ( t1.club_id = c1.id )
where r1.season=2008
and p1.id in
(
SELECT p.id
FROM ejl_players p
left JOIN ejl_registration r ON (r.player_id = p.id)
left JOIN ejl_teams t ON (r.team_id = t.id)
left JOIN ejl_clubs c ON (t.club_id = c.id)
WHERE r.season = 2008
GROUP BY p.id
HAVING COUNT(DISTINCT c.id) > 1
)
</code></pre>
<p>Explain (I restricted outer query to maximum 20 records:</p>
<pre><code>id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY p1 range PRIMARY PRIMARY 4 NULL 19 Using where
1 PRIMARY r1 ref team_id,season season 10 const,d17528sd14898.p1.id 1 Using where
1 PRIMARY t1 eq_ref PRIMARY PRIMARY 4 d17528sd14898.r1.team_id 1
1 PRIMARY c1 eq_ref PRIMARY PRIMARY 4 d17528sd14898.t1.club_id 1
2 DEPENDENT SUBQUERY p index PRIMARY PRIMARY 5 NULL 23395 Using index
2 DEPENDENT SUBQUERY r ref team_id,season season 10 const,d17528sd14898.p.id 1 Using where; Using index
2 DEPENDENT SUBQUERY t eq_ref PRIMARY PRIMARY 4 d17528sd14898.r.team_id 1
2 DEPENDENT SUBQUERY c eq_ref PRIMARY PRIMARY 4 d17528sd14898.t.club_id 1 Using index
</code></pre>
| <p>Try using an INNER JOIN (something like this):</p>
<pre><code>SELECT p1.surname ,p1.name,p1.id,r1.start_date,r1.end_date,c1.short_name
FROM ejl_players p1
INNER JOIN (
SELECT p.id
FROM ejl_players p
LEFT JOIN ejl_registration r ON (r.player_id = p.id)
LEFT JOIN ejl_teams t ON (r.team_id = t.id)
LEFT JOIN ejl_clubs c ON (t.club_id = c.id)
WHERE r.season = 2008
GROUP BY p.id
HAVING COUNT(DISTINCT c.id) > 1
) p2 ON p1.id = p2.id
LEFT JOIN ejl_registration r1 ON ( r1.player_id = p1.id )
LEFT JOIN ejl_teams t1 ON ( r1.team_id = t1.id )
LEFT JOIN ejl_clubs c1 ON ( t1.club_id = c1.id )
WHERE r1.season=2008
</code></pre>
<p>Using the subquery in this manner should be more efficient but isn't always. However, it does bypass the issue of having the subquery executed for every record returned in the main query. Instead the subquery is constructed as a virtual table in memory and then used for comparison with the main query.</p>
<p><b>Edit:</b> I should point out that you'll want to use EXPLAIN in MySQL to verify that this query is indeed performing more efficiently.</p>
|
iPhone Mic volume <p>Is there any way to poll the mic input volume with AVFoundation? I have seen the CoreAudio examples like SpeakHere but I really only need the current value. Is CA my only option?</p>
| <p>You should checkout SCListener. It's a simple way just to get the average or peak level of the mic.</p>
<p><a href="http://github.com/stephencelis/sc%5Flistener" rel="nofollow">http://github.com/stephencelis/sc_listener</a></p>
|
What are the File Permission Signs @ and + for? <p>My mac has folders Shared and Public folders. Their permissions are drwxr-xr-x+ for Public and drwxrwxrwt@ for Shared. What do the signs + and @ mean?</p>
| <p>@ means there are "extended attributes". Type</p>
<pre><code>ls -l@
</code></pre>
<p>to see what they are. With that command, everything with a @ after it will have some extra lines explaining why it has a @. In my experience, the @ usually means a file is going to be opened with an application other than the default (i.e. it might open with a different text editor than you're used to), or occasionally that it's in a different encoding than the default specified by $LANG.</p>
<p>No idea about the +. I've never run across it.</p>
<p>EDIT: From the manpage for "ls":</p>
<p>If the file or directory has extended attributes, the permissions field printed by the -l option is followed by a '@' character. Otherwise, if the file or directory has extended security information, the permissions field printed by the -l option is followed by a '+' character.</p>
|
Need help in refreshing the page after submit <p>I am developing an web application following the 3 tier architecture.When i am hitting on submit button data is storing in database but not showing response message like "Record submitted successfully" and fields are not refreshing. Here is my code:</p>
<pre><code>protected void BtnSubmit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
NewuserBAL NUB = new NewuserBAL();
string UserName = TxtUserName.Text;
string Password = PWD.Text;
string EmailId = Email.Text;
try
{
NUB.newinsert(UserName, Password, EmailId);
Response.Write("<b>New User Created Successfully</b>");
TxtUserName.Text = "";
PWD.Text = "";
CnfrmPwd.Text = "";
Email.Text = "";
}
catch
{
throw;
}
finally
{
NUB = null;
}
}
</code></pre>
<p>Thanks,
Masum</p>
| <p>Rather than using Response.Write, set a label such as labelResults to display the outcome. Response.Write is not going to show up in the proper place in your rendered HTML.</p>
|
Control camera via Firewire <p>Some SONY Cameras have a <a href="http://en.wikipedia.org/wiki/Firewire" rel="nofollow">FireWire</a> interface.</p>
<p>Is it possible to control any <strong>camera</strong> functions via FireWire using any <a href="http://www.unibrain.com/Products/DriverAPI/FireAPI.html" rel="nofollow">FireWire SDK</a> etc?</p>
<ul>
<li><strong>Tape:</strong> record/stop, forward/rewind</li>
<li><strong>Lens:</strong> exposure, zoom, shutter speed, focus, white balance</li>
<li><strong>Other:</strong> effects (sepia/invert)</li>
</ul>
<p><strong>Found:</strong></p>
<ul>
<li><a href="http://www.adobe.com/products/premiere/" rel="nofollow">Adobe Premiere</a> can <a href="http://www.manifest-tech.com/premiere/dvcapture.htm#DV%20Device%20Control" rel="nofollow">control <strong>Tape</strong> playback</a> functions (play, forward/rewind)</li>
</ul>
| <p>The open source video editor <a href="http://www.kinodv.org/" rel="nofollow">kinoDV</a> does this for all kinds of cameras, including sony. Maybe have a look at the source ?</p>
|
SQL Server column relationships <p>I've got two tables.</p>
<p>One is "Corporations" (e.g., one record is for Taco Bell). The index and PK for this table is named "Id".</p>
<p>I've got another table: "Branches" (e.g., one record is for Los Angeles). The Branch table has a column named "Corporation". This column should only accept an "Id" value that corresponds with an "Id" in the "Corporations" table.</p>
<p>How do I enforce this? Do I add a constraint? How do I do that?</p>
<p>If I'm barking up the wrong tree, how do I define this relationship between Corporations and Branches?</p>
| <p>Add a FOREIGN KEY to Branches that references Corporations.</p>
<p>i.e. in the CREATE TABLE for Branches:</p>
<pre><code>CREATE TABLE Branches
(
...
CorporationId int NOT NULL
CONSTRAINT FOREIGN KEY FK_Branches_Corporations REFERENCES Corporations(Id)
...
)
</code></pre>
|
Is there a way to access an iteration-counter in Java's for-each loop? <p>Is there a way in Java's for-each loop</p>
<pre><code>for(String s : stringArray) {
doSomethingWith(s);
}
</code></pre>
<p>to find out how often the loop has already been processed?</p>
<p>Aside from using using the old and well-known <code>for(int i=0; i < boundary; i++)</code> - loop, is the construct</p>
<pre><code>int i = 0;
for(String s : stringArray) {
doSomethingWith(s);
i++;
}
</code></pre>
<p>the only way to have such a counter available in a for-each loop?</p>
| <p>No, but you can provide your own counter.</p>
<p>The reason for this is that the for-each loop internally does not <em>have</em> a counter; it is based on the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Iterable.html" rel="nofollow">Iterable</a> interface, i.e. it uses an <code>Iterator</code> to loop through the "collection" - which may not be a collection at all, and may in fact be something not at all based on indexes (such as a linked list).</p>
|
Array functions in jQuery <p>I am using jQuery in my web application. I want to use arrays, but I am not able to find out functions for arrays (add, remove or append elements in array) in jQuery. Is there any link related to jQuery array functions which will explain the jQuery array functions?</p>
| <p>Have a look at
<a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array">https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array</a>
for documentation on JavaScript Arrays.<br />
jQuery is a library which adds some magic to JavaScript which is a capable and featurefull scripting language. The libraries just fill in the gaps - get to know the core!</p>
|
Primitive type 'short' - casting in Java <p>I have a question about the primitive type <code>short</code> in Java. I am using JDK 1.6. </p>
<p>If I have the following: </p>
<pre><code>short a = 2;
short b = 3;
short c = a + b;
</code></pre>
<p>the compiler does not want to compile - it says that it "cannot convert from int to short" and suggests that I make a cast to <code>short</code>, so this:</p>
<pre><code>short c = (short) (a + b);
</code></pre>
<p>really works. But my question is why do I need to cast? The values of a and b are in the range of <code>short</code> - the range of short values is {-32,768, 32767}.
I also need to cast when I want to perform the operations -, *, / (I haven't checked for others).</p>
<p>If I do the same for primitive type <code>int</code>, I do not need to cast aa+bb to <code>int</code>. The following works fine:</p>
<pre><code>int aa = 2;
int bb = 3;
int cc = aa +bb;
</code></pre>
<p>I discovered this while designing a class where I needed to add two variables of type short, and the compiler wanted me to make a cast. If I do this with two variables of type <code>int</code>, I don't need to cast. </p>
<p>Thank you very much in advance.</p>
<p>A small remark: the same thing also happens with the primitive type <code>byte</code>. So, this works:</p>
<pre><code>byte a = 2;
byte b = 3;
byte c = (byte) (a + b);
</code></pre>
<p>but this not:</p>
<pre><code>byte a = 2;
byte b = 3;
byte c = a + b;
</code></pre>
<p>For <code>long</code>, <code>float</code>, <code>double</code>, and <code>int</code>, there is no need to cast. Only for <code>short</code> and <code>byte</code> values. </p>
| <p>As explained in <a href="http://msdn.microsoft.com/en-us/library/ybs77ex4(VS.71).aspx">short C#</a> (but also for other language compilers as well, like Java)</p>
<p>There is a predefined implicit conversion from short to int, long, float, double, or decimal.</p>
<p>You cannot implicitly convert nonliteral numeric types of larger storage size to short (see Integral Types Table for the storage sizes of integral types). Consider, for example, the following two short variables x and y:</p>
<pre><code>short x = 5, y = 12;
</code></pre>
<p>The following assignment statement will produce a compilation error, <strong>because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.</strong></p>
<pre><code>short z = x + y; // Error: no conversion from int to short
</code></pre>
<p>To fix this problem, use a cast:</p>
<pre><code>short z = (short)(x + y); // OK: explicit conversion
</code></pre>
<p>It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:</p>
<pre><code>int m = x + y;
long n = x + y;
</code></pre>
<p><hr /></p>
<p>A good follow-up question is:</p>
<p>"why arithmetic expression on the right-hand side of the assignment operator evaluates to int by default" ?</p>
<p>A first answer can be found in:</p>
<p><a href="http://www.jblech.de/Glesner-Blech-COCV-2003.pdf">Classifying and Formally Verifying Integer Constant Folding</a></p>
<blockquote>
<p>The <strong>Java language specification defines exactly how integer numbers are represented and how integer arithmetic expressions are to be evaluated</strong>. This is an important property of Java as this programming language has been designed to be used in distributed applications on the Internet. <strong>A Java program is required to produce the same result independently of the target machine executing it</strong>. </p>
<p>In contrast, C (and the majority of widely-used imperative and
object-oriented programming languages) is more sloppy and leaves many important characteristics open. The intention behind this inaccurate language
specification is clear. The same C programs are supposed to run on a 16-bit,
32-bit, or even 64-bit architecture by instantiating the integer arithmetics of
the source programs with the arithmetic operations built-in in the target processor. This leads to much more eï¬cient code because it can use the available
machine operations directly. As long as the integer computations deal only
with numbers being âsufficiently smallâ, no inconsistencies will arise. </p>
<p>In this sense, the C integer arithmetic is a placeholder which is not defined exactly
by the programming language specification but is only completely instantiated by determining the target machine. </p>
<p>Java precisely defines how integers are represented and how integer arithmetic is to be computed. </p>
</blockquote>
<pre><code> Java Integers
--------------------------
Signed | Unsigned
--------------------------
long (64-bit) |
int (32-bit) |
short (16-bit) | char (16-bit)
byte (8-bit) |
</code></pre>
<blockquote>
<p>Char is the only unsigned integer type. Its values represent Unicode characters, from <code>\u0000</code> to <code>\uffff</code>, i.e. from 0 to 2<sup>16</sup>â1. </p>
<p><strong>If an integer operator has an operand of type long, then the other operand is also converted to type long. Otherwise the operation is performed on operands of type int, if necessary shorter operands are converted into int</strong>. The conversion rules are exactly specified.</p>
</blockquote>
<p>[From Electronic Notes in Theoretical Computer Science 82 No. 2 (2003)<br />
Blesner-Blech-COCV 2003: <a href="http://pes.cs.tu-berlin.de/pes/index.php.html">Sabine GLESNER</a>, Jan Olaf BLECH,<br />
Fakultät für Informatik,<br />
Universität Karlsruhe<br />
Karlsruhe, Germany]</p>
|
What's the idiomatic Python equivalent to Django's 'regroup' template tag? <p><a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup">http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup</a></p>
<p>I can think of a few ways of doing it with loops but I'd particularly like to know if there is a neat one-liner.</p>
| <p>Combine <a href="http://docs.python.org/library/itertools.html#itertools.groupby"><code>itertools.groupby</code></a> with <a href="http://docs.python.org/library/operator.html#operator.itemgetter"><code>operator.itemgetter</code></a> to get a pretty nice solution:</p>
<pre><code>from operator import itemgetter
from itertools import groupby
key = itemgetter('gender')
iter = groupby(sorted(people, key=key), key=key)
for gender, people in iter:
print '===', gender, '==='
for person in people:
print person
</code></pre>
|
Create temp dir that is globally known and that gets automagically removed (C++)? <p>In C++, I have a few functions that need to write to a temp directory. Ideally, only one temp directory gets created that they all write to (to minimize I/O overhead). That directory should be automagically removed when the program exits.</p>
<p>However, I don't want to deal with creation and removal of the temp directory in the main function because I think only the functions that actually use the directory should be responsible for its creation and removal. And the main function doesn't necessarily know that a temp directory is used at all. </p>
<p>Here is what I tried (see code below): A getTempDir() function that can be globally called from anywhere creates a directory on its first call only and returns the dir name on every call. On the first call it also creates a static boost::shared_ptr to a little DirRemover object whose destructor will remove the directory. That destructor gets called automatically when the program exits. </p>
<p>The problem is that it won't call the FileRemover destructor on an unsuccessful exit of the program, or a kill etc. Are there better solutions? </p>
<p>Here is the code:</p>
<pre><code>std::string getTempDir(){
static bool alreadyThere = false;
static std::string name = "";
if(!alreadyThere){
// create dir with
// popen("mktemp -p /tmp","r"))
// and store its name in 'name'
removeAtEnd(name);
alreadyThere = true;
}
return name;
}
void removeAtEnd(const std::string& name){
static boost::shared_ptr<DirRemover> remover(new DirRemover(name));
}
struct DirRemover {
std::string name;
DirRemover(const std::string& n) : name(n){}
~DirRemover(){
// remove 'name' dir with popen("rm -r ...")
}
};
</code></pre>
| <p>Using popen() to execute things like "rm -r" or "mktemp -p /tmp" is a recipe for disaster. In my opinion it is extremely bad style.</p>
<p>UNIX Specific: If you want temporary files to disappear even if your application terminates abnormally then the best way to go is to immediately unlink temp files after opening them. Your app will still have a file handle to them so you can work with the file. When your application terminates and the file descriptor is closed then the file will be automatically removed from the file system.</p>
<p>Btw, I see you are using Boost. Are you sure Boost.Filesystem does not have the above functionality?</p>
|
What to use? Digital signature? <p>Sorry I couldn't find the best heading for this question. Following is my requirement.</p>
<p>I a working on a project which deals which large amount of money transactions to different account. The system automatically transfers money to accounts of A,B, C etc etc,, But before this is done Some one from A,B or C should approve(electronically) the amount to be transferred.</p>
<p>What do you think is the best way of doing it? I want the system to send a file (PDF of something) which is digitally signed (?) and the authorised person from A,B and C should check and confirm that the amount is correct.</p>
<p>Since the amount is high I must make sure the file sent out by the system is not tampered and at the same time I also want to make sure the file (reply) sent by A,B or C is also not tampered . What is the best way to achieve it? Any ideas?</p>
| <p>Digital Signatures is what you are looking for. Adobe PDF (since you mentioned pdf) allows you to sign the pdf in the free Adobe Reader version and verification is also done automatically, as soon as you open the pdf document.</p>
<p>The difference between DigSig and (H)MACs as posted by Noldorin is, that MACs use symmetric encryption, where you require a secure channel to exchange the key, whereas in a <a href="http://en.wikipedia.org/wiki/Public_key_infrastructure">PKI</a> environment that secure channel is not required.</p>
<p>It depends how you want to distribute your keys.</p>
|
Friendly Form Validations (Rails) <p>I checked out <a href="http://stackoverflow.com/questions/361161/rails-form-validation">both </a> of <a href="http://stackoverflow.com/questions/423160/rails-form-validation-conditional-bypass">these</a> previously-asked questions, and they're a help but not a full solution for my case.</p>
<p>Essentially I need to validate a user-submitted URL from a form. I've started by validating that it begins with http://, https://, or ftp:// :</p>
<pre><code>class Link < ActiveRecord::Base
validates_format_of [:link1, :link2, :link3,
:link4, :link5], :with => /^(http|https|ftp):\/\/.*/
end
</code></pre>
<p>That works great for what it's doing, but I need to go these two steps further:</p>
<ol>
<li>Users should be allowed to leave the form fields blank if needed, and</li>
<li>If the URL provided by the user does not already start with http:// (say they enter google.com, for example), it should pass the validation but add the http:// prefix while being processed.</li>
</ol>
<p>I'm having a hard time determining how to make this work cleanly and efficiently.</p>
| <p>FYI, you don't have to pass an array to <code>validates_format_of</code>. Ruby will do arrays automagically (Rails parses the output of <code>*args</code>).</p>
<p>So, for your question, I'd go for something like this:</p>
<pre><code>class Link < ActiveRecord::Base
validate :proper_link_format
private
def proper_link_format
[:link1, :link2, :link3, :link4, :link5].each do |attribute|
case self[attribute]
when nil, "", /^(http|https|ftp):\/\//
# Allow nil/blank. If it starts with http/https/ftp, pass it through also.
break
else
# Append http
self[attribute] = "http://#{self[attribute]}"
end
end
end
end
</code></pre>
|
Something like overloading in PHP? <p>I'd like to accomplish something like this: Call a method, say "turn", and then have "turn" applied differently to different data types, e.g., calling "turn" with a "screwdriver" object/param uses the "turnScrewdriver" method, calling "turn" with a "steeringWheel" object/param uses the "turnSteeringWheel" method, etc. -- different things are being done, but they're both called "turn."</p>
<p>I'd like to implement this so that the calling code needn't worry about the type(s) involved. In this example, "turn" should suffice to "turn" a "screwdriver", "steeringWheel", or whatever might need to be "turned."</p>
<p>In C++ I'd do this with overloading -- and C++ would sort things out based on the datatype/signature -- but this doesn't work in PHP.</p>
<p>Any suggestions as to where should I begin? A switch statement is obvious, but I'm thinking there must be a (more elegant) OO solution. No?</p>
<p>TIA</p>
| <p>I read davethegr8's solution but it seems one could do the same thing with stronger typing:</p>
<pre><code><?php
interface Turnable
{
public function turn();
}
class Screwdriver implements Turnable
{
public function turn() {
print "to turning sir!\n";
}
}
class SteeringWheel implements Turnable
{
public function turn() {
print "to everything, turn, turn turn!\n";
}
}
function turn(Turnable $object) {
$object->turn();
}
$driver = new Screwdriver();
turn($driver);
$wheel = new SteeringWheel();
turn($wheel);
$obj = new Object(); // any object that does not implement Turnable
turn($object); // ERROR!
</code></pre>
<p>PHP does permit you to use a type hint for the parameter, and the type hint can be an interface name instead of a class name. So you can be sure that if the <code>$object</code> implements the <code>Turnable</code> interface, then it <em>must</em> have the <code>turn()</code> method. Each class that implements <code>Turnable</code> can do its own thing to accomplish turning.</p>
|
What's a reasonable version of Windows to support for a new .Net application? <p>If I develop a .Net application that's going to run on WinXP and Vista, as well as on a modern Mac or Linux under Mono, what are older versions of Windows where I will have to start thinking carefully if I want to support them? Does Windows 2000 for example run .Net and is it capable of any version of the runtime? Usually, older systems mean older hardware too, which might also be a problem, I guess.</p>
<p><hr /></p>
<p><strong>Edit</strong>: reading Joe's answer made me rephrase my question in the title. If Win 2k already has a lower common denominator with XP than Linux, that pretty much settles it for me. However, I'm still open to more info and will upvote additional helpful facts.</p>
| <p>Since <a href="http://www.go-mono.com/mono-downloads/download.html" rel="nofollow">Mono</a> runs on all your target platforms (Win 2000+, Linux and Mac OSX) you can develop your app with that instead of Microsoft .NET. Doing that will also reduce the pain of getting your app running on non-Windows platforms later (since as long as you don't use any platform-specific libraries it should Just Work).</p>
<p>Having said that, if you are going to develop something that can be compiled under Mono it's worth understanding its limitations.</p>
<p>For example, they have C# 2.0 fully implemented, but only partial support for C# 3.0.</p>
<p>Mono is also not .NET for Linux, it's an implementation of the CLR that is cross platform -- some libraries may not be implemented (although the core ones are).</p>
<p>Check out <a href="http://en.wikipedia.org/wiki/Mono_(software)" rel="nofollow">the wikipedia page</a> and <a href="http://mono-project.com/Main_Page" rel="nofollow">their home page</a>.</p>
|
Why are there many JRE implementations? <p>I was wondering..There is Sun's JRE, IBM's JRE, BEA's JRE, Oracle's JRE and some more less know JREs in the market.
Why is there so many JRE implementations? Does the fact that Sun opened the Java platforms mean that there will be one open JRE / JDK? Or are we going towards what happened with Linux and its many distributions ? </p>
| <p>Why is there more than one C compiler? Why is there more than one implementation of Ruby? Different implementations allow different teams to explore different possibilities for optimisation etc. For instance, I'm pretty sure that at one point the IBM JRE was much faster than the Sun one for floating point. Other implementations may have special features for pre-compilation etc.</p>
<p>As for whether OpenJDK will reduce the variety available - it's hard to say. I'm pleased that the variety exists though - competition like this helps everyone.</p>
|
Getting user's group name in Windows <p>I'm using a Java program that has to gather info that can be derived from the user's group.</p>
<p>How can you get a user's group name from windows? Is it found in a file or is there some method/API for getting it?</p>
<p>Please help.</p>
<p>Thanks</p>
| <p>This forum post <a href="http://forums.sun.com/thread.jspa?threadID=581444&messageID=3313188" rel="nofollow">Naming and Directory (JNDI) - JNDI, Active Directory and Group Memberships</a> should put you on the right track.</p>
|
Clear file cache to repeat performance testing <p>What tools or techniques can I use to remove cached file contents to prevent my performance results from being skewed? I believe I need to either completely clear, or selectively remove cached information about file and directory contents.</p>
<p>The application that I'm developing is a specialised compression utility, and is expected to do a lot of work reading and writing files that the operating system hasn't touched recently, and whose disk blocks are unlikely to be cached.</p>
<p>I wish to remove the variability I see in IO time when I repeat the task of profiling different strategies for doing the file processing work.</p>
<p>I'm primarily interested in solutions for Windows XP, as that is my main development machine, but I can also test using linux, and so am interested in answers for that environment too.</p>
<p>I tried SysInternals <a href="http://technet.microsoft.com/en-us/sysinternals/bb897561.aspx">CacheSet</a>, but clicking "Clear" doesn't result in a measurable increase (restoration to timing after a cold-boot) in the time to re-read files I've just read a few times.</p>
| <p>Use SysInternal's <a href="http://technet.microsoft.com/en-us/sysinternals/ff700229.aspx">RAMMap app</a>.</p>
<p><img src="http://i.stack.imgur.com/EuOmF.png" alt="rammap empty standby"></p>
<p>The Empty / Empty Standby List menu option will clear the Windows file cache.</p>
|
Efficient join with a "correlated" subquery <p>Given three tables Dates(date aDate, doUse boolean), Days(rangeId int, day int, qty int) and Range(rangeId int, startDate date) in Oracle</p>
<p>I want to join these so that Range is joined with Dates from aDate = startDate where doUse = 1 whith each day in Days.</p>
<p>Given a single range it might be done something like this</p>
<pre><code>SELECT rangeId, aDate, CASE WHEN doUse = 1 THEN qty ELSE 0 END AS qty
FROM (
SELECT aDate, doUse, SUM(doUse) OVER (ORDER BY aDate) day
FROM Dates
WHERE aDate >= :startDAte
) INNER JOIN (
SELECT rangeId, day,qty
FROM Days
WHERE rangeId = :rangeId
) USING (day)
ORDER BY day ASC
</code></pre>
<p>What I want to do is make query for all ranges in Range, not just one.</p>
<p>The problem is that the join value "day" is dependent on the range startDate to be calculated, wich gives me some trouble in formulating a query.</p>
<p>Keep in mind that the Dates table is pretty huge so I would like to avoid calculating the day value from the first date in the table, while each Range Days shouldn't be more than a 100 days or so.</p>
<p>Edit: Sample data</p>
<pre><code>Dates Days
aDate doUse rangeId day qty
2008-01-01 1 1 1 1
2008-01-02 1 1 2 10
2008-01-03 0 1 3 8
2008-01-04 1 2 1 2
2008-01-05 1 2 2 5
Ranges
rangeId startDate
1 2008-01-02
2 2008-01-03
Result
rangeId aDate qty
1 2008-01-02 1
1 2008-01-03 0
1 2008-01-04 10
1 2008-01-05 8
2 2008-01-03 0
2 2008-01-04 2
2 2008-01-05 5
</code></pre>
| <p>Try this:</p>
<pre><code>SELECT rt.rangeId, aDate, CASE WHEN doUse = 1 THEN qty ELSE 0 END AS qty
FROM (
SELECT *
FROM (
SELECT r.*, t.*, SUM(doUse) OVER (PARTITION BY rangeId ORDER BY aDate) AS span
FROM (
SELECT r.rangeId, startDate, MAX(day) AS dm
FROM Range r, Days d
WHERE d.rangeid = r.rangeid
GROUP BY
r.rangeId, startDate
) r, Dates t
WHERE t.adate >= startDate
ORDER BY
rangeId, t.adate
)
WHERE
span <= dm
) rt, Days d
WHERE d.rangeId = rt.rangeID
AND d.day = GREATEST(rt.span, 1)
</code></pre>
<p>P. S. It seems to me that the only point to keep all these <code>Dates</code> in the database is to get a continuous calendar with holidays marked.</p>
<p>You may generate a calendar of arbitrary length in Oracle using following construction:</p>
<pre><code>SELECT :startDate + ROWNUM
FROM dual
CONNECT BY
1 = 1
WHERE rownum < :length
</code></pre>
<p>and keep only holidays in <code>Dates</code>. A simple join will show you which <code>Dates</code> are holidays and which are not.</p>
|
Most bandwidth efficient unidirectional synchronise (server to multiple clients) <p><strong>What is the most bandwidth efficient way to <em>unidirectionally</em> synchronise a list of data from one server to many clients?</strong></p>
<p>I have sizeable chunk of data (perhaps 20,000, 50-byte records) which I need to periodically synchronise to a series of clients over the Internet (perhaps 10,000 clients). Records may added, removed or updated <em>only at the server end</em>.</p>
| <p>Something similar to bittorrent? Or even using bittorrent. Or maybe invent a wrapper around bittorrent.</p>
<p>(Assuming you pay for bandwidth on your server and not the others ...)</p>
|
Recursion or iteration? <p>I love recursion. I think it simplifies things a lot. Another may disagree; I think it also makes the code a lot easier to read. However, I've noticed that recursion is not used as much in languages such C# as they are in LISP (which by the way is my favorite language because of the recursion). </p>
<p>Does anybody know if there is any good reasons not use recursion in the languages such as C#? Is it more expensive than iteration?</p>
| <blockquote>
<p>Are they more expensive than
iterations?</p>
</blockquote>
<p>Yes they are. Many Lisp variants support the idea of a "tail-call optimisation" which allows many uses of a recursive function call to be converted into an iterative one (this is simplifying a bit). If tail-call is not supported, then a recursive function call will use progressively more memory on the stack.</p>
|
Copy MySQL structure across servers via PHP <p>I'm in need of help - I've got two mysql databases on different servers with a web host, and I need to copy a Joomla installation from one to the other. The problem I have is that the only way I can access the data is via php, as direct odbc connections to the database are locked down.</p>
<p>I don't mind doing it table by table, but have no idea of how to code the script :(</p>
<p>My knowledge of php is limited (hence using Joomla), so if anyone has a couple of minutes to point me in the right direction, it'd be appreciated.</p>
<p>Thanks in advance,</p>
<p>PG</p>
| <p>Can you install <a href="http://phpmyadmin.net/" rel="nofollow">phpMyAdmin</a>? If so, it has a database export/import functionality that would likely be perfect for this.</p>
|
How to select even or odd elements based on class name <p>if you create html layout like so</p>
<pre><code><ul>
<li class='a'></li>
<li class='b'></li>
<li class='a'></li>
<li class='b'></li>
<li class='a'></li>
<li class='b'></li>
<li class='a'></li>
<li class='b'></li>
</ul>
</code></pre>
<p>and try to select odd elements with 'a' class like so $$('.a:odd') you will get empty array, and if you do $$('.a:even') you will get all four li elements with 'a' class.. It really strange.. But im new to mootools, maybe im doing something wrong.. </p>
<p>So my question is how to select first and third li elements with a class.
I know that i can do it with function like this</p>
<p>$$('.a').filter(function(item, index) { return index%2; }</p>
<p>but its too complicated for such small task as selecting odd or even elements..</p>
| <p>The problem is that :odd and :even (and their CSS cousins :nth-child(odd) and :nth-child(even)) refer to the order in which the elements appear as children of their parent, not as children with that particular selector.</p>
<p>This worked for me (Prototype, but it looks like MooTools has similar syntax):</p>
<pre><code>var odd = $$('.a').filter(function(item, index) {
return index % 2 == 0;
});
var even = $$('.a').filter(function(item, index) {
return index % 2 == 1;
});
</code></pre>
<p>Edit: it seems you already covered that in the question, boo on me for answering before reading fully.</p>
|
ASP Error and IIS 7.0 <p>In IIS 6 ASP errors were displayed with the line number and a description of the problem. For example, </p>
<pre><code>{call dbo.spGetCommunityInfo(xx)}
Microsoft SQL Native Client error '80020005'
Invalid character value for cast specification
/communitydetail.asp, line 42
</code></pre>
<p>IIS 7 changes the way ASP errors are handled and displays something a lot less helpful. For example,</p>
<pre><code>Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request
</code></pre>
<p>Does anyone know what configuration changes are required to get the behavior of IIS 6 in IIS 7?</p>
| <p>You can use AppCmd to turn on ScriptErrorSentToBrowser (it's false in IIS7 defaults, it was true in IIS6). AppCmd live in %SystemRoot%\system32\inetsrv and you need to run it as admin:</p>
<blockquote>
<p>appcmd.exe set config
-section:system.webServer/asp -ScriptErrorSentToBrowser:true</p>
</blockquote>
|
Merging C Callergraphs with Doxygen or determining union of all calls <p>I have a collection of legacy C code which I'm refactoring to split the C computational code from the GUI. This is complicated by the heavily recursive mathematical core code being K&R style declarations. I've already abandoned an attempt to convert these to ANSI declarations due to nested use of function parameters (just couldn't get those last 4 compiler errors to go).</p>
<p>I need to move some files into a pure DLL and determine the minimal interface to make public, which is going to require wrapper functions writing to publish a typed interface.</p>
<p>I've marked up the key source files with the Doxygen @callergraph markup so informative graphs are generated for individual functions. What I'd like to do beyond that is amalgamate these graphs so I can determine the narrowest boundary of functions exposed to the outside world.</p>
<p>The original header files are no use - they expose everything as untyped C functions.</p>
<p>There are hundreds of functions so simple inspection of the generated callergraphs is painful.</p>
<p>I'm considering writing some kind of DOT merge tool - setting DOT_CLEANUP=NO makes Doxygen leave the intermediate DOT files there rather then just retaining the png files they generated.</p>
<p>I'm not obsessed by this being a graphical solution - I'd be quite happy if someone could suggest an alternative analysis tool (free or relatively cheap) or technique using Doxygen's XML output to achieve the same goal.</p>
<p>A callergraph amalgamated at the file level does have a certain appeal for client documentation rather than a plain list :-)</p>
| <p>In your Doxyfile, set</p>
<pre><code>GENERATE_XML = YES
</code></pre>
<p>and then you can find your call graph in the XML files. For each function marked with the callergraph, you'll find <code><referencedby></code> elements in the output that you can use. Here's a sample from one of my C files:</p>
<pre><code> <memberdef kind="function" id="spfs_8c_1a3"
prot="public" static="yes" const="no" explicit="no"
inline="no" virt="non-virtual">
<type>svn_error_t *</type>
<definition>svn_error_t * init_apr</definition>
<argsstring>(apr_pool_t **ppool, int *argc, char const *const **argv)</argsstring>
<name>init_apr</name>
<!-- param and description elements clipped for brevity ... -->
<location file="src/spfs.c" line="26" bodystart="101" bodyend="120"/>
<referencedby refid="spfs_8c_1a13" compoundref="spfs_8c"
startline="45" endline="94">main</referencedby>
</memberdef>
</code></pre>
<p>So for every memberdef/referencedby pair, you have a caller-callee relationship, which you can grab via XSLT:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:apply-templates select="//memberdef[@kind eq 'function']"/>
</xsl:template>
<xsl:template match="memberdef">
<xsl:variable name="function-name"
select="concat(definition, argsstring)"/>
<xsl:for-each select="referencedby">
<xsl:value-of select="concat(./text(), ' calls ', $function-name, '&#xA;')"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>Which gives you a line per caller-callee like this:</p>
<pre><code>main calls svn_error_t * init_apr(apr_pool_t **ppool, int *argc, char const *const **argv)
</code></pre>
<p>You'll want to tweak that XSLT and then partition that directed graph in the way that cuts across the fewest edges. Woo hoo, an NP-complete problem! Luckily, there are lots of papers on the subject, some are here: <a href="http://www.sandia.gov/~bahendr/partitioning.html" rel="nofollow">http://www.sandia.gov/~bahendr/partitioning.html</a></p>
|
How do I get Visual Web Developer to use IIS, and not ASP.NET development server? <p>I want to make sure my local is matching the production environment closely and that means running IIS and not the ASP.NET development server that comes with Visual Web Developer express edition. What is the best way to do this?</p>
| <p>In Visual Studio you right-click the project, select Properties then Web and change it to use Local IIS. It seems the process is similar for VWD, but there there is a <a href="http://blogs.msdn.com/webdevelopertips/archive/2008/11/04/tip-20-did-you-know-how-to-change-wap-to-use-an-iis-web-server.aspx" rel="nofollow">Properties node you open instead</a>. I don't have VWD installed right now so can't check to see if this method is indeed accurate but the article is recent so I assume that it is.</p>
|
.NET MVC: How to create form from controller? <p>In .NET 3.5 winforms, I've created an MVC. I'd like to take the controller part and put it into a separate assembly, so that it has no knowledge of the view. My app uses five forms in its view. The controller takes care of initializing the forms at different times, which means the controller has a reference to the view (something I'd rather not). This means the controller can't be separated since it needs to know the form types being created, which probably means it isn't a true controller. </p>
| <p>I use an IOC Container to resolve the view and inject the controller instance via the form constructor, like so.</p>
<pre><code>public class MainWindowController : WindowController<IMainWindowView>
{
}
public class WindowController<TView> where TView : IView
{
public WindowController( IViewFactory factory ) {}
public void ShowWindow() {}
public void CloseWindow() {}
}
public interface IViewFactory
{
IView CreateWithController( IWindowController controller ) {}
}
public interface IView {}
public interface IMainWindowView : IView {}
public class MainForm : Form, IMainWindowView
{
public MainForm( IWindowController windowController )
{
}
}
</code></pre>
<p>My Window Controller class has a dependency on a view factory, which will create an instance of the registered View (using the container).</p>
<p>The ViewFactory uses the IOC container to create transient views and injects the controller instance into the constructor.</p>
<p>It also has methods like ShowWindow and CloseWindow that will show and hide the form. This allows me to unit test my controllers with mock views. It also removes any dependency on Windows Forms from my controller and model code, allowing me to replace any views with WPF views in the future.</p>
<p>I set it up that my main application logic, the view interfaces, the controllers and models live inside one main assembly and the other assembly only contains the Windows Forms forms and controls. </p>
|
Find path where SQL Server is installed? <p>How can I get the path where SQL Server 2005 is installed in a system, through SQL command?</p>
| <p><code>select filename from master.sys.sysfiles where name = 'master'</code></p>
|
ASP.NET Forms auth - gettings user data <p>I'm using forms authentication on a very small ASP.NET web app (Web Forms) in which I want to store additional info about the user in a separate database table.</p>
<p>This is then linked back to the <code>aspnet_User</code> table and I was figuring the best column to link to is the <code>UserId</code> column. Problem is I can't work out how to get this piece of data when the user is logged in. Is it even possible?</p>
<p>Also, how do I get the email address?</p>
<p><hr /></p>
<p>Before someone points it out, I am aware of the ProfileProvider but the details stored need to be re-submitted each year (it's a registration application for a sporting club) and all previous data stored. So the ProfileProvider isn't really applicable (unless I'm wrong and it can be used to have it stored <em>historically</em>?). </p>
| <p>here's how you can get the userid</p>
<pre><code>MembershipUser myObject = Membership.GetUser();
string UserID = myObject.ProviderUserKey.ToString();
string Email = myObject.Email;
</code></pre>
|
WPF translation transform <p>How can i get the new bounds after applying a translation transform to a WPF mesh geometry 3D?</p>
| <p>What I found:</p>
<p>Rect3D newRec3D = modelVisual3D.Transform.TransformBounds(modelVisual3D.Geometry.Bounds);</p>
<p>If you have better way, please post it.</p>
|
trim is not part of the standard c/c++ library? <p>Is it me or are there no standard trim functions in the c or c++ library? is there any single function that acts as a trim? If not can anyone tell me Why trim is not part of the standard library? (i know trim is in boost)</p>
<p>My trim code is</p>
<pre><code>std::string trim(const std::string &str)
{
size_t s = str.find_first_not_of(" \n\r\t");
size_t e = str.find_last_not_of (" \n\r\t");
if(( string::npos == s) || ( string::npos == e))
return "";
else
return str.substr(s, e-s+1);
}
</code></pre>
<p>test: cout << trim(" \n\r\r\n \r\n text here\nwith return \n\r\r\n \r\n ");
-edit-
i mostly wanted to know why it wasnt in the standard library, BobbyShaftoe answer is great. <a href="http://stackoverflow.com/questions/479080/trim-is-not-part-of-the-standard-c-c-library#479091">http://stackoverflow.com/questions/479080/trim-is-not-part-of-the-standard-c-c-library#479091</a></p>
| <p>No, you have to write it yourself or use some other library like Boost and so forth.</p>
<p>In C++, you could do:</p>
<pre><code>#include <string>
const std::string whiteSpaces( " \f\n\r\t\v" );
void trimRight( std::string& str,
const std::string& trimChars = whiteSpaces )
{
std::string::size_type pos = str.find_last_not_of( trimChars );
str.erase( pos + 1 );
}
void trimLeft( std::string& str,
const std::string& trimChars = whiteSpaces )
{
std::string::size_type pos = str.find_first_not_of( trimChars );
str.erase( 0, pos );
}
void trim( std::string& str, const std::string& trimChars = whiteSpaces )
{
trimRight( str, trimChars );
trimLeft( str, trimChars );
}
</code></pre>
|
Who has the best metaphor for WPF dependency properties? <p>I'm reading WPF Recipes in C# 2008:</p>
<p><a href="http://www.apress.com/book/view/9781430210849" rel="nofollow">http://www.apress.com/book/view/9781430210849</a></p>
<p>and starting on the third recipe they asssume you know how dependency properties work. </p>
<p>So after a little googling, I understand in general that these are properties of an object which when placed inside another object "adapts to the context" to the host object. I also "learned" that "you never really know what the value of these properties are since they depend on their context."</p>
<p>But still much of what is being described in the book leaves me with no idea how I could use these when building applications.</p>
<p>Who has a good metaphor or example of dependency properties for people starting out with them and wanting to know when and how they would use them?</p>
| <p>Dependency properties are just like normal properties except they have some special "hooks" that WPF uses.</p>
<p>One special thing is that sometimes if you don't set a property value it will receive its value from the control it is placed in (so if you set the font for a button the text block inside the button will use this font unless you specified a different font for the text block), I assume this is the source of all the "never know the value" nonsense.</p>
<p>If you are writing a WPF control you probably should use dependency properties because you can specify if changes should automatically cause the control to re-render itself (and more) and you can use them for data binding.</p>
<p>If you are writing a class derived from Freezable (directly or indirectly) using only dependency properties will save you some work.</p>
<p>If you are writing a class that is not WPF specific then there is probably no reason to use dependency properties. </p>
|
Nested accordion menu in jQuery <p>I have a menu implemented using a set of nested accordions, <code>1</code> and <code>2</code>, each with elements, <code>a</code> and <code>b</code>.</p>
<p>I would like to implement the following logic:</p>
<ul>
<li><p>When I click <code>1a</code>, I will get the data of <code>1a</code> and two submenu <code>2a</code>,<code>2b</code></p></li>
<li><p>When I click <code>2a</code>, <code>2b</code> I will get the data of each, respectively.</p></li>
</ul>
<p><strong>The problem</strong></p>
<p>Desired result:</p>
<ul>
<li>I only want to display the <code>nth-most</code> child element for the last click, collapsing all others.</li>
<li>Upon initialization, only <code>1a</code> and <code>1b</code> should be visible.</li>
</ul>
<p>Current result:</p>
<ul>
<li>Clicking on <code>1b</code>, then on <code>2b</code>, <code>1b</code> is still fully visible.</li>
</ul>
<h3>JavaScript code</h3>
<pre><code>$(document).ready(function() {
$("#acc1").accordion({
active:".ui-accordion-left",
alwaysOpen: false,
autoheight: false,
header: 'a.acc1',
clearStyle: true
});
$("#acc2").accordion({
alwaysOpen: false,
autoheight: false,
header: 'a.acc2',
clearStyle: true
});
});
</code></pre>
<p>HTML:</p>
<pre><code><ul id="acc1" class="ui-accordion-container">
<li>
<div class="ui-accordion-left"></div>
<a class="ui-accordion-link acc1">1a
<span class="ui-accordion-right"></span>
</a>
<div>
data of 1a<br/>
data of 1a<br/>
data of 1a<br/>
</div>
<div>
<ul class="ui-accordion-container" id="acc2">
<li>
<div class="ui-accordion-left"></div>
<a class="ui-accordion-link acc2">2a
<span class="ui-accordion-right"></span>
</a>
<div>
data of 2a<br/>
data of 2a<br/>
data of 2a<br/>
</div>
</li>
<li>
<div class="ui-accordion-left"></div>
<a class="ui-accordion-link acc2">2b
<span class="ui-accordion-right"></span>
</a>
<div>
data of 2b<br/>
data of 2b<br/>
data of 2b<br/>
</div>
</li>
</ul>
</div>
</li>
<li>
<div class="ui-accordion-left"></div>
<a class="ui-accordion-link acc1">1b
<span class="ui-accordion-right"></span>
</a>
<div>
data of 1b<br />
data of 1b<br />
dta of 1b <br />
</div>
</li>
</ul>
</code></pre>
| <p>Just a few changes to the order of the elements in your HTML and you get the behavior you are looking for. At the start now only 1a and 1b are open. Similarly when you click on 1b now it will close 1a which will hide any open 2a/2b section as well.</p>
<pre><code> $(document).ready(function() {
$("#acc1").accordion({
active:".ui-accordion-left",
alwaysOpen: false,
autoheight: false,
header: 'a.acc1',
clearStyle: true
});
$("#acc2").accordion({
active:".ui-accordion-left",
alwaysOpen: false,
autoheight: false,
header: 'a.acc2',
clearStyle: true
});
});
<ul id="acc1" class="ui-accordion-container">
<li>
<div class="ui-accordion-left">
</div>
<a class="ui-accordion-link acc1">1a
<span class="ui-accordion-right"></span>
</a>
<div>
data of 1a<br/>
data of 1a<br/>
data of 1a<br/>
<ul class="ui-accordion-container" id="acc2">
<li>
<div class="ui-accordion-left">
</div>
<a class="ui-accordion-link acc2">2a
<span class="ui-accordion-right"></span>
</a>
<div>
data of 2a<br/>
data of 2a<br/>
data of 2a<br/>
</div>
</li>
<li>
<div class="ui-accordion-left">
</div>
<a class="ui-accordion-link acc2">2b
<span class="ui-accordion-right"></span></a>
<div>
data of 2b<br/>
data of 2b<br/>
data of 2b<br/>
</div>
</li>
</ul>
</div>
</li>
<li>
<div class="ui-accordion-left"></div>
<a class="ui-accordion-link acc1">1b
<span class="ui-accordion-right"></span></a>
<div>
data of 1b<br />
data of 1b<br />
dta of 1b <br />
</div>
</li>
</ul>
</body>
</code></pre>
|
detect os language from c# <p>Is there a way to detect the Language of the OS from within a c# class?</p>
| <p>Unfortunately, the previous answers are not 100% correct. </p>
<p>The <code>CurrentCulture</code> is the culture info of the running thread, and it is used for operations that need to know the current culture, but not do display anything. <code>CurrentUICulture</code> is used to format the display, such as correct display of the <code>DateTime</code>.
Because you might change the current thread <code>Culture</code> or <code>UICulture</code>, if you want to know what the OS <code>CultureInfo</code> actually is, use <code>CultureInfo.InstalledUICulture</code>.</p>
<p>Also, there is another question about this subject (more recent than this one) with a detailed answer:</p>
<p><a href="http://stackoverflow.com/questions/5710127/get-operating-system-language-in-c">Get operating system language in c#</a>.</p>
|
Microsoft.Reporting.* vs XML/XSLT <p>I would like to add reporting capabilities to a .NET application. My data source is just the data model of the application, i.e. a bunch of objects that may have been generated or loaded from anything (not necessarily from a database).</p>
<p>The initial plan was to generate a report data XML file from these objects, and then use XSLT to transform this into an XHTML report file. The report can then be shown in the application with a browser control.</p>
<p>However, I've noticed that there exist Microsoft.Reporting.* namespaces and from what I've tried, it seems that the classes and controls in there can also take care of my reporting. Would it be a good idea to use this instead? Will it save work compared to the XML/XSLT approach? What limitations (if any) of the Microsoft Reporting framework am I likely to run into? </p>
| <p>A couple of things to consider.</p>
<p>1) Reporting Services are part of Sql Server, so you may have an extra license issue if you go that route.</p>
<p>2) Reporting Services can serve up web pages, or be used in WinForms with full paging, sorting, sub reports, totals etc etc - that's really hard in XSL. It will also play nicely with printers.</p>
<p>3) Reporting services comes with a WYSIWYG editor to build reports. It's not perfect by any means, but a lot easier than hand crafting.</p>
<p>4) Using XSL to create XHTML can be real performance hit. XSL works on an entire XML Dom, and that maybe a big document if you're dealing with a multipage report. I'd expect Reporting Services to work a lot faster.</p>
<p>5) Reporting Services can leverage the whole of .Net, so you can get a lot of other functionality for free.</p>
<p>Taking all that on board, using Reporting Services will save you time, unless your reporting requirements are very simple. It is less fun though.</p>
|
One Cache for various Applications? <p>i have two applications - one is an asp.net website and the other is a windows service.</p>
<p>both applications are referencing my business layer (library project), which itself is referencing my data access layer (library project) that itself uses the enterprise library data application block to receive the data form a sql server 2005 database.</p>
<p>currently i use the System.Web.Caching.Cache object in my BL to cache some of my objects:</p>
<pre><code>public static System.Web.Caching.Cache Cache
{
get
{
if(cache == null)
{
if (System.Web.HttpContext.Current != null)
{
//asp.net
cache = System.Web.HttpContext.Current.Cache;
}
else
{
//windows service
cache = System.Web.HttpRuntime.Cache;
}
}
return cache;
}
}
</code></pre>
<p>as both applications are running on their own - they both are using a separate Cache object on their own - and this is the problem actually:</p>
<p>if i change a object in the asp.net website and save it to the DB. the object to this cache key is removed from the cache - the asp.net application's cache! that's fine.</p>
<p>but the windows service's Cache becomes stale!</p>
<p>vice-versa</p>
<p>is it possible that both applications are using the same Cache? One Cache for both applications?</p>
<p>the only option i have i think about is that i will have to use SqlDependency with </p>
<blockquote>
<p><a href="http://quickstarts.asp.net/QuickStartv20/aspnet/doc/caching/SQLInvalidation.aspx" rel="nofollow">Sql Server 2005 Notification-based Cache Invalidation</a></p>
</blockquote>
<p>is there any other way?</p>
<p>EDIT:
i just found <a href="http://www.codeplex.com/SharedCache" rel="nofollow">http://www.codeplex.com/SharedCache</a>. i will give it a try.
as because velocity will be in release candidate status until mid 2009.</p>
| <p>You should take a significant look at Microsoft's new free distributed cache "Velocity."</p>
<p>Here's a podcast I did on the subject:
<a href="http://www.hanselman.com/blog/HanselminutesPodcast116DistributedCachingWithMicrosoftsVelocity.aspx" rel="nofollow">http://www.hanselman.com/blog/HanselminutesPodcast116DistributedCachingWithMicrosoftsVelocity.aspx</a></p>
<p>Here's details on MSDN: <a href="http://msdn.microsoft.com/en-us/data/cc655792.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/data/cc655792.aspx</a></p>
<p>Here's downloads and samples: <a href="http://code.msdn.microsoft.com/velocity" rel="nofollow">http://code.msdn.microsoft.com/velocity</a></p>
|
Enum ToString with user friendly strings <p>My enum consists of the following values:</p>
<pre><code>private enum PublishStatusses{
NotCompleted,
Completed,
Error
};
</code></pre>
<p>I want to be able to output these values in a user friendly way though.<br>
I don't need to be able to go from string to value again. </p>
| <p>I do this with extension methods:</p>
<pre><code>public enum ErrorLevel
{
None,
Low,
High,
SoylentGreen
}
public static class ErrorLevelExtensions
{
public static string ToFriendlyString(this ErrorLevel me)
{
switch(me)
{
case ErrorLevel.None:
return "Everything is OK";
case ErrorLevel.Low:
return "SNAFU, if you know what I mean.";
case ErrorLevel.High:
return "Reaching TARFU levels";
case ErrorLevel.SoylentGreen:
return "ITS PEOPLE!!!!";
default:
return "Get your damn dirty hands off me you FILTHY APE!";
}
}
}
</code></pre>
|
Can I make more then one request on a curl connection? <p>In PHP (v5), is there a way to make multiple requests on an open curl connection?</p>
<p>I'm noticing that my big bottleneck is the timeout/teardown of the connection its self (i'm making lots of small data requests that finish quickly), so I would like to be able to do something like open</p>
<p>init curl connection,</p>
<p>set url/params, do request, get results
set url/params, do request, get results
</p>
<p>close curl</p>
<p>I just dont know if this is possible at all.</p>
| <p>Probably the <a href="http://php.net/manual/en/function.curl-multi-init.php" rel="nofollow"><code>curl_multi_*</code></a> functions are what you are looking for.</p>
|
How do you get resin to serve index.html by default if you navigate to a directory? (equivalent of DirectoryIndex in Apache) <p>Is it possible to configure <a href="http://caucho.com/resin/" rel="nofollow">Resin</a> to serve static files such that navigating to e.g. <a href="http://localhost:8888/foo/bar/" rel="nofollow">http://localhost:8888/foo/bar/</a> will serve the file foo/bar/index.html (without performing a redirect)? I can't find the answer in the Resin docs, though I might be looking in the wrong place.</p>
<p>The equivalent in Apache would be the DirectoryIndex directive.</p>
| <p>Maybe I don't get the question, but <a href="http://caucho.com/resin/doc/webapp-tags.xtp#welcome-file-list" rel="nofollow">welcome-file-list</a> seems to do just that?</p>
|
How do I get the actual value of a DependancyProperty? <p>I have a small UserControl and it needs to know the Background Brush of the control on which it's being rendered.</p>
<p>However, if I look in the Background property of the UserControl it comes back null. </p>
<p>If I call GetValue(UserControl.BackgroundProperty) it also returns null even though up the Visual tree it is definitely being set.</p>
<p>Seems like I must be missing something pretty obvious as it's can't be that hard to figure out the background colour of a control.</p>
| <p>It seems to me that your UserControl does not have a background color defined - null means transparent, which is why the parent control's background is visible at all.</p>
<p>It is still the background color of the parent control - the fact that your control does not have its own background color does not mean that it takes the color from the parent control. The "background" of your control will simply show whatever is behind your control.</p>
|
File / Folder monitoring <p>What is the best way to monitor disks against file activities. I mean that getting the full file name (c:\temp\abc.txt), action(created/deleted/modified/renamed), and also the user (user1) and process name (notepad.exe) causing the file (multiple delete) activities.</p>
<p>I heard about Some APIs and ShellNotifications but could not use them for the whole needs above.</p>
<p>Best regards.</p>
| <p>One of my favorite blogs answered this question (with full source and a demo application) quite a while ago. Checkout the <a href="http://delphi.about.com/od/kbwinshell/l/aa030403a.htm">Delphi About.com article here</a> which has a more in depth explanation. Code provided by Zarko Gajic at <a href="http://delphi.about.com">http://delphi.about.com</a></p>
<p><em>Wanna get notified when a file gets created, renamed or deleted on the system? Need to know the exact folder and file name? Let's start monitoring system shell changes!</em></p>
<pre><code>//TSHChangeNotify
unit SHChangeNotify;
{$IFNDEF VER80} {$IFNDEF VER90} {$IFNDEF VER93}
{$DEFINE Delphi3orHigher}
{$ENDIF} {$ENDIF} {$ENDIF}
//*************************************************************
//*************************************************************
// TSHChangeNotify component by Elliott Shevin shevine@aol.com
// vers. 3.0, October 2000
//
// See the README.TXT file for revision history.
//
//*
//* I owe this component to James Holderness, who described the
//* use of the undocumented Windows API calls it depends upon,
//* and Brad Martinez, who coded a similar function in Visual
//* Basic. I quote here from Brad's expression of gratitude to
//* James:
//* Interpretation of the shell's undocumented functions
//* SHChangeNotifyRegister (ordinal 2) and SHChangeNotifyDeregister
//* (ordinal 4) would not have been possible without the
//* assistance of James Holderness. For a complete (and probably
//* more accurate) overview of shell change notifcations,
//* please refer to James' "Shell Notifications" page at
//* http://www.geocities.com/SiliconValley/4942/
//*
//* This component will let you know when selected events
//* occur in the Windows shell, such as files and folders
//* being renamed, added, or deleted. (Moving an item yields
//* the same results as renaming it.) For the complete list
//* of events the component can trap, see Win32 Programmer's
//* reference description of the SHChangeNotify API call.
//*
//* Properties:
//* MessageNo: the Windows message number which will be used to signal
//* a trapped event. The default is WM_USER (1024); you may
//* set it to some other value if you're using WM_USER for
//* any other purpose.
//* TextCase: tcAsIs (default), tcLowercase, or tcUppercase, determines
//* whether and how the Path parameters passed to your event
//* handlers are case-converted.
//* HardDriveOnly: when set to True, the component monitors only local
//* hard drive partitions; when set to False, monitors the
//* entire file system.
//*
//* Methods:
//* Execute: Begin monitoring the selected shell events.
//* Stop: Stop monitoring.
//*
//* Events:
//* The component has an event corresponding to each event it can
//* trap, e.g. OnCreate, OnMediaInsert, etc.
//* Each event handler is passed either three or four parameters--
//* Sender=this component.
//* Flags=the value indentifying the event that triggered the handler,
//* from the constants in the SHChangeNotify help. This parameter
//* allows multiple events to share handlers and still distinguish
//* the reason the handler was triggered.
//* Path1, Path2: strings which are the paths affected by the shell
//* event. Whether both are passed depends on whether the second
//* is needed to describe the event. For example, OnDelete gives
//* only the name of the file (including path) that was deleted;
//* but OnRenameFolder gives the original folder name in Path1
//* and the new name in Path2.
//* In some cases, such as OnAssocChanged, neither Path parameter
//* means anything, and in other cases, I guessed, but we always
//* pass at least one.
//* Each time an event property is changed, the component is reset to
//* trap only those events for which handlers are assigned. So assigning
//* an event handler suffices to indicate your intention to trap the
//* corresponding shell event.
//*
//* There is one more event: OnEndSessionQuery, which has the same
//* parameters as the standard Delphi OnCloseQuery (and can in fact
//* be your OnCloseQuery handler). This component must shut down its
//* interception of shell events when system shutdown is begun, lest
//* the system fail to shut down at the user's request.
//*
//* Setting CanEndSession (same as CanClose) to FALSE in an
//* OnEndSessionQuery will stop the process of shutting down
//* Windows. You would only need this if you need to keep the user
//* from ending his Windows session while your program is running.
//*
//* I'd be honored to hear what you think of this component.
//* You can write me at shevine@aol.com.
//*************************************************************
//*************************************************************
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
{$IFNDEF Delphi3orHigher}
OLE2,
{$ELSE}
ActiveX, ComObj,
{$ENDIF}
ShlObj;
const
SHCNF_ACCEPT_INTERRUPTS = $0001;
SHCNF_ACCEPT_NON_INTERRUPTS = $0002;
SHCNF_NO_PROXY = $8000;
type NOTIFYREGISTER = record
pidlPath : PItemIDList;
bWatchSubtree : boolean;
end;
type PNOTIFYREGISTER = ^NOTIFYREGISTER;
type TTextCase = (tcAsIs,tcUppercase,tcLowercase);
type
TOneParmEvent = procedure(Sender : TObject; Flags : cardinal; Path1 : string) of object;
TTwoParmEvent = procedure(Sender : TObject; Flags : cardinal; Path1, Path2 : string) of object;
TEndSessionQueryEvent = procedure(Sender: TObject; var CanEndSession: Boolean) of object;
function SHChangeNotifyRegister(
hWnd : HWND;
dwFlags : integer;
wEventMask : cardinal;
uMsg : UINT;
cItems : integer;
lpItems : PNOTIFYREGISTER) : HWND; stdcall;
function SHChangeNotifyDeregister(
hWnd : HWND) : boolean; stdcall;
function SHILCreateFromPath(Path: Pointer;
PIDL: PItemIDList; var Attributes: ULONG):
HResult; stdcall;
type
TSHChangeNotify = class(TComponent)
private
fTextCase : TTextCase;
fHardDriveOnly : boolean;
NotifyCount : integer;
NotifyHandle : hwnd;
NotifyArray : array[1..26] of NOTIFYREGISTER;
AllocInterface : IMalloc;
PrevMsg : integer;
prevpath1 : string;
prevpath2 : string;
fMessageNo : integer;
fAssocChanged : TTwoParmEvent;
fAttributes : TOneParmEvent;
fCreate : TOneParmEvent;
fDelete : TOneParmEvent;
fDriveAdd : TOneParmEvent;
fDriveAddGUI : TOneParmEvent;
fDriveRemoved : TOneParmEvent;
fMediaInserted : TOneParmEvent;
fMediaRemoved : TOneParmEvent;
fMkDir : TOneParmEvent;
fNetShare : TOneParmEvent;
fNetUnshare : TOneParmEvent;
fRenameFolder : TTwoParmEvent;
fRenameItem : TTwoParmEvent;
fRmDir : TOneParmEvent;
fServerDisconnect : TOneParmEvent;
fUpdateDir : TOneParmEvent;
fUpdateImage : TOneParmEvent;
fUpdateItem : TOneParmEvent;
fEndSessionQuery : TEndSessionQueryEvent;
OwnerWindowProc : TWndMethod;
procedure SetMessageNo(value : integer);
procedure WndProc(var msg: TMessage);
protected
procedure QueryEndSession(var msg: TMessage);
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Execute;
procedure Stop;
published
property MessageNo : integer read fMessageNo write SetMessageNo default WM_USER;
property TextCase : TTextCase read fTextCase write fTextCase default tcAsIs;
property HardDriveOnly : boolean read fHardDriveOnly write fHardDriveOnly default True;
property OnAssocChanged : TTwoParmEvent read fAssocChanged write fAssocChanged;
property OnAttributes : TOneParmEvent read fAttributes write fAttributes;
property OnCreate : TOneParmEvent read fCreate write fCreate;
property OnDelete : TOneParmEvent read fDelete write fDelete;
property OnDriveAdd : TOneParmEvent read fDriveAdd write fDriveAdd;
property OnDriveAddGUI : TOneParmEvent read fDriveAddGUI write fDriveAddGUI;
property OnDriveRemoved : TOneParmEvent read fDriveRemoved write fDriveRemoved;
property OnMediaInserted : TOneParmEvent read fMediaInserted write fMediaInserted;
property OnMediaRemoved : TOneParmEvent read fMediaRemoved write fMediaRemoved;
property OnMkDir : TOneParmEvent read fMkDir write fMkDir;
property OnNetShare : TOneParmEvent read fNetShare write fNetShare;
property OnNetUnshare : TOneParmEvent read fNetUnshare write fNetUnshare;
property OnRenameFolder : TTwoParmEvent read fRenameFolder write fRenameFolder;
property OnRenameItem : TTwoParmEvent read fRenameItem write fRenameItem;
property OnRmDir : TOneParmEvent read fRmDir write fRmDir;
property OnServerDisconnect : TOneParmEvent read fServerDisconnect write fServerDisconnect;
property OnUpdateDir : TOneParmEvent read fUpdateDir write fUpdateDir;
property OnUpdateImage : TOneParmEvent read fUpdateImage write fUpdateImage;
property OnUpdateItem : TOneParmEvent read fUpdateItem write fUpdateItem;
property OnEndSessionQuery : TEndSessionQueryEvent
read fEndSessionQuery write fEndSessionQuery;
{ Published declarations }
end;
procedure Register;
implementation
const Shell32DLL = 'shell32.dll';
function SHChangeNotifyRegister;
external Shell32DLL index 2;
function SHChangeNotifyDeregister;
external Shell32DLL index 4;
function SHILCreateFromPath;
external Shell32DLL index 28;
procedure Register;
begin
RegisterComponents('Custom', [TSHChangeNotify]);
end;
// Set defaults, and ensure NotifyHandle is zero.
constructor TSHChangeNotify.Create (AOwner : TComponent);
begin
inherited Create(AOwner);
fTextCase := tcAsIs;
fHardDriveOnly := true;
fAssocChanged := nil;
fAttributes := nil;
fCreate := nil;
fDelete := nil;
fDriveAdd := nil;
fDriveAddGUI := nil;
fDriveRemoved := nil;
fMediaInserted := nil;
fMediaRemoved := nil;
fMkDir := nil;
fNetShare := nil;
fNetUnshare := nil;
fRenameFolder := nil;
fRenameItem := nil;
fRmDir := nil;
fServerDisconnect := nil;
fUpdateDir := nil;
fUpdateImage := nil;
fUpdateItem := nil;
fEndSessionQuery := nil;
MessageNo := WM_USER;
// If designing, dodge the code that implements messag interception.
if csDesigning in ComponentState
then exit;
// Substitute our window proc for our owner's window proc.
OwnerWindowProc := (Owner as TWinControl).WindowProc;
(Owner as TWinControl).WindowProc := WndProc;
// Get the IMAlloc interface so we can free PIDLs.
SHGetMalloc(AllocInterface);
end;
procedure TSHChangeNotify.SetMessageNo(value : integer);
begin
if (value >= WM_USER)
then fMessageNo := value
else raise Exception.Create
('MessageNo must be greater than or equal to '
+ inttostr(WM_USER));
end;
// Execute unregisters any current notification and registers a new one.
procedure TSHChangeNotify.Execute;
var
EventMask : integer;
driveletter : string;
i : integer;
pidl : PItemIDList;
Attributes : ULONG;
NotifyPtr : PNOTIFYREGISTER;
begin
NotifyCount := 0;
if csDesigning in ComponentState
then exit;
Stop; // Unregister the current notification, if any.
EventMask := 0;
if assigned(fAssocChanged ) then EventMask := (EventMask or SHCNE_ASSOCCHANGED);
if assigned(fAttributes ) then EventMask := (EventMask or SHCNE_ATTRIBUTES);
if assigned(fCreate ) then EventMask := (EventMask or SHCNE_CREATE);
if assigned(fDelete ) then EventMask := (EventMask or SHCNE_DELETE);
if assigned(fDriveAdd ) then EventMask := (EventMask or SHCNE_DRIVEADD);
if assigned(fDriveAddGUI ) then EventMask := (EventMask or SHCNE_DRIVEADDGUI);
if assigned(fDriveRemoved ) then EventMask := (EventMask or SHCNE_DRIVEREMOVED);
if assigned(fMediaInserted ) then EventMask := (EventMask or SHCNE_MEDIAINSERTED);
if assigned(fMediaRemoved ) then EventMask := (EventMask or SHCNE_MEDIAREMOVED);
if assigned(fMkDir ) then EventMask := (EventMask or SHCNE_MKDIR);
if assigned(fNetShare ) then EventMask := (EventMask or SHCNE_NETSHARE);
if assigned(fNetUnshare ) then EventMask := (EventMask or SHCNE_NETUNSHARE);
if assigned(fRenameFolder ) then EventMask := (EventMask or SHCNE_RENAMEFOLDER);
if assigned(fRenameItem ) then EventMask := (EventMask or SHCNE_RENAMEITEM);
if assigned(fRmDir ) then EventMask := (EventMask or SHCNE_RMDIR);
if assigned(fServerDisconnect ) then EventMask := (EventMask or SHCNE_SERVERDISCONNECT);
if assigned(fUpdateDir ) then EventMask := (EventMask or SHCNE_UPDATEDIR);
if assigned(fUpdateImage ) then EventMask := (EventMask or SHCNE_UPDATEIMAGE);
if assigned(fUpdateItem ) then EventMask := (EventMask or SHCNE_UPDATEITEM);
if EventMask = 0 // If there's no event mask
then exit; // then there's no need to set an event.
// If the user requests watches on hard drives only, cycle through
// the list of drive letters and add a NotifyList element for each.
// Otherwise, just set the first element to watch the entire file
// system.
if fHardDriveOnly
then for i := ord('A') to ord('Z') do begin
DriveLetter := char(i) + ':\';
if GetDriveType(pchar(DriveLetter)) = DRIVE_FIXED
then begin
inc(NotifyCount);
with NotifyArray[NotifyCount] do begin
SHILCreateFromPath
(pchar(DriveLetter),
addr(pidl),
Attributes);
pidlPath := pidl;
bWatchSubtree := true;
end;
end;
end
// If the caller requests the entire file system be watched,
// prepare the first NotifyElement accordingly.
else begin
NotifyCount := 1;
with NotifyArray[1] do begin
pidlPath := nil;
bWatchSubtree := true;
end;
end;
NotifyPtr := addr(NotifyArray);
NotifyHandle := SHChangeNotifyRegister(
(Owner as TWinControl).Handle,
SHCNF_ACCEPT_INTERRUPTS +
SHCNF_ACCEPT_NON_INTERRUPTS,
EventMask,
fMessageNo,
NotifyCount,
NotifyPtr);
if NotifyHandle = 0
then begin
Stop;
raise Exception.Create('Could not register SHChangeNotify');
end;
end;
// This procedure unregisters the Change Notification
procedure TSHChangeNotify.Stop;
var
NotifyHandle : hwnd;
i : integer;
pidl : PITEMIDLIST;
begin
if csDesigning in ComponentState
then exit;
// Deregister the shell notification.
if NotifyCount > 0
then SHChangeNotifyDeregister(NotifyHandle);
// Free the PIDLs in NotifyArray.
for i := 1 to NotifyCount do begin
pidl := NotifyArray[i].PidlPath;
if AllocInterface.DidAlloc(pidl) = 1
then AllocInterface.Free(pidl);
end;
NotifyCount := 0;
end;
// This is the procedure that is called when a change notification occurs.
// It interprets the two PIDLs passed to it, and calls the appropriate
// event handler, according to what kind of event occurred.
procedure TSHChangeNotify.WndProc(var msg: TMessage);
type
TPIDLLIST = record
pidlist : array[1..2] of PITEMIDLIST;
end;
PIDARRAY = ^TPIDLLIST;
var
Path1 : string;
Path2 : string;
ptr : PIDARRAY;
p1,p2 : PITEMIDLIST;
repeated : boolean;
p : integer;
event : longint;
parmcount : byte;
OneParmEvent : TOneParmEvent;
TwoParmEvent : TTwoParmEvent;
// The internal function ParsePidl returns the string corresponding
// to a PIDL.
function ParsePidl (Pidl : PITEMIDLIST) : string;
begin
SetLength(result,MAX_PATH);
if not SHGetPathFromIDList(Pidl,pchar(result))
then result := '';
end;
// The actual message handler starts here.
begin
if Msg.Msg = WM_QUERYENDSESSION
then QueryEndSession(Msg);
if Msg.Msg = fMessageNo
then begin
OneParmEvent := nil;
TwoParmEvent := nil;
event := msg.LParam and ($7FFFFFFF);
case event of
SHCNE_ASSOCCHANGED : TwoParmEvent := fAssocChanged;
SHCNE_ATTRIBUTES : OneParmEvent := fAttributes;
SHCNE_CREATE : OneParmEvent := fCreate;
SHCNE_DELETE : OneParmEvent := fDelete;
SHCNE_DRIVEADD : OneParmEvent := fDriveAdd;
SHCNE_DRIVEADDGUI : OneParmEvent := fDriveAddGUI;
SHCNE_DRIVEREMOVED : OneParmEvent := fDriveRemoved;
SHCNE_MEDIAINSERTED : OneParmEvent := fMediaInserted;
SHCNE_MEDIAREMOVED : OneParmEvent := fMediaRemoved;
SHCNE_MKDIR : OneParmEvent := fMkDir;
SHCNE_NETSHARE : OneParmEvent := fNetShare;
SHCNE_NETUNSHARE : OneParmEvent := fNetUnshare;
SHCNE_RENAMEFOLDER : TwoParmEvent := fRenameFolder;
SHCNE_RENAMEITEM : TwoParmEvent := fRenameItem;
SHCNE_RMDIR : OneParmEvent := fRmDir;
SHCNE_SERVERDISCONNECT : OneParmEvent := fServerDisconnect;
SHCNE_UPDATEDIR : OneParmEvent := fUpdateDir;
SHCNE_UPDATEIMAGE : OneParmEvent := fUpdateImage;
SHCNE_UPDATEITEM : OneParmEvent := fUpdateItem;
else begin
OneParmEvent := nil; // Unknown event;
TwoParmEvent := nil;
end;
end;
if (assigned(OneParmEvent)) or (assigned(TwoParmEvent))
then begin
// Assign a pointer to the array of PIDLs sent
// with the message.
ptr := PIDARRAY(msg.wParam);
// Parse the two PIDLs.
p1 := ptr^.pidlist[1];
try
SetLength(Path1,MAX_PATH);
Path1 := ParsePidl(p1);
p := pos(#00,Path1);
if p > 0
then SetLength(Path1,p - 1);
except
Path1 := '';
end;
p2 := ptr^.pidlist[2];
try
SetLength(Path2,MAX_PATH);
Path2 := ParsePidl(p2);
p := pos(#00,Path2);
if p > 0
then SetLength(Path2,p - 1);
except
Path2 := '';
end;
// If this message is the same as the last one (which happens
// a lot), bail out.
try
repeated := (PrevMsg = event)
and (uppercase(prevpath1) = uppercase(Path1))
and (uppercase(prevpath2) = uppercase(Path2))
except
repeated := false;
end;
// Save the elements of this message for comparison next time.
PrevMsg := event;
PrevPath1 := Path1;
PrevPath2 := Path2;
// Convert the case of Path1 and Path2 if desired.
case fTextCase of
tcUppercase : begin
Path1 := uppercase(Path1);
Path2 := uppercase(Path2);
end;
tcLowercase : begin
Path1 := lowercase(Path1);
Path2 := lowercase(Path2);
end;
end;
// Call the event handler according to the number
// of paths we will pass to it.
if not repeated then begin
case event of
SHCNE_ASSOCCHANGED,
SHCNE_RENAMEFOLDER,
SHCNE_RENAMEITEM : parmcount := 2;
else parmcount := 1;
end;
if parmcount = 1
then OneParmEvent(self, event, Path1)
else TwoParmEvent(self, event, Path1, Path2);
end;
end; // if assigned(OneParmEvent)...
end; // if Msg.Msg = fMessageNo...
// Call the original message handler.
OwnerWindowProc(Msg);
end;
procedure TSHChangeNotify.QueryEndSession(var msg: TMessage);
var
CanEndSession : boolean;
begin
CanEndSession := true;
if Assigned(fEndSessionQuery)
then fEndSessionQuery(Self, CanEndSession);
if CanEndSession
then begin
Stop;
Msg.Result := 1;
end
else Msg.Result := 0;
end;
destructor TSHChangeNotify.Destroy;
begin
if not (csDesigning in ComponentState)
then begin
if Assigned(Owner)
then (Owner as TWinControl).WindowProc := OwnerWindowProc;
Stop;
end;
inherited;
end;
end.
{
********************************************
Zarko Gajic
About.com Guide to Delphi Programming
http://delphi.about.com
email: delphi.guide@about.com
free newsletter: http://delphi.about.com/library/blnewsletter.htm
forum: http://forums.about.com/ab-delphi/start/
********************************************
}
</code></pre>
|
IE6 Bullet Point Alignment Problem <p>I am currently having some problems with <code><li></code> in IE6 essentially my code looks like this,</p>
<pre><code><ul>
<li>some filler text some filler text</li>
<li>some filler text some filler text</li>
<li>some filler text some filler text</li>
</ul>
</code></pre>
<p>The problem come when I view the page in IE 6 the bullets and the text do not line up as you would expect has any one ever encountered this problem before, for the record here is the CSS for the div and li concerned. </p>
<pre><code> #contentMiddle li
{
/*background-image:url(../images/bullet.gif);
background-repeat:no-repeat;
background-position:left bottom;
text-align:left;
list-style-position:outside;*/
list-style-image:url(../images/bullet.gif);
list-style-position:inside;
text-align:left;
margin-bottom:5px;
}
#contentMiddle
{
background-color:#A3BAD9;
padding-left:20px;
padding-right:20px;
}
</code></pre>
<p>Thank you for your help</p>
<p>sico87 :-)</p>
| <p>You should decide whether you want to use background-image or list-style-image to add the bullet. I'd advise for the background-image solution as the other one has problems in IE6, as you saw already.</p>
|
.asmx web services with ssl <p>Are there any special configuration settings you have to do to make a web service work with SSL?</p>
<p>Is there a way to force the service methods to authenticate using a username/password like I can do with a WCF service?</p>
| <ol>
<li>No. SSL support provided by web server (IIS). </li>
<li>Yes. Just configure authentication through web.config</li>
</ol>
|
How to programmatically create a Quick Campaign in MS Dynamics CRM <p>I am trying to create a "quick campaign" in code, but I don't find a class to do that.</p>
<p>I found the way to create a list and add users to that list. But I can't continue, because I don't know the way.</p>
| <p>this is an old post but I thought I'd reply anyway.</p>
<p>The 'quick campaign' entity in CRM is called 'bulkoperation'. The Quick Campaign Wizard only creates activity records of other types, such as phone calls or tasks. The bulk operation is that which actually performs the action of distributing the campaign. A quick campaign is not a standard CRM entity. </p>
<p>As far as I know, you can't create a bulkoperation record using code - there is no 'Create' method for this class. I assume this is because the bulk operations are tied to the CRM platform too tightly. </p>
<p>The closest way to simulate creating a quick campaign, I would suggest, is to perform the actions of the Quick Campaign Wizard using code and create the associated activities that the Wizard would normally create. That, or use the Campaign entity, which can be managed with code.</p>
<p>Search the CRM SDK for the bulkoperation class for more information.</p>
|
Com Object Exception <p>I wrote an application that loops through a set of records and prints two things. </p>
<p>One is a report from SSRS wich works correctly. </p>
<p>The other is a drawing that uses a COM object to print. The COM object randomly fails and causes the program to quit. </p>
<p>Is there a way to stop it from killing the entire program when the COM Object fails? I have tried catch every exception at every level and it still does not work.</p>
| <p>Do you have the code of COM object that you are calling. If you have code then check whether there any exit command on failure. </p>
|
WCF Service Throttling <p>Lets assume that I'm dealing with a service that involves sending large amounts of data.</p>
<p>If I implement this with WCF, will WCF throttle the service based on how much memory each request takes to serve? Or will I be getting continuous out of memory exceptions each time I receive a large number of hits to my service?</p>
<p>I'm quite curious as to dealing with this problem outside of WCF, I'm still a bit new to service development...</p>
| <p>While using the binding attributes and readerQuotas like Andrew Hare suggests will allow for essentially an unlimited size for most practical uses, keep in mind that the you will run into other issues such as timeouts if you accept a long running command, no matter how that service is constructed (using WCF or not). </p>
<p>No matter what the size of your message is, the WCF service will need to be throttled for performance so that it is not flooded. If you are hosting it in IIS or WAS, you will have additional built-in features to those hosting environments that will make your service much more "highly available". However, you still need to pay attention to concurrency issues. The following WCF config provides an example of setting some throttling values.</p>
<pre><code> <system.serviceModel>
...
<behaviors>
<serviceBehaviors>
<behavior name="GenericServiceBehavior">
<serviceTimeouts transactionTimeout="00:09:10"/>
<serviceThrottling
maxConcurrentCalls="20"
maxConcurrentSessions="20"
maxConcurrentInstances="20"
/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</code></pre>
|
User variables - fighting syntax <p>Can anyone set my MySQL syntax straight please?
I am trying to set a user variable called "seconds" to equal the output of the query shown below (and it does work by it's self), but I am constantly geting "You have an error in your SQL syntax" errors.</p>
<pre><code>SET @seconds=AVG(t2.epoch-t1.epoch)
FROM tmp_4045_metrics AS t1, tmp_4045_metrics AS t2
WHERE t1.seq+1 = t2.seq
</code></pre>
<p>I have tried SELECT AVG...., (SELECT AVG...), and quite a few others, but always the same error warning that my syntax is incorrect and never any clues to where it's incorrect.</p>
<p>Can anyone point me in the right direction?</p>
<p>Thanks,
Rich</p>
| <p>If i remember correctly (and it works on MS SQL Server at work), this should do it:</p>
<pre><code>Select @seconds=AVG(t2.epoch-t1.epoch)
FROM tmp_4045_metrics AS t1, tmp_4045_metrics AS t2
WHERE t1.seq+1 = t2.seq
</code></pre>
|
Apache is listening on a different port, but how do I get it so I don't have to type in the port number? <p>I am running IIS and Apache HTTP Server side-by-side on my localhost machine, and Apache is listening on a different port (port 81). IIS is listening to port 80. However, I can only get to my virtual domains for Apache if I type in that port number. So for instance:</p>
<p><a href="http://virtual.myvirtualdomain.com:81" rel="nofollow">http://virtual.myvirtualdomain.com:81</a>
<a href="http://virtual.myvirtualdomain2.com:81" rel="nofollow">http://virtual.myvirtualdomain2.com:81</a></p>
<p>How can I make it so Apache automatically knows it is port 81, and does not force me to type in the port number?</p>
<p><strong>EDIT:</strong></p>
<p>The answer appears to be that I need to redirect IIS to Apache. Can anyone provide clarification on how that is done with IIS 5.1?</p>
| <p>It's not a matter of telling Apache, it's a matter of the browser knowing what to connect to. You're either going to have to have IIS redirect to Apache, or give up.</p>
|
ASP.NET - running a bat script on another machine <p>I would like to run a bat script on one of the machines on the domain, from my asp.net application. Machine with the batch script is a temporary storage machine, and script synchronizes it with the permanent storage machine. So, what is the optimal way of doing this?</p>
<p>The thing I tried is to use <a href="http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx" rel="nofollow">PsExec</a> to run a script on the remote machine. I create a process that makes a PsExec call, and it actually does it's job pretty well. However, since the ASP.NET worker thread runs under ASP.NET account that has restricted privileges, I must hard-code my domain user credentials in PsExec call, and that's something I do not like doing. </p>
<p>Is there a way to overcome this problem, or maybe some other approach that I could try?</p>
<p>Thanks...</p>
| <p>You can use the <identity impersonate="true" /> setting in your Web.config to have the application run under the IUSR, or you can set a username/password on the identity tag to an account you'd like to use to run the BAT file.</p>
<p>I had previously found some details on Impersonate over at: <a href="http://www.aspdev.org/articles/web.config/" rel="nofollow">http://www.aspdev.org/articles/web.config/</a></p>
<p>But I'm sure a quick web search will find you even more info on Impersonate.</p>
|
Calling WSE service from a .net 3.5 application <p>I am trying to call a .asmx (WSE) web service from a .net 3.5 application.</p>
<p>This is possible correct?
It seems when I add a web reference the API is completely different than when I add a reference in a .net 2.0 app.</p>
| <p>You can use the Add Web Reference button in the dialog displayed (Add service reference) to add a pre-3.0 style reference. </p>
<p>By default, when you add a service reference, VS will generate a class that uses WCF. It's not an issue but you might prefer to stick to the old style.</p>
<p>By the way, WCF is more flexible and unified approach to communication in .NET 3.0 onwards. You should consider it.</p>
|
Is the "_" prefix reserved for MovieClip names? <p>Is it possible to use the <strong>"_" underscore prefix</strong> for your own <strong>MovieClip names?</strong> (AS2)</p>
<p>i.e. Can you name a created/attached MovieClip "_feature" or "_bug" ?</p>
<p>Typically this is reserved for <strong>internal properties</strong> like <code>_x</code> or <code>_visible</code>.</p>
| <p>The "_" prefix has no technical significance - you can use it your own names for MovieClips, text fields, or any other variable or method you like.</p>
<p>As a convention, it used to be common for the names of "built in" properties (like <code>_x</code>, <code>_visible</code>, etc.) to begin with an underbar, but they stopped doing this around v6 or v7, so many later properties (<code>filters</code>, <code>transform</code> for example) don't use it. Also, they've used (and still use I believe, in AS3) multiple underbars for internal names they don't want people to trip over (like <code>__proto__</code>).</p>
<p>There also used to be a fairly widespread convention to prepend <code>$</code> to properties or methods intended to be private, since declaring them to be private doesn't have any effect. You see this a lot in components.</p>
|
should i really use a relation table when tagging blog posts? <p>while trying to figure out how to tag a blog post with a single sql statement <a href="http://stackoverflow.com/questions/480065/nested-insert-in-mysql-for-tagging">here</a>, the following thought crossed my mind: using a relation table tag2post that references tags by id as follows just isn't necessary:</p>
<pre><code>tags
+-------+-----------+
| tagid | tag |
+-------+-----------+
| 1 | news |
| 2 | top-story |
+-------+-----------+
tag2post
+----+--------+-------+
| id | postid | tagid |
+----+--------+-------+
| 0 | 322 | 1 |
+----+--------+-------+
</code></pre>
<p><strong>why not</strong> just using the following model, where you <strong>index the tag itself</strong> as follows? taken that tags are never renamed, but added and removed, this could make sense, right? what do you think?</p>
<pre><code>tag2post
+----+--------+-------+
| id | postid | tag |
+----+--------+-------+
| 1 | 322 | sun |
+----+--------+-------+
| 2 | 322 | moon |
+----+--------+-------+
| 3 | 4443 | sun |
+----+--------+-------+
| 4 | 2567 | love |
+----+--------+-------+
</code></pre>
<p>PS: i keep an <strong>id</strong>, i order to easily display the last <em>n</em> tags added...</p>
| <p>It works, but it is not normalized, because you have redundancy in the tags. You also lose the ability to use the "same" tags to tag things besides posts. For small N, optimization doesn't matter, so I have no problems if you run with it.</p>
<p>As a practical matter, your indexes will be larger (assuming you are going to index on tag for searching, you are now indexing duplicates and indexing strings). In the normalized version, the index on the tags table will be smaller, will not have duplicates, and the index on the tag2post table on tagid will be smaller. In addition, the fixed size int columns are very efficient for indexing and you might also avoid some fragmentation depending on your clustering choices.</p>
<p>I know you said no renaming, but in general, in both cases, you might still need to think about the semantics of what it means to rename (or even delete) a tag - do all entries need to be changed, or does the tag get split in some way. Because this is a batch operation in a transaction in the worst case (all the tag2post have to be renamed), I don't really classify it as significant from a design point of view.</p>
|
How do you convert LOGFONT.lfHeight to pixels? <p>I have a LOGFONT.lfHeight value of -11. However, I know that the font size is actually 8 so do I need to convert this number to a different unit of measurement? I found this formula in the MSDN docs:</p>
<p>int height = abs((pixels * DOTSY) / 72);</p>
<p>This takes pixels and makes it into a height value that LOGFONT can use. If I work this the other way:</p>
<p>int pixels = abs((height / DOTSY) * 72);</p>
<p>This gives me a value of 8.24. Am I correct in assuming this is all I need to do to convert the font height into a usable value?</p>
| <p>Yes. DOTSY will be 96, which is the default monitor resolution in DPI in Windows. You will need to ensure that this value is correct for the device you're writing to - printers will usually have a much higher resolution, and the monitor resolution can be changed. lfHeight is negative to indicate that the font mapper should use character height instead of cell height to match, so only the absolute value is important here.</p>
|
Problem getting selected text when using a sprited button and selection.createRange() in Internet Explorer <p>I'm working on implementing sprited buttons in Stackoverflow's beloved WMD markdown editor and I've run into an odd bug. On all versions of IE, the selected text is lost upon button clicks, so, say, highlighting a block of text and clicking the code button acts like you placed the cursor at the end of the selection and clicked the button.</p>
<p>e.g. highlighting this:</p>
<pre><code>This
Is
Code
</code></pre>
<p>and clicking the code button give you:</p>
<pre><code>This
Is
Code`enter code here`
</code></pre>
<p>What's really weird is that I left the original non-sprited button bar in <em>and that works just fine.</em> In fact <strong>ALL</strong> buttons and keyboard shortcuts code use the same <code>doClick(button)</code> function!</p>
<ul>
<li>Old-style non-sprited buttons: OK</li>
<li>Keyboard shortcuts: OK</li>
<li>Sprited buttons in non-IE browsers: OK</li>
<li>Sprited buttons in IE: <strong>WTF</strong></li>
</ul>
<p>I've isolated the problem down to a call to <code>selection.createRange()</code> which finds nothing <strong>only</strong> when the sprited button is clicked. I've tried screwing around with focus()ing and making sure as little as possible happens before the <code>doClick()</code> but no joy. The keyboard shortcuts seem to work because the focus is never lost from the input textarea. Can anyone think of a hack that will let me somehow collect the selected text in IE?</p>
<p>The onclick handler looks like this:</p>
<pre><code>button.onmouseout = function(){
this.style.backgroundPosition = this.XShift + " " + normalYShift;
};
button.onclick = function() {
if (this.onmouseout) {
this.onmouseout();
}
doClick(this);
}
</code></pre>
<p>I've tried moving the <code>onmouseout</code> call to after the <code>doClick</code> in case that was causing a loss of focus but that's not the problem.</p>
<p>EDIT:</p>
<p>The only thing that seems to be different is that, in the original button code, you are clicking on an image. In the sprited code, you are clicking on a list item <code><li></code> with a background image set. Perhaps it's trying to select the non-existent text in my list item?</p>
<p>/EDIT</p>
<p>Actual code is located in my wmd repository on <a href="http://github.com/derobins/wmd/tree/master" rel="nofollow">git</a> in the <code>button-cleanup</code> branch.</p>
<p>If you revert to the 0d6d1b32bb42a6bd1d4ac4e409a19fdfe8f1ffcc commit you can see both button bars. The top one is sprited and exhibits the weird behavior. The bottom one contains the remnants of the original button bar and works fine. The suspect code is in the <code>setInputAreaSelectionStartEnd()</code> function in the <code>TextareaState</code> object.</p>
<p>One last thing I should mention is that, for the time being, I'm trying to keep the control in pure Javascript so I'd like to avoid fixing this with an external library like jQuery if that's possible.</p>
<p>Thanks for your help!</p>
| <p>I know what the answer to my own question is.</p>
<p>The sprited buttons are implemented using an HTML list and CSS, where all the list items have a background image. The background image is moved around using CSS to show different buttons and states (like mouseover highlights). Standard CSS button spriting stuff.</p>
<p>This works fine in IE with one exception: IE tries to select the empty list text when you click on the background image "button". The selection in the input textarea goes away and the current selection (which will be returned by document.selection.createRange()) is moved to the empty text in the list item.</p>
<p>The fix for this is simple - I created a variable to cache the selection and a flag. In IE I cache the selection and set the flag in a mousedown event handler. In the text processing, I check for the presence of the flag - if it's set I use the cached range instead of querying document.selection.createRange().</p>
<p>Here are some code snippets:</p>
<pre><code>wmd.ieCachedRange = null;
wmd.ieRetardedClick = false;
if(global.isIE) {
button.onmousedown = function() {
wmd.ieRetardedClick = true;
wmd.ieCachedRange = document.selection.createRange();
};
}
var range;
if(wmd.ieRetardedClick && wmd.ieCachedRange) {
range = wmd.ieCachedRange;
wmd.ieRetardedClick = false;
}
else {
range = doc.selection.createRange();
}
</code></pre>
<p>The solution is only a few lines of code and avoids messing around with the DOM and potentially creating layout engine issues.</p>
<p>Thanks for your help, Cristoph. I came up with the answer while thinking and googling about your answer.</p>
|
Send message from one running console app to another <p>I have one console app that is doing some lengthy syncing to an ftp server.<br />
Another console app prepares a local filesystem with some needed updated files.<br />
Then the second one will wait for the first one to finish before swapping a final directory name so it becomes visible on the web.</p>
<p>I searched for the best way to make the syncing app to communicate to the second app that it's finished it's job. It looks like <a href="http://msdn.microsoft.com/en-us/library/aa365574(VS.85).aspx#base.using_data_copy_for_ipc">Using Data Copy for IPC</a> is the best suited solution for this. </p>
<p>Question is two fold:</p>
<ul>
<li>Am I right? Is there a more straight forward way to get to the same result?</li>
<li>Is there a managed (.net) way to do this?</li>
</ul>
| <p>If all you need is to notify one application that the other has completed its task, the easiest way would be to use a named EventWaitHandle. The object is created in its unsignaled state. The first app waits on the handle, and the second app signals the handle when it's finished doing its job. For example:</p>
<pre><code>// First application
EventWaitHandle waitForSignal = new EventWaitHandle(false, EventResetMode.ManualReset, "MyWaitHandle");
// Here, the first application does whatever initialization it can.
// Then it waits for the handle to be signaled:
// The program will block until somebody signals the handle.
waitForSignal.WaitOne();
</code></pre>
<p>That sets up the first program to wait for synchronization. The second application is equally simple:</p>
<pre><code>// Second app
EventWaitHandle doneWithInit = new EventWaitHandle(false, EventResetMode.ManualReset, "MyWaitHandle");
// Here, the second application initializes what it needs to.
// When it's done, it signals the wait handle:
doneWithInit.Set();
</code></pre>
<p>When the second application calls Set, it signals the event and the first application will continue.</p>
|
How to efficiently render and process video streams using GPU? <p>I plan to develop a tool for realtime video manipulation using C++, Qt and OpenGL. Video overlay isn't an option since shaders should be used for frame processing. At the moment I imagine a following sequence of steps:</p>
<ol>
<li>Decode video (CPU)</li>
<li>Preprocess it (optional, CPU)</li>
<li>Transer it to video memory (GPU using DMA)</li>
<li>Further process it using vertex and fragment shaders (GPU)</li>
<li>Render it (GPU)</li>
</ol>
<p>I'm looking for some general advice explaning what extentions or technics can be used here. Is there a good reason to use Direct3D instead? </p>
| <p>If you're linux, NVIDIA's recent drivers in the 180.xx series have added support for video decoding via the VDPAU api (Video Decoding and Presentation something). Many major projects have integrated with the api including mplayer, vlc, ffmpeg, and mythtv. I don't know all of the specifics, but they provide api for many codecs including common sub-operations and bitstream manipulation.</p>
<p>I'd look here before going straight to CUDA (which I assume VDPAU may use)</p>
|
Is C# a superset of C? <p>Is C# a superset of C in anyway, like Objective-C or C++? Is there a way to compile C online with constructs such compiler flags?</p>
| <p>In a word, No.</p>
|
css inheritance <p>I've just added the Twitter script to my website, and cannot, despite inexpertly consulting firebug, determine how to alter the css to make the feed appear uniform with the other text on my page.</p>
<p>The page in question is
<a href="http://willworth.co.uk/latest.htm" rel="nofollow">http://willworth.co.uk/latest.htm</a></p>
<p>Any help would be greatly appreciated</p>
<p>Thank you in advance. </p>
<p>As I improve, I will help the community as best I can</p>
<p>Will </p>
| <p>You've applied your font styling etc to the <code><p></code> tag only.</p>
<p>The content of your twitter <code><div></code> contains no <code><p></code>, and doesn't descend from a <code><p></code>.</p>
<p>You need to change the markup to wrap with paragraph tags, or change the CSS to apply the font styling to the <code><div></code> or more likely the <code><body></code></p>
<p>edit: heh, Jonathan actually looked at the source :) The reason this doesn't show up in firebug (and so for me too!) is because it didn't parse as Jonathan points out. FB only reports the state of the page as it exists.</p>
|
What is the best way to sort a partially ordered list? <p>Probably best illustrated with a small example.<br />
Given the relations</p>
<pre><code>A < B < C
A < P < Q
</code></pre>
<p>Correct outputs would be</p>
<pre><code>ABCPQ or APQBC or APBCQ ... etc.
</code></pre>
<p>In other words, any ordering is valid in which the given relationships hold.</p>
<p>I am most interested in the solution that is easiest to implement, but the best O(n) in speed and time is interesting as well.</p>
| <p>This is called <a href="http://en.wikipedia.org/wiki/Topological_sorting" rel="nofollow">topological sorting</a>.</p>
<p>The standard algorithm is to output a minimal element, then remove it and repeat until done.</p>
|
How do I set a field to null in Quest Toad "Browse Database Objects" view? <p>Simple question, would love a solution if there is one! I assume there has to be some keyboard shortcut that will insert a null but Google isn't helping.</p>
<p>Thanks in advance!</p>
| <p>I followed Brent's suggestion and got my answer: <kbd>ctrl</kbd>+<kbd>del</kbd>.</p>
|
How do I get a count of items in one column that match items in another column? <p>Assume I have two data tables and a linking table as such:</p>
<pre>
A B A_B_Link
----- ----- -----
ID ID A_ID
Name Name B_ID
</pre>
<p>2 Questions:</p>
<ol>
<li><p>I would like to write a query so that I have all of A's columns and a count of how many B's are linked to A, what is the best way to do this?</p></li>
<li><p>Is there a way to have a query return a row with all of the columns from A and a column containing <em>all</em> of linked names from B (maybe separated by some delimiter?)</p></li>
</ol>
<p>Note that <strong>the query must return distinct rows from A</strong>, so a simple left outer join is not going to work here...I'm guessing I'll need nested select statements?</p>
| <p>For #1</p>
<pre><code>SELECT A.*,
(SELECT COUNT(*) FROM A_B_Link WHERE A_B_Link.A_ID = AOuter.A_ID)
FROM A as AOuter
</code></pre>
|
Code to calculate "median of five" in C# <p><strong>Note:</strong> Please don't interpret this as "homework question." This is just a thing I curious to know :)</p>
<p>The median of five is sometimes used as an exercise in algorithm design and is known to be computable <strong>using only 6 comparisons</strong>.</p>
<p>What is the best way to implement this <strong>"median of five using 6 comparisons"</strong> in C# ? All of my attempts seem to result in awkward code :( I need nice and readable code while still using only 6 comparisons.</p>
<pre><code>public double medianOfFive(double a, double b, double c, double d, double e){
//
// return median
//
return c;
}
</code></pre>
<p><strong>Note:</strong> I think I should provide the "algorithm" here too:</p>
<p>I found myself not able to explain the algorithm clearly as <em>Azereal</em> did in his forum post. So I will reference his post here. From <a href="http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi?board=riddles_cs;action=display;num=1061827085">http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi?board=riddles_cs;action=display;num=1061827085</a></p>
<blockquote>
<p>Well I was posed this problem in one
of my assignments and I turned to this
forum for help but no help was here.
I eventually found out how to do it.</p>
<ol>
<li><p>Start a mergesort with the first 4 elements and order each pair (2
comparisons)</p></li>
<li><p>Compare the two lower ones of each pair and eliminate the lowest one from
the possibilities (3 comparisons)</p></li>
<li><p>Add in the 5th number set aside to the number without a pair and compare
the two (4 comparisons)</p></li>
<li><p>Compare the two lowest of the two new pairs and eliminate the lower one
(5 comparisons)</p></li>
<li><p>Compare the one by itself and the lower of the last pair and the lower
number is the median</p>
<p>The possible median is within the
parentesis</p></li>
</ol>
<p>(54321)</p>
<p>5:4 3:2 2 comparisons</p>
<p>(4<5 2<3 1) </p>
<p>4:2 3 comparisons</p>
<p>2(4<5 3 1)</p>
<p>1:3 4 comparisons</p>
<p>2(4<5 1<3)</p>
<p>4:1 5 comparisons</p>
<p>1,2(4<5 3)</p>
<p>4:3 6 comparisons</p>
<p>1,2(3)4,5 </p>
<p>Three is the median</p>
</blockquote>
<p><strong>EDIT:</strong> As your request and to prevent myself from getting more downvotes, this are C++ code I wrote to find median of five. Don't mind it's awkwardness:</p>
<pre><code>double StageGenerator::MedianOfFive(double n1, double n2, double n3, double n4, double n5){
double *a = &n1, *b = &n2, *c = &n3, *d = &n4, *e = &n5;
double *tmp;
// makes a < b and b < d
if(*b < *a){
tmp = a; a = b; b = tmp;
}
if(*d < *c){
tmp = c; c = d; d = tmp;
}
// eleminate the lowest
if(*c < *a){
tmp = b; b = d; d = tmp;
c = a;
}
// gets e in
a = e;
// makes a < b and b < d
if(*b < *a){
tmp = a; a = b; b = tmp;
}
// eliminate another lowest
// remaing: a,b,d
if(*a < *c){
tmp = b; b = d; d = tmp;
a = c;
}
if(*d < *a)
return *d;
else
return *a;
}
</code></pre>
<p>It should be more compact, isn't it ?</p>
<p><strong>EDIT:</strong></p>
<p>As @pablito pointed out in his answer. The built-in List.Sort() cannot fulfill this requirement since it uses up to 13 comparisons :]</p>
| <p>I found this post interesting and as an exercise I created this which ONLY does 6 comparisons and NOTHING else:</p>
<pre><code>static double MedianOfFive(double a, double b, double c, double d, double e)
{
return b < a ? d < c ? b < d ? a < e ? a < d ? e < d ? e : d
: c < a ? c : a
: e < d ? a < d ? a : d
: c < e ? c : e
: c < e ? b < c ? a < c ? a : c
: e < b ? e : b
: b < e ? a < e ? a : e
: c < b ? c : b
: b < c ? a < e ? a < c ? e < c ? e : c
: d < a ? d : a
: e < c ? a < c ? a : c
: d < e ? d : e
: d < e ? b < d ? a < d ? a : d
: e < b ? e : b
: b < e ? a < e ? a : e
: d < b ? d : b
: d < c ? a < d ? b < e ? b < d ? e < d ? e : d
: c < b ? c : b
: e < d ? b < d ? b : d
: c < e ? c : e
: c < e ? a < c ? b < c ? b : c
: e < a ? e : a
: a < e ? b < e ? b : e
: c < a ? c : a
: a < c ? b < e ? b < c ? e < c ? e : c
: d < b ? d : b
: e < c ? b < c ? b : c
: d < e ? d : e
: d < e ? a < d ? b < d ? b : d
: e < a ? e : a
: a < e ? b < e ? b : e
: d < a ? d : a;
}
</code></pre>
|
How to corretly load DataContext of Conditional Linq-to-SQL Stored Proc <p>I have a Stored Proc that do a validation on a parameter</p>
<p>ex.</p>
<pre><code>IF @SearchType = 'BNa'
BEGIN
... DO something
END
ELSE IF @SearchType = 'SNa'
BEGIN
... DO something
END
</code></pre>
<p>So by default the Stored Proc return a scalar value and if SearchType = something valid it will return a IMultipleValues.</p>
<p>The problem is that when I drop my Stored Proc in the DataContext designer, it creates the LINQ-to-SQL for a function that only returns a scalar int. It doesn't understands that the Strored Proc could return a IMultipleResults with a scalar value and a DataSet.</p>
<p>Anyone know how to made LINQ-to-SQL to extrapolate the possible return values?</p>
| <p>I can't answer your question directly, but have you tried using SQL Profiler to work out how the designer retrieves the metadata for your stored procedure? </p>
<p>I'm thinking that in your situation it may not be possible for the designer to figure things out for you. SQL Profiler will let you figure this out for sure either way...</p>
<p>I've had quite a positive experience with using SqlMetal (instead of the designer). To save you Googling the documentation is at <a href="http://msdn.microsoft.com/en-us/library/bb386987.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb386987.aspx</a>.</p>
<p>One of the ways you can use SqlMetal is:</p>
<ol>
<li>Run SqlMetal to extract database metadata to a DBML file. </li>
<li>Run some custom processing on the DBML file (which is easy to do as it's just XML). </li>
<li>Run SqlMetal again to turn the updated DBML into code.</li>
</ol>
<p>Using this approach, you could correct the metadata being used for your stored procedure (assuming it can't be determined correctly).</p>
<p>The winning thing about this approach for me is that you can modify your database whenever you need to, and easily regenerate the matching strongly typed code, while still retaining a high degree of control over what is generated.</p>
|
Stored procedure name tagging <p>Ever wonder what wikipedia's database schema looks like? I recently read this thread from <a href="http://www.reddit.com/r/programming/comments/7r3mg/ever_wonder_what_the_wikipedia_database_schema/" rel="nofollow">reddit</a>. </p>
<p>I like how their tables are tagged with a prefix so you can sort of tell its functionality, purpose, and relationship with other tables right off the bat. </p>
<p>One thing I do not notice is how they name their stored procedures. Do they even use SP? </p>
<p>I use MS SQL Server. Prefixing all stored procedures with USP_ or SP_ seems redundant and anti-beneficial as the object explorer already sorts it all out for me. How do you name your SPs?</p>
| <blockquote>
<p>I like how their tables are tagged with a prefix so you can sort of tell its functionality, purpose, and relationship with other tables right off the bat</p>
</blockquote>
<p>That is why you have Schemas in SQL Server, you create a schema to group several object together and then you can give the HR person just access to the HR schema</p>
<blockquote>
<p>Prefixing all stored procedures with USP_ or SP_ seems redundant and anti-beneficial as the object explorer already sorts it all out for me. How do you name your SPs?</p>
</blockquote>
<p>SP_ should never be use because you will get a performance hit, whenever SQL server 'sees' a proc that starts with sp_ it will check the master database first, worst if MS decided to ship a proc with the sane name as yours and it starts with sp_ yours will never get executed</p>
<p>BTW not everyone is using the project explorer, some people like to do this in T-SQL</p>
|
Limiting access to a WCF REST (webHttpBinding) Service using the ASP.NET Membership Provider? <p>I have found a lot of material on the web about using the ASP.NET Membership Provider with the wsHttpBindings, but I haven't seen any reference to using it with webHttpBindings.</p>
<p>I am looking for a system that will work in two scenarios:</p>
<ol>
<li>The user is logged into an asp.net website and the website is making calls to the service.</li>
<li>The user accesses the service directly via REST.</li>
</ol>
<p>Is this possible using the built in framework (i.e. just through configuration)? If so how do I configure the service? And how does the user pass the credentials to the REST service? </p>
| <p>The best source I've found is here: <a href="http://www.leastprivilege.com/FinallyUsernamesOverTransportAuthenticationInWCF.aspx" rel="nofollow">http://www.leastprivilege.com/FinallyUsernamesOverTransportAuthenticationInWCF.aspx</a></p>
<p>The site also has tons of other information about setting up HTTP Modules to handle basic authentication (which I'm guessing you'll be using since it is kind of the standard).</p>
<p>The HTTP Module authentication method is located on Codeplex with sample code and everything here: <a href="http://www.codeplex.com/CustomBasicAuth" rel="nofollow">http://www.codeplex.com/CustomBasicAuth</a></p>
|
How can I use Flex to access foreign-keyed fields in Django? <p>I have the following Django and Flex code:</p>
<p><strong>Django</strong></p>
<pre><code>class Author(models.Model):
name = models.CharField(max_length=30)
class Book(models.Model):
title = models.CharField(max_length=30)
author = models.ForeignKeyField(Author)
</code></pre>
<p><strong>Flex</strong></p>
<pre><code>package com.myproject.models.vo
{
[Bindable]
[RemoteClass(alias="myproject.models.Book")]
public class BookVO
{
public var id:int;
public var title:String;
public var author: AuthorVO;
}
}
</code></pre>
<p>As you can see in this example, Author is a foreign key in my Book model. Now I'd like to acccess the author's name when I call my BookVO in Flex. As such, I'd expect code like the following to work, but "author_name" results in a null:</p>
<pre><code>var book = new BookVO();
var author_name = book.author.name;
</code></pre>
<p>I realize I could call an AuthorVO directly, but the crux of this question is how can you retrieve foreign-keyed values using Flex when your VOs are bound to a remote object? I'm currently using PyAMF to bridge the gap between Flex and Django, but I'm not sure that's relevant.</p>
| <p>Ok, Here's an example...</p>
<p>Model: </p>
<pre><code>class Logger(models.Model):
lname = models.CharField(max_length=80)
def __unicode__(self):
return self.lname
#
#
class DataSource(models.Model):
dsname = models.CharField(max_length=80)
def __unicode__(self):
return self.dsname
#
#
class LoggedEvent(models.Model):
# who's data is this?
who = models.ForeignKey(Logger)
# what source?
source = models.ForeignKey(DataSource)
# the day (and, for some events also the time)
when = models.DateTimeField()
# the textual description of the event, often the raw data
what = models.CharField(max_length=200)
# from -1.0 to 1.0 this is the relative
# importance of the event
weight = models.FloatField()
def __unicode__(self):
return u"%2.2f %s:%s - %s" % (self.weight, self.source, self.who, self.what)
#
#
</code></pre>
<p>Here's my amfgateway.py</p>
<pre><code>def fetch_events(request, source):
events = LoggedEvent.objects.select_related().all()
return events
#
services = {
'recall.fetch_events': fetch_events,
}
gateway = DjangoGateway(services)
</code></pre>
<p>and here's my Actionscript for the receiving side of the AMF call:</p>
<pre><code>protected function onRetrievedEvents(result: Object): void {
for each(var evt: Object in result) {
var who: Object = evt._who_cache.lname;
...
</code></pre>
<p>The evt._who_cache.lname is populated with the select_related() and missing when the select related is missing. If I get rid of the select_related() call, then I see the error:</p>
<pre><code>TypeError: Error #1010: A term is undefined and has no properties.
</code></pre>
<p>You must be trying a different technique with your RemoteClass... so the select_related might not be the problem at all... (otherwise my first answer wouldn't have gotten negged.) The rest is up to you.</p>
|
Is BCrypt a good hashing algorithm to use in C#? Where can I find it? <p>I have read that when hashing a password, many programmers recommend using the BCrypt algorithm. </p>
<p>I am programming in C# and is wondering if anyone knows of a good implementation for BCrypt? I found <a href="http://derekslager.com/blog/posts/2007/10/bcrypt-dotnet-strong-password-hashing-for-dotnet-and-mono.ashx">this page</a>, but I don't really know if it is bogus or not. </p>
<p>What should I be aware of when choosing a password hashing scheme? Is BCrypt a 'good' implementation?</p>
| <p>First, some terms that are important:</p>
<p><strong><a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">Hashing</a></strong> - The act of taking a string and producing a sequence of characters that cannot be reverted to the original string.</p>
<p><strong><a href="http://en.wikipedia.org/wiki/Symmetric-key_algorithm">Symmetric Encryption</a></strong> - (Usually just referred to as 'encryption') - The act of taking a string and producing a sequence of characters that <strong>can</strong> be decrypted to the original string through the use of the same encryption key that encrypted it.</p>
<p><strong><a href="http://en.wikipedia.org/wiki/Rainbow_table">Rainbow Table</a></strong> - a lookup table that contains all variations of characters hashed in a specific hashing algorithm.</p>
<p><strong><a href="http://en.wikipedia.org/wiki/Salt_%28cryptography%29">Salt</a></strong> - a known random string appended to the original string before it is hashed.</p>
<p>For the .NET Framework, Bcrypt does not yet have a <em>verified</em> reference implementation. This is important because there's no way to know if there are serious flaws in an existing implementation. You can get an implementation of <a href="http://bcrypt.codeplex.com/">BCrypt for .NET here</a>. I don't know enough about cryptography to say whether it's a good or bad implementation. Cryptography is a very deep field. <strong>Do not attempt to build your own encryption algorithm</strong>. Seriously. </p>
<p>If you are going to implement your own password security (sigh), then you need to do several things: </p>
<ol>
<li>Use a <a href="http://en.wikipedia.org/wiki/Crypt_%28Unix%29#Blowfish-based_scheme">relatively secure hash algorithm</a>.</li>
<li>Salt each password before it's hashed.</li>
<li>Use a <a href="http://en.wikipedia.org/wiki/Rainbow_table#Defense_against_rainbow_tables">unique and long salt for each password</a>, and store the salt with the password.</li>
<li><strong>Require strong passwords</strong>.</li>
</ol>
<p>Unfortunately, even if you do all this, a determined hacker still could potentially figure out the passwords, it would just take him a really long time. That's your chief enemy: <strong>Time</strong>.</p>
<p>The <a href="http://codahale.com/how-to-safely-store-a-password/">bcrypt algorithm works because it takes <em>five</em> orders of magnitude longer to hash a password than MD5</a>; (and still much longer than AES or SHA-512). It forces the hacker to spend a lot more time to create a rainbow table to lookup your passwords, making it far less likely that your passwords will be in jeopardy of being hacked.</p>
<p>If you're salting and hashing your passwords, and each salt is different, <a href="http://www.codinghorror.com/blog/2007/09/rainbow-hash-cracking.html">then a potential hacker would have to create a rainbow table for each variation of salt</a>, just to have a rainbow table for one salted+hashed password. That means if you have 1 million users, a hacker has to generate 1 million rainbow tables. If you're using the same salt for every user, then the hacker only has to generate 1 rainbow table to successfully hack your system.</p>
<p>If you're not salting your passwords, then all an attacker has to do is to pull up an existing Rainbow table for every implementation out there (AES, SHA-512, MD5) and just see if one matches the hash. This <a href="https://crackstation.net/hashing-security.htm">has already been done</a>, an attacker <em>does not need to calculate these Rainbow tables themselves</em>.</p>
<p>Even with all this, <a href="http://programmers.stackexchange.com/questions/46716/what-technical-details-should-a-programmer-of-a-web-application-consider-before">you've got to be using good security practices</a>. If they can successfully use another attack vector (XSS, SQL Injection, CSRF, <a href="https://www.owasp.org/index.php/Category:Attack">et. al.</a>) on your site, good password security doesn't matter. That sounds like a controversial statement, but think about it: If I can get all your user information through a SQL injection attack, or I can get your users to give me their cookies through XSS, <a href="https://www.schneier.com/essay-028.html">then it doesn't matter how good your password security is</a>.</p>
<p>Other resources:</p>
<ol>
<li>Jeff Atwood: <a href="http://www.codeproject.com/KB/security/SimpleEncryption.aspx?fid=172899&df=90&mpp=10&noise=2&sort=Position&view=Expanded&fr=91">.NET Encryption Simplified</a> (great for an overview of hashing)</li>
<li>Jeff Atwood: <a href="http://www.codinghorror.com/blog/2009/05/i-just-logged-in-as-you-how-it-happened.html">I just logged in as you</a></li>
<li>Jeff Atwood: <a href="http://www.codinghorror.com/blog/2007/09/youre-probably-storing-passwords-incorrectly.html">You're probably storing passwords incorrectly</a></li>
<li>Jeff Atwood: <a href="http://www.codinghorror.com/blog/2012/04/speed-hashing.html">Speed Hashing</a></li>
</ol>
<p><strong>Note:</strong> Please recommend other good resources. I've must have read a dozen articles by dozens of authors, but few write as plainly on the subject as Jeff does. Please edit in articles as you find them.</p>
|
Why are request cookie poperties null or incorrect on ASP.NET postback? <p>I'm debugging the HttpContext.Current.Request.Cookie values in an ASP.NET web application, and finding the only property correctly populated is the Value. The Domain and Path are null, and the Expires value is set to DateTime.Min.</p>
| <p>Those values are not available in the Request.Cookies collecton. They are only used when you are "setting" the value. You can verify this with a network trace. In the request headers, the client browser only sends the name/value pairs in the "Cookie" header.</p>
|
Best way for users to import to a database? <p>I know this isn't a unique issue but I've not had much luck finding examples of how others have addressed this issue. I have an intranet asp.net application I have inherited and am building upon. One particular page is for data entry to submit a claim for approval and we have a form where one record at a time can be entered and it is validated in realtime against the database for valid product information.</p>
<p>I have been asked to add a feature where users can import a large number of records all at once to save them time of going through each text box and dropdown list one at a time for over 100 records sometimes.</p>
<p>The solution I've looked into as my first option is to create an excel spreadsheet they can open from a link on the page that I have formatted into a template that they can copy/paste their data into, save and then upload to the server and import as a linked server object into sql server.</p>
<p>Due to the nature of this solution and some of the data being imported I have to program some error handling into VB for the spreadsheet and if I ever find a bug to fix, there is no good way to guarentee the user is going to use the version on the page and not some local copy they saved that may break when trying to import.</p>
<p>I've ruled out one big text box that I attempt to parse because I have no control that way over how the user enters the data.</p>
<p>Is there some better and possibly more obvious solution that I am missing?</p>
| <p>Uncontrolled spreadsheet import processes are a bad thing. There are too many things that users can do to break the process. If you're going to bulk load from spreadsheets, the process should consist of the following components:</p>
<ul>
<li><p>A controlled template file,
downloaded by the user and generated
from the application (if the template
doesn't need to be changed, it can
just live in a folder somewhere).</p></li>
<li><p>A check to ensure that the template
has been used.</p></li>
<li><p>The actual load process. </p></li>
<li><p>A screen where the user can verify
what they have imported, edit and
commit the upload.</p></li>
</ul>
<p>The check and validate part is a good way to place a control on the upload that can validate data. The user has to inspect the imported data and manually approve it. This puts the onus for correctness back on the users, and empowers them to see and fix the upload. </p>
|
Cell Format Strings for Reporting Services/Dundas Charts <p>Reporting services use format strings to auto format cell data. For example "c2" formats a cell to be displayed as currency with a decimal precision of 2.</p>
<p>Does anyone know where I'd find a comprehensive list off all the different formats available?</p>
| <p>Reporting Services uses the .Net formatting strings. So you can look them up on MSDN. Here is a link to the <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k(VS.95).aspx" rel="nofollow">standard codes</a> and here is the reference for creating <a href="http://msdn.microsoft.com/en-us/library/0c899ak8(VS.95).aspx" rel="nofollow">custom codes</a>.</p>
<p>A standard code is one like "C2" you gave as an example and the advantage is that it's "aware" of you're Regional Settings. So C2 in the US is formatted differently to C2 in Japan.</p>
<p>A custom code allows you to roll your own. e.g. "#,##0.0" will format a number to one decimal place with thousands seperator and will have a leading 0 if the value is between 1 and -1. With a custom string you can also have seperate formatting if it's positive, negative or 0.</p>
|
Windows Service or Task Scheduler for maintenance tasks? <p>I have a C# Application that does some maintenance tasks. It needs to run roughly every hour, although it's not too important if it's a bit off. And it has to run on a Win2003 Server with no one logged in.</p>
<p>Basically I wonder if I should write a Windows Service, and if yes, if Thread.Sleep() is a proper way to pause the Thread for an hour, or if there are better ways to make sure the Thread stays idle and does not put any server load? (aka. what is the most opposite of a Spinlock)</p>
<p>The alternative is the Windows Task Scheduler, but I am not sure if that is good for server use since a) i'd have to store the schedule in it rather than in my app.config, b) I cannot easily control the service through start/stop/restart and c) I do not know if the Credentials of the Windows User are as secure as when I enter it in the Service MMC Snapin.</p>
<p>What are your opinions? Is it possible and good to have an idle Service or would you recommend the task scheduler instead?</p>
| <p>You may find this <a href="http://channel9.msdn.com/shows/Going+Deep/Chittur-Subbaraman-Inside-Windows-7-Service-Controller-and-Background-Processing/" rel="nofollow" title="Service Controller">video</a> interesting . Good interview with the engineer responsible for windows services and also goes into when to pick service or task. In a nutshell if your feature falls into the periodic maintenance category go with a task.</p>
|
How to add a file selector/opener in cocoa with Interface Builder? <p>I'm wondering how to make a button or input field in Interface Builder react in such a way that on click it opens a file dialog and lets you select one or more files and puts them into a specified array/table...</p>
<p>Once the button is pushed and files are chosen (this seems a like quite trivial thing) I guess it will already contain some sort of array (like an array with paths to the selected files) so I've got that covered.. I only need to know how to link the button to a file selector and in what way the file selector delivers the files to me (or paths to the files) so I can redirect them to the array</p>
<p>Is there an easy way to do this, and more importantly; is there a file selector thingie or do I have to do this with XCode instead of Interface builder?</p>
<p>thanks...</p>
<p>ps. I'm sorry if this isn't the right site to ask these questions</p>
| <p>This must be done in Xcode. The code <a href="http://ekle.us/index.php/2006/12/displaying_a_file_open_dialog_in_cocoa_w">here</a> should work fine.</p>
<p>Just hook the button up with a method using IB and use that example as a guide of what to put in the method.</p>
<p>There's also all sorts of good help WRT NSOpenPanel at <a href="http://www.cocoadev.com/index.pl?NSOpenPanel">Cocoadev</a>, including tips on opening the panel as a sheet instead of a modal window.</p>
<p>Of course you should always read the <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSOpenPanel_Class/Reference/Reference.html">Apple documentation</a> as well.</p>
|
Setting up multiple development environments'm <p>I'm a solo developer working on a typical web project (Django + PostgresSQL) using Eclipse as my IDE and Subversion for source control. So far I've been working on a single development machine that I have setup myself. Recently, I've been asked to do some work at the customer site and there have also been a few occasions when it would have been useful to have access to the site at home. I'm thinking about what the best way to set this up is. Unfortunately, for various reasons a laptop is not a viable solution, so the solutions I am thinking of are:</p>
<ol>
<li>Installing all the necessary development tools on each machine (PostgresSQL, Eclipse, Django, Python + librariries etc.) and keeping the code in sync using SVN.</li>
<li>Setting some kind of VNC access on my development machine and accessing it remotely to do work.</li>
<li>Creating a Virtual machine and copying the image between all the machines using a pen drive.</li>
</ol>
<p>The advantage of #1 is fast local development, but then I have to setup all the tools on each machine and deal with their configurations and keeping everything in sync. Also, to share code between the machines, I'd have to check it into SVN even if it's not "ready." Solution #2 solves this problem, but at the expense of slower UI experience. Finally, #3 seems like a nice solution, but I'm not sure if I can really fit a virtual image on a pen drive and I'm not sure about the performance.</p>
<p>I guess there's not really a "correct" answer, but I'm throwing this out to get ideas and suggestions from people who have been doing this longer than me. :)</p>
| <p>I'd say option number 1 is still the best. I'd assume you only have one computer at home and you can work off of that one, so the setup should hopefully just be a one time thing.</p>
<p>You're right though, the setup time is quite tedious, however it does in fact make up for the slow UI of using something like VNC to work remotely. Your problem with committing code that may not work is a valid one, however if you're concerned about that, simply comment out the broken code and ensure that your latest version compiles.</p>
<p>Working through a repository is the most efficient method, especially if you're working on a fairly large project. It's too bad you don't have a laptop, setting up all the tools on a laptop makes coding/working from anywhere (provided you have an internet connection) especially convenient.</p>
<p>Anyways, option 1 is my preference, I hope it helps.</p>
|
What's the maximum number of threads in Windows Server 2003? <p>Does anyone know? And a bigger question is what happens when you encounter this maximum? Is this the same number with other Windows OSs such as Vista, XP etc.?</p>
| <p>First I would advise reading this:
<a href="http://blogs.msdn.com/oldnewthing/archive/2007/03/01/1775759.aspx">http://blogs.msdn.com/oldnewthing/archive/2007/03/01/1775759.aspx</a></p>
<p>then <a href="http://blogs.msdn.com/oldnewthing/archive/2005/07/29/444912.aspx">http://blogs.msdn.com/oldnewthing/archive/2005/07/29/444912.aspx</a></p>
<p>To summarise, the limitation is normally stack space (which must be in contiguous blocks) and since every thread consumes this scattered about you rapidly run out of contiguous blocks.
On 64 bit machines and operating systems this is much less of a problem.</p>
<p>Mitigation strategies exist but will only go so far (and rely on you not using much stack per thread)</p>
<p>As a rough guide: </p>
<ul>
<li>creating tens is almost certain to work</li>
<li>hundreds is probable on current server and desktop hardware but risky</li>
<li>thousands will almost certainly fail.</li>
</ul>
<p>You likely shouldn't need to create more than ten anyway (and if you really <strong>do</strong> need to you should know this information already)</p>
|
How many threads is too many? <p>I am writing a server, and I branch each action of into a thread when the request is incoming. I do this because almost every request makes database query. I am using a threadpool library to cut down on construction/destruction of threads.</p>
<p>My question is though - what is a good cutoff point for I/O threads like these? I know it would just be a rough estimate, but are we talking hundreds? thousands?</p>
<hr>
<h3>EDIT:</h3>
<p>Thank you all for your responses, it seems like I am just going to have to test it to find out my thread count ceiling. The question is though: how do I know I've hit that ceiling? What exactly should I measure?</p>
| <p>Some people would say that <em>two</em> threads is too many - I'm not quite in that camp :-)</p>
<p>Here's my advice: <em>measure, don't guess.</em> One suggestion is to make it configurable and initially set it to 100, then release your software to the wild and monitor what happens.</p>
<p>If your thread usage peaks at 3, then 100 is too much. If it remains at 100 for most of the day, bump it up to 200 and see what happens.</p>
<p>You <em>could</em> actually have your code itself monitor usage and adjust the configuration for the next time it starts but that's probably overkill.</p>
<hr>
<p><em>For clarification and elaboration:</em></p>
<p>I'm not advocating rolling your own thread pooling subsystem, by all means use the one you have. But, since you were asking about a good cut-off point for threads, I assume your thread pool implementation has the ability to limit the maximum number of threads created (which is a good thing).</p>
<p>I've written thread and database connection pooling code and they have the following features (which I believe are essential for performance):</p>
<ul>
<li>a minimum number of active threads.</li>
<li>a maximum number of threads.</li>
<li>shutting down threads that haven't been used for a while.</li>
</ul>
<p>The first sets a baseline for minimum performance in terms of the thread pool client (this number of threads is always available for use). The second sets a restriction on resource usage by active threads. The third returns you to the baseline in quiet times so as to minimise resource use.</p>
<p>You need to balance the resource usage of having unused threads (A) against the resource usage of not having enough threads to do the work (B).</p>
<p>(A) is generally memory usage (stacks and so on) since a thread doing no work will not be using much of the CPU. (B) will generally be a delay in the processing of requests as they arrive as you need to wait for a thread to become available.</p>
<p>That's why you measure. As you state, the vast majority of your threads will be waiting for a response from the database so they won't be running. There are two factors that affect how many threads you should allow for.</p>
<p>The first is the number of DB connections available. This may be a hard limit unless you can increase it at the DBMS - I'm going to assume your DBMS can take an unlimited number of connections in this case (although you should ideally be measuring that as well).</p>
<p>Then, the number of threads you should have depend on your historical use. The minimum you should have running is the minimum number that you've ever had running + A%, with an absolute minimum of (for example, and make it configurable just like A) 5.</p>
<p>The maximum number of threads should be your historical maximum + B%.</p>
<p>You should also be monitoring for behaviour changes. If, for some reason, your usage goes to 100% of available for a significant time (so that it would affect the performance of clients), you should bump up the maximum allowed until it's once again B% higher.</p>
<hr>
<p><em>In response to the "what exactly should I measure?" question:</em></p>
<p>What you should measure specifically is the maximum amount of threads in concurrent use (e.g., waiting on a return from the DB call) under load. Then add a safety factor of 10% for <em>example</em> (emphasised, since other posters seem to take my examples as fixed recommendations).</p>
<p>In addition, this should be done in the production environment for tuning. It's okay to get an estimate beforehand but you never know what production will throw your way (which is why all these things should be configurable at runtime). This is to catch a situation such as unexpected doubling of the client calls coming in.</p>
|
How make scrolling function with Interface builder on the iPhone? <p>I wonder how is possible to make a view scroll, like in a table view.</p>
<p>I have a form that have several fields on it. I don't wanna buil it as a traditional table that drill-down.</p>
<p>Is not very large but because the main windows is a tab-bar I lack of a bit of vertical space. Also, when I try to fill a textfield get covered by the keywoard and I want that the focus move to the field and the view scrool, like in the safari way.</p>
| <p>Select the main form view in Interface Builder and choose Layout > Embed Objects in > Scroll View from the menu. You may have to adjust some connections to make everything work.</p>
|
Castle ActiveRecord, Web Project, and the Bin folder <p>Which assemblies are necessary to add to the Bin folder for ASP.NET 3.5 project that is going to use Castle ActiveRecord? </p>
<p>Is it:<br />
Castle.ActiveRecord.dll<br />
Castle.Core.dll<br />
Iesi.Collections.dll<br />
NHibernate.dll<br />
log4net.dll </p>
<p>What else is needed? </p>
| <p>For Castle RC3, you're missing Castle.DynamicProxy.dll and Castle.Components.Validator.dll</p>
|
How to build a kind of firewall <p>Actually what i am trying to build is like a kind of firewall. It should be able to get to know all the requests going from my machine. It should be able to stop selected ones. I am not sure how to even start about with this. I am having VS 2008/2005 with framework 2.0. Please let me know if there is any particular class i can start with and is there any samples i can get. </p>
| <p>Firewalls really should be implemented fairly low in the networking stack; I'd strongly suggest NDIS. <a href="http://www.codeproject.com/KB/IP/drvfltip.aspx" rel="nofollow">This article</a> may be of interest.</p>
|
is there some dojo.fx.sleep function to use within a dojo.fx.chain animation? <p>I would like to <code>fadeIn</code> a node over one second. Then leave it on for 10 seconds. Then <code>fadeOut</code> for another 3 seconds. One way of chaining this would be as follows:</p>
<pre><code>dojo.fx.chain([
dojo.fadeIn({node:myNode, duration:1000}), // fading in for 1 second
dojo.fadeIn({node:myNode, duration:10000}), // this does nothing for 10 seconds
dojo.fadeOut({node:myNode, duration:3000}) // fade out for 3 seconds
]).play();
</code></pre>
<p>In the previous code, the middle step is a very silly way of achieving nothing. Is there some sort of <code>dojo.fx.sleep</code> animation that does nothing for a specified length of time?</p>
| <p>Positive there isn't at this point in time; the only way to achieve the effect is to split your code into pre-sleep and post-sleep sections, which you've pretty much done here. The only thing I'd recommend is having Dojo do as little as possible during the 1o,ooo-millisecond duration; as you have it now, the <strong>fadeIn()</strong> method is being called and, while probably negligible, the fact that it is running at least one conditional statement (to check whether or not it needs to modify an opacity property), it is definitely a bit slower than just having the script do nothing.</p>
|
How to add a TabBar to NavigationController based iPhone app <p>I have a simple NavigationController based app. The main window shows a TableView and selecting an item loads a sub-view. I used Interface Builder for UI views.</p>
<p>Now I want to add a TabBar to the app. Where do I put it? Do I need a TabBarController? Should it go in the MainWindow.xib, or RootViewController.xib?</p>
<p>How do I tie it together with my NavigationController?</p>
| <p>The <em>definitive</em> answer to this question is presented in the iPhone SDK documentation in the <em>View Controller Programming Guide for iPhone</em>.</p>
<p><a href="http://developer.apple.com/iphone/library/featuredarticles/ViewControllerPGforiPhoneOS/CombiningViewControllers/CombiningViewControllers.html#//apple_ref/doc/uid/TP40007457-CH104-SW2" rel="nofollow" title="View Controller Programming Guide: Combining View Controllers">View Controller Programming Guide: Combining View Controllers</a></p>
<p>This link goes straight to the section and includes a discussion of the correct ways to create navigation and tab bar-based interfaces.</p>
|
How can I send a NULL in Ruby Sockets? <p>I'm working on a socket app in Ruby Shoes, and want to send a message to the server. The server expects the XML message, and then a null (0) character.</p>
<p>How can I send that in TCP Sockets in Ruby?</p>
<p>Thanks.</p>
| <p>I found my own answer... The problem was not sending the NULL, it was a thread issue.</p>
<p>You can send a NULL as part of a string by just concatenating it on to the end of the string...</p>
<p>NULL = "\000"</p>
<p>...
tc = tc + "</endtag>"</p>
<p>tc = tc + NULL</p>
<p>Socket.send(tc, 0)</p>
|
preg_match works in regexbuddy, not in php <p>Ok so I have this regex that I created and it works fine in RegexBuddy but not when I load it into php. Below is an example of it.</p>
<p>Using RegexBuddy I can get it to works with this:</p>
<pre><code>\[code\](.*)\[/code\]
</code></pre>
<p>And checking the dot matches newline, I added the case insensitive, but it works that way as well.</p>
<p>Here is the php:</p>
<pre><code>$q = "[code]<div>html code to display on screen</div>[/code]";
$pattern = '/\[code\](.*)\[/code\]/si';
$m = preg_match($pattern, $q, $code);
</code></pre>
<p>So you can see I am using [code][/code] and then once I can extract this I will run htmlentities() on it to display instead of render html code.</p>
| <p>You're including the forward slash in the middle of your pattern (/code). Either escape it or delimit your pattern with something else (I prefer !).</p>
|
PhysX NxActor Question <p>As far as I know, using the PhysX API, the only way to obtain an NxActor is from an instance of NxScene using the createActor method. This is really bugging me. I want to keep my code clean, but I feel like there is no choice but to go around passing this scene from constructor to constructor so that classes can make and have references to actors. I suppose that, alternatively, I could make the scene global (eek!), but I don't think global variables are a good idea. One thought I had was to have my classes simply store an NxActorDesc (and have them provide it to the scene to create the actor via message passing), but they really need references to the NxActor so that they can sync their transformations with the actor. </p>
<p>Anyhow, I would like to see what insight others might have. Do you think I am going about this the right way (passing the NxScene all over the place)? It feels kind of icky, but maybe I'm just crazy. If not, how can I sync something such as a Model class with an NxActor in a way that is more elegant? Thanks in advance!</p>
| <p>If you don't want you're objects directly coupled with the Actors I would suggest a different approach. You could come up with a way of registering an object to have physics update it. Then the module that those objects registered with would assign each object to an Actor that would be use to set the information of the objects periodically. This way you have just one module coupled with Actor/PhysX management and the objects just need an interface that allows them to be updated with the physics information.</p>
|
How to customize wordpress "comment error" page <p>If you enter incorrect information into the comment forms (missing name, email etc), wordpress returns an empty page with the relevant error message. I googled, but couldn't find a way to customize this response.</p>
<p>Does anyone know how to do it?</p>
| <p>For this particular problem, I ended up modifying \wp-comments-post.php directly - the theme engine doesn't allow you to customize it.</p>
<p>The short description of what I did is to bypass the usage of "wp_die()" and instead have the script execute "my_wp_die()" in scenarios when the blog comment post does not validate.</p>
<p>Here's a sequential example:</p>
<p>1) User lands on article page (invoking single.php in your theme) <br />
2) User enters some info into the comments fields (may or may not validate) <br />
3) Form posts to "wp-comments-post.php" with the article's URL as a parameter so it can pass back validation results to a page which has the proper visuals (sidebar: I wasn't able to hook in an outside template library I wrote which gets integrated into the theme instead of duplicating my site's template into the theme) and the user form fields. <br />
4) wp-comments-post.php will call <code>my_wp_die()</code> when not validating (includes a dupe check from /comment.php:function <code>wp_allow_comment()</code>), or <code>my_wp_success()</code> if the comment is valid and gets posted. <br />
5) wp-comments-post.php will forward the user back to the article URL (originating permalink).<br />
6) single.php in the theme will display error/success message and new comment.</p>
|
TFS: Hundreds of separate applications/projects - what's the best approach? <p>Let's say that the company has a large number of separate small to medium applications which can be logically divided into a small number of groups.</p>
<p>For example, I can have BMW, Mazda, Honda, Ford .... , Kawasaki, Harley, .... altogether a few dozens or even hundreds of applications.</p>
<p>I think I have 2 options in TFS:</p>
<ol>
<li><p>Create a separate project for each application. I end up with lots of small projects and can be hit by the limit, but the benefit is that I can have all workitems, bugs, reports etc. assigned separately to each project and have a portal for each project.</p></li>
<li><p>Create a project 'Cars' and a project 'Motorcycles', and create a source control tree with a branch for each application under each project. That will provide a better structure and less overhead, but I cannot have a portal and a list of workitems, bugs, reports etc. separately for 'Honda' and separately for 'BMW' anymore.</p></li>
</ol>
<p>Am I missing something? Is there a way to have both - a separate list of workitems, bugs for each small project without the overhead of creating heaps of projects with the risk of hitting the TFS limit on the number of projects?</p>
| <p>I would go with point 2. You can use the 'Areas' section of TFS to assign work items to a particular sub-project. </p>
<p>There is way too much overhead in creating full Team Projects for all those small apps. Does each of those apps need a completely independent life cycle, collaboration tool (WSS site) and set of reports? Usually not. </p>
<p>Worst case you can then create a new team project for any of them if it gets too big to manage, because when you create projects and get to the source control screen, there is an option to 'branch from existing project' so you could just use that to keep your source history and create a dedicated project. </p>
<p>Start agile, scale as needed.</p>
|
iPhone development - memory release issue <p>I am running into this issue of releasing an already released object but can't for the life of me find out where the error is taking place. I have added NSZombieEnabled flag and this is the log I get in gdb. Can someone please tell me how to go about resolving this issue or rather finding out where the error occurred.</p>
<pre><code>*** -[CFString release]: message sent to deallocated instance 0x5e4780
(gdb) where
#0 0x952ff907 in ___forwarding___ ()
#1 0x952ffa12 in __forwarding_prep_0___ ()
#2 0x9260e20f in NSPopAutoreleasePool ()
#3 0x30a564b0 in _UIApplicationHandleEvent ()
#4 0x31563dea in SendEvent ()
#5 0x3156640c in PurpleEventTimerCallBack ()
#6 0x95280615 in CFRunLoopRunSpecific ()
#7 0x95280cf8 in CFRunLoopRunInMode ()
#8 0x31564600 in GSEventRunModal ()
#9 0x315646c5 in GSEventRun ()
#10 0x30a4ec98 in -[UIApplication _run] ()
#11 0x30a5a094 in UIApplicationMain ()
#12 0x00002494 in main (argc=1, argv=0xbfffef9c) at /Users/adminUser/Projects/MyProject/main.m:14
</code></pre>
<p>Thanks.</p>
| <p>The autorelease pool is trying to release an object which already released. </p>
<p>This can happen if you manually release an object registered for autorelease</p>
<pre><code>NSString* foo = [NSString stringWithFormat:@"foo:%d",42];
[foo release]; /* this release is bad, as this object is already
registered for autorelease */
</code></pre>
<p>You can use the following method, to find the point of allocation:</p>
<ol>
<li>Set <a href="http://developer.apple.com/documentation/Performance/Conceptual/ManagingMemory/Articles/MallocDebug.html" rel="nofollow">MallocStackLogging, MallocStackLoggingNoCompact</a> environments to 1.</li>
<li>Run the program and once it breaks into gdb use <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/malloc_history.1.html" rel="nofollow">malloc_history</a> from shell to find out the stack trace of the allocation: <code>malloc_history <pid> <addr></code>. (NSZombieEnabled will print out the address in gdb)</li>
</ol>
<p>Another option (that is less likely to slow down your runtime performance) is to use the Instruments tool with the "Zombies" template. It will track zombies and also tell you the history of a zombie without having to use the malloc_history command.</p>
|
How do I convert a string to a double in Python? <p>I would like to know how to convert a string containing digits to a double.</p>
| <pre><code>>>> x = "2342.34"
>>> float(x)
2342.3400000000001
</code></pre>
<p>There you go. Use float (which is almost always a C double).</p>
|
HttpWebRequest not returning response stream when cache hit, and AllowAutoRedirect == false <p>I have an HttpWebRequest that I've set the CachePolicy to CacheIfAvailable, and I've set AllowAutoRedirect to false.
Now when there is a cache hit, the HttpWebResponse.Status == NotModified, and there is no response stream. I need to know what the cached response is!</p>
<p>If I set the CachePolicy to BypassCache it works just fine. But I need to cache these results.</p>
<p>Can anyone tell me how to retrieve the cached response in the case of a cache hit?</p>
| <p>It turns out that the problem is that I was setting HttpWebRequest.IfModifiedSince (to itself). Yes, the getter for that property is set to always return DateTime.Now, until it is explicitly set. So:
request.IfModifiedSince = request.IfModifiedSince;
is not a safe no-op. It actually sets a flag saying to actually send the If-Modified-Since HTTP header, which was causing my grief.</p>
|
Generate a C# delegate method stub <p>Anyone know how to automatically create a delegate stub method?</p>
<p>In WPF it seems im constantly having to pass delegates around. i would like to be able to type a method name that doesnt exist and have a method stub automatically generated...currently i'am having to constantly reference the docs to get the delegate signature and then manually create method with matching signature.</p>
| <p>Use an IDE plugin like Refactor Pro! It also allows you to convert your delegates to instance methods, or if its a one-liner, into a lambda. I tend to start typing using a lambda and then hovering my cursor over the parms gives you the types available.</p>
<p>Or. Wait till Visual Studio 10 which would have this all built in. But until then use either of the aforementioned :)</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.