instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Does anyone have an example (code or a link) that will allow me to export a gridview template field to excel? Here is an example of what I mean. Assume I have the following GridView Declaration:</p>
<pre><code><asp:GridView Id="gvResults" runat="server">
<Columns>
<asp:TemplateField HeaderText="Contact Info">
<ItemTemplate>
<b>Name:</b><%# Eval("Name") %><br/>
<b>Address:</b><%# Eval("Address") %><br/>
<b>Phone:</b><%# Eval("Phone") %><br/>
<b>E-mail:</b><%# Eval("Email") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</code></pre>
<p>When I export to excel, I want to export the fields in the template field to columns in the excel file, so it will look similar to this:</p>
<p>Name Address Phone E-mail</p>
<p>==== ======= ==== =====</p>
<p>John 123 Rd 40330 J@j.com</p>
<p>Mark 456 St 22039 M@M.com</p>
|
<p>Sure, although it's easier in the fluent syntax:</p>
<pre><code>var query_foo = db.Foo.Where(f=>f.Bar > 5);
// :
var foo =query_foo.Select(f=>SomeMethodThatReturnsEtc(f));
</code></pre>
|
<blockquote>
<p>I guess my real question is, what's
the syntax of the SomeMethod()? –
Jonas (an hour ago)</p>
</blockquote>
<p>The way you want to do it, you can only return "object" from the method.</p>
| 49,192
|
<p>I've got a collection (List<Rectangle>) which I need to sort left-right. That part's easy. Then I want to iterate through the Rectangles in their <em>original</em> order, but easily find their index in the sorted collection. indexOf() won't work, since I may have a number of equal objects. I can't help feeling there should be an easy way to do this.</p>
|
<p>I've found a solution - but perhaps there is a neater/more optimal one out there.</p>
<pre><code>List<Rectangle> originalRects = ...;
/* record index of each rectangle object.
* Using a hash map makes lookups efficient,
* and using an IdentityHashMap means we lookup by object identity
* not value.
*/
IdentityHashMap<Rectangle, Integer> originalIndices = new IdentityHashMap<Rectangle, Integer>();
for(int i=0; i<originalRects.size(); i++) {
originalIndices.put(originalRects.get(i), i);
}
/* copy rectangle list */
List<Rectangle> sortedRects = new ArrayList<Rectangle>();
sortedRects.addAll(originalRects);
/* and sort */
Collections.sort(sortedRects, new LeftToRightComparator());
/* Loop through original list */
for(int i=0; i<sortedRects.size(); i++) {
Rectangle rect = sortedRects.get(i);
/* Lookup original index efficiently */
int origIndex = originalIndices.get(rect);
/* I know the original, and sorted indices plus the rectangle itself */
...
</code></pre>
|
<p>Clone the lists and sort one of them. Having two references of the same object is will not matter too much with indexOf() since the pointers to the same object are the same and you can't tell between them.
If you have two objects that are equal but not identical and you do want to distinguish between them then you do have a problem since indexOf() is using the equal method.
In this case the best solution might be to simply iterate through the list and check for object identity (==).</p>
| 25,360
|
<p>I'll get straight to the point!</p>
<p>My javascript sends about 20 AJAX requests to my PHP file to respond to (via an external web API) when the user submits their search. The results are stored in an array in the session array.</p>
<p>I've read that browsers will only allow 2 simultaneous requests to a server.</p>
<p>My first problem is that while there are still more than one requests still waiting for a response the AJAX "add to basket" request won't work since it's still waiting for the other requests to complete.</p>
<p>My second (and more annoying) problem is that the 2 requests that are being handled simultaneously seem to be over writing each other so that when all the responses are complete only half are in the session array. Either all the odd ones or even ones depending on whether the final request is odd or even.</p>
<p>I'd prefer not to have to send requests individually (ie only send the next when the last has finished) as that would slow things down for the user a fair bit.</p>
<p>Is there a solution to this session overwriting or should I be using a completely different approach altogether?</p>
<p>Thanks all!
<hr />
Edit:<br/>
It's for checking domain availability. The user searches for "mydomain" and results for com, net, org, etc are eventually presented.</p>
<p>Sending a single request and having the script search for all tlds in one go means that a response isn't returned until all results are in. The result for some tlds seem to take upto and over 30 seconds during which the user is getting no feedback save for a swirly icon and "Please Wait" (this is what happens when javascript isn't enabled).</p>
<p>Seperate requests allow me to display the domains availability as they come in.</p>
<p>I'm currently thinking along the lines of sending a single request and then using javascript's setinterval to repeatedly check the session until all results are in.</p>
|
<p>I think you should start refactoring your solution:</p>
<ol>
<li>All the performance guidelines states that you should minimize the number of HTTP requests. 20 is too much</li>
<li>If you have a shared resource you need to lock an unlock the parts you manipulate it to prevent that two or more requests update it at the same time</li>
</ol>
|
<p>Sorry it's not really the answer you're after but 20 requests sounds like far too much for a single search. Having implemented something similar ie. a brief search history stored in the session we opted not to use AJAX at all. There's a time and a place for it but not if it's going to kill your server with requests when your traffic increases.</p>
| 45,461
|
<p>This should be a really really simple thing, but for some reason it is just eluding me.</p>
<p>I want a Sharepoint page which will have a drop down list that is tied to a database lookup table. </p>
<p>When an item is selected and they click a GO button, I want it to update a gridview that is also on the page.</p>
<p>I'm looking for a simple how to - while assuming I'm a sharepoint idiot. BTW, I am using the Microsoft Office Sharepoint Designer.</p>
<p>Thanks,</p>
<p>Edit:
My need is actually very simple. I want to filter the results of a query using a drop down list. This used to be called a master - detail relationship.</p>
<p>For example, my regular data has school name, application name, and how long the application was running. Because there could be a hundred applications per school and there are 60+ schools, I only want to show one schools information at a time.</p>
<p>So, I want to put a drop down list at the top of the screen which contains the list of schools. When one is selected, the gridview should be updated to reflect the new schools information.</p>
<p>Chris.</p>
|
<p>I currently use a drop down tied to one sharepoint list to filter a dataview of another sharepoint List.</p>
<p>The instructions are here:
<a href="http://blogs.msdn.com/sharepointdesigner/archive/2007/03/05/asp-net-controls-filter-the-data-view.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/sharepointdesigner/archive/2007/03/05/asp-net-controls-filter-the-data-view.aspx</a></p>
|
<p>I'm not exactly sure of the specific needs here, but it seems that you are trying to stretch a bit beyond what Sharepoint Designer is well suited to. To look up data, you do have access via the dataview web part, which is here:</p>
<p><a href="http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx" rel="nofollow noreferrer">http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx</a></p>
<p>However your filtering needs may prevent you from using this. If you want to do it .net without knowing too much about MOSS, you can use the "son of smartpart" (google it) which allows you to host standard .net user controls in webparts.</p>
<p>Hope this helps!</p>
| 21,327
|
<p>As part of a wide ranging job for a cystic fibrosis support organization, they'd also like a web site set up and I've decided on Apache running on Linux (due to its security and low cost mostly). Other than (fairly) static content, they also want a forum where people can discuss issues with the condition - it'll be attached to a hospital chain so there'll be plenty of medical staff there who know little about the web.</p>
<p>I can handle all the specific coding and Apache setup since I've done it before but I'm interested in people's opinions as to whether I should roll my own forum software or get a hold of some ready-built stuff. I've not had <strong>any</strong> experience with forum software but I could generate my own (initially buggy, I'm sure) in a month or so.</p>
<p>It'll require registration and login to leave comments (but guest access just to read) and I'd like it to be 'pretty' (excuse me while I remember damning customers for providing similarly vague requirements specs :-) but not necessarily infinitely-configurable with skins/themes/etc.</p>
<p>If anyone has some compelling reasons (and experience with specific products that can provide what I need), I'd be interested in hearing about them. Alternatively, does anyone have any 'gotchas' they experienced while coding their own forum software?</p>
|
<p><strong>Advantages</strong> to rolling your own:</p>
<ul>
<li>a non-standard custom-built system means you'll be less prone to "standard" attacks (e.g.: a vulnerability in PunBB) since bad guys tend to bother with exploit-hunting only on widely-deployed systems (more return on their investment)</li>
<li>absolute control over how your system works and looks</li>
<li>you'll learn a lot</li>
</ul>
<p><strong>Disadvantages:</strong></p>
<ul>
<li>you'll repeat mistakes other people have already solved</li>
<li>it'll take you longer to get up and running</li>
<li>long-term it'll be more maintenance (since you have to fix bugs & add features yourself).</li>
<li>you can't "leverage the community" -- if you choose an off-the-shelf forum that has a plugin system then there's a whole bunch of community add-ons that won't be available for your custom forum software.</li>
</ul>
<p>There's <a href="http://en.wikipedia.org/wiki/Internet_forum_software" rel="nofollow noreferrer">a GIANT list of forum software on wikipedia</a> -- there's most likely something in there that will suit your needs that you can get up and running quickly.</p>
|
<p>My answer would be: don't reinvent the wheel, there are plenty of fora software out there. My preference would go for <a href="http://rforum.andreas-s.net/" rel="nofollow noreferrer">RForum</a> if you need only that.</p>
| 48,936
|
<p>In the past, when I've worked on long-running C++ daemons I've had to deal with heap fragmentation issues. Tricks like keeping a pool of my large allocations were necessary to keep from running out of contiguous heap space. </p>
<p>Is this still an issue with a 64 bit address space? Perf is not a concern for me, so I would prefer to simplify my code and not deal with things like buffer pools anymore. Does anyone have any experience or stories about this issue? I'm using Linux, but I imagine many of the same issues apply to Windows. </p>
|
<blockquote>
<p>Is this still an issue with a 64 bit address space?</p>
</blockquote>
<p>No, it is not still an issue.</p>
<p>You are correct that it was an issue on 32-bit systems, but it no longer is an issue on 64-bit systems.</p>
<p>The virtual address space is so large on 64-bit systems (2^48 bytes at the moment on todays x86_64 processors, and set to increase gradually to 2^64 as new x86_64 processors come out), that running out of contiguous virtual address space due to fragmentation is practically impossible (for all but some highly contrived corner cases).</p>
<p>(It is a common error of intuition caused by the fact that 64 is "only" double 32, that causes people to think that a 64-bit address space is somehow roughly double a 32-bit one. In fact a full 64-bit address space is 4 billion times as big as a 32-bit address space.)</p>
<p>Put another way if it took your 32-bit daemon <strong>one week</strong> to fragment to a stage where it couldn't allocate an x byte block, than it would take at minimum <strong>one thousand years</strong> to fragment today's x86_64 processors 48-bit address spaces, and it would take <strong>80 million years</strong> to fragment the future planned full 64-bit address space.</p>
|
<p>If your process genuinely needs gigabytes of virtual address space, then upgrading to 64-bit really does instantly remove the need for workarounds.</p>
<p>But it's worth working out how much memory you expect your process to be using. If it's only in the region of a gigabyte or less, there's no way even crazy fragmentation would make you run out of 32-bit address space - memory leaks might be the problem.</p>
<p>(Windows is more restrictive, by the way, since it reserves an impolite amount of address space in each process for the OS).</p>
| 40,648
|
<p>I'm trying to design a form which contains a dropdown box containing a list of grocery item choices. </p>
<p>What criteria should I look at when trying to decide on whether to use a java enum or a lookup table? Also, I will need to plan ahead for i18n support for the dropdown strings.</p>
|
<p>There is a line, somewhere... sharing library code is positively encouraged - but you need to be a <em>little</em> bit careful when apps consume each-other, simply to prevent spaghetti code and circular references.</p>
<p>If the code you mention is really library code (i.e. neither project is the "master" for this data), then it should be fine (versioning issues aside). If it is the case that Project A wants Project B's data, then it usually isn't long before Project B wants Project A's data, and you have a spider web. In such cases, it may be preferable to use an SOA approach; have the projects expose their data via something like a WCF service, so that other projects only call into the public mex/wsdl API (ideally without assembly sharing).</p>
<p>But it is a deceptively complex question, and I don't think any single answer can cater for every scenario.</p>
|
<p>You should share everything (within the limits of common sense of course.) You are a team of developers, not a set of individual developers. Sharing code has numerous benefits: reusability means quicker development, simpler maintenance (you only need to fix a bug once), a new feature or improvement is potentially able to benefit all dependent projects immediately and it means sharing ideas as well. Personally, I have learnt a couple of tricks and good practices from the source code written by my coworkers.</p>
| 27,273
|
<p>Today somebody told me that interface implementation in C# is just "Can-Do" relationship, not "Is-A" relationship. This conflicts with my long-time believing in LSP(Liskov Substitution Principle). I always think that all inheritance should means "Is-A" relationship. </p>
<p>So, If interface implementation is just a "Can-Do" relationship. What if there is a interface "IHuman" and "IEngineer", and one class "Programmer" inherits from "IHuman" & "IEngineer"? Surely, a "Programmer" Is A "IHuman" and A "IEngineer". </p>
<p>If it is just "Can-Do" relationship, does it mean we cannot expect the "Programmer" instance behavior may be different between when treated as a IHuman and treated as IEngineer?</p>
|
<p>In my experience it doesn't really help that much to think of "is-a" and "can-do" relationships. You rapidly get into problems. It's an impedance mismatch between the real world and OO, basically. However much people actually talk about modeling the real world, you fundamentally need to understand what the relationships between types mean on the platform you're using.</p>
<p>Sometimes interfaces can be used as capabilities, and sometimes they can represent more of a normal "is-a" relationship. I wouldn't get too hung up about it - just make sure you understand what they can do and what they can't.</p>
|
<p>The designers of the .NET framework use interfaces to designate a "has a" (or "can do") relationship, whereas "is a" is implemented using inheritance.</p>
<p>The rationale for this can be found in the <a href="http://msdn.microsoft.com/en-us/library/ms229013.aspx" rel="nofollow noreferrer">Choosing Between Classes and Interfaces</a> section of the .NET Framework Developer's Guide:</p>
<blockquote>
<p>An interface defines the signatures for a set of members that implementers must provide. Interfaces cannot provide implementation details for the members.</p>
</blockquote>
<p>So, since your "Programmer" and "Engineer" example classes would most likely come with their own specific functionality, they would be more suitably implementated using inheritance.</p>
| 31,901
|
<p>I'm creating some videos from a collection of images, I subsequently wish to play this video back with java. I found JMF but I haven't been able to find an encoding which is actually playable by it. Does anybody have an ffmpeg or mencoder formulation which produces JMF playable output? I would also take alternatives to JMF if there is something better. </p>
|
<p>According to the <a href="http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/formats.html" rel="nofollow noreferrer">JMF 2.1.1 - Supported Formats</a> page, Quicktime and various codecs are supported for decoding directly.</p>
|
<p>If you're not stuck with JMF, you could try <a href="http://www.xuggle.com/xuggler" rel="nofollow noreferrer">Xuggler</a>. It will encode almost all formats for you (one of the areas JMF just falls down on).</p>
<p>Here's a <a href="http://wiki.xuggle.com/MediaTool_Introduction#How_To_Take_Snapshots_Of_Your_Desktop" rel="nofollow noreferrer">tutorial</a> for Xuggler showing how to create a video file from pre-existing video images.</p>
| 45,359
|
<p>Hey everyone, I'm using Virtual PC and working with a virtual hard disk (*.vhd) that is only sized at 8.2 GB. I would like to double the size to something like 16-20GB. I see options for compacting the VHD but nothing to expand it. It's set to "dynamically expand" but I'm installing some software and it doesn't seem to resize itself to a larger space.</p>
<p>Thanks much.</p>
|
<p><a href="http://vmtoolkit.com/files/folders/converters/entry87.aspx" rel="nofollow noreferrer">VHD Resizer</a></p>
|
<p>Never worked with Virtual PC but from other virtualization software I know I guess that dynamically expand means that initially the .vhd file will take less space in the HD than the specified and will dynamically grow as you keep installing programs or adding files into the virtual drive UP TO the specified size.</p>
<p>For what you want I guess that you will have to modify the specified size in the virtual hard drive from Virtual PC's setup window.</p>
<p>A bit offtopic but give a go to Virtual Box: www.virtualbox.org</p>
| 4,859
|
<p>I am sure to become a scrum master could really add value to the process I am following, however I believe that the background of the area of the application I am working on help more to get better planning and scheduling done for the project</p>
|
<p>I just have an issue with the wording used here - in the question and responses. As a scrum master you would <strong>not</strong> be <strong>managing</strong> the project, or <strong>running</strong> it. The team runs the project in a self-directed way. The scrum master's role is to <strong>facilitate and coach</strong>.</p>
<p>This may seem like semantics, but I often find that our chosen terms shed light on our underlying tendencies - in this case they may indicate a tendency towards command and control vs. facilitating self-directed teams.</p>
<p>I do agree that reading on agile (not just scrum) is helpful. And having been a member of an agile team is incredibly useful in <strong><em>serving</em></strong> as a scrum master. CSM is like the PMP for classic project management (without the test) for agile - not an indicator of ability, but useful for finding jobs with acronym-myopic recruiters and hiring managers. </p>
<p>There are good consultants out there to help, and useful resources online (see the scrumdevelopment group on Yahoo). I suggest you use both liberally.</p>
|
<p>You probably would benefit from becomming a certified scrum master (i recently became one myself).</p>
<p>The scrum master shouldn't 'manage the scrums' but instead be there to facilitate the team - help it remove impediments. The team is self organizing and pretty much manages itself.</p>
| 21,655
|
<p>Under VS's external tools settings there is a "Use Output Window" check box that captures the tools command line output and dumps it to a VS tab.</p>
<p>The question is: <em>can I get the same processing for my program when I hit F5?</em></p>
<p><strong>Edit:</strong> FWIW I'm in C# but if that makes a difference to your answer then it's unlikely that your answer is what I'm looking for.</p>
<p>What I want would take the output stream of the program and transfer it to the output tab in VS using the same devices that output redirection ('|' and '>') uses in the cmd prompt.</p>
|
<p>I'm going to make a few assumptions here. First, I presume that you are talking about printf output from an application (whether it be from a console app or from a windows GUI app). My second assumption is the C language.</p>
<p><em>To my knowledge, you cannot direct printf output to the output window in dev studio, not directly anyway.</em> <sub>[emphasis added by OP]</sub></p>
<p>There might be a way but I'm not aware of it. One thing that you could do though would be to direct printf function calls to your own routine which will</p>
<ol>
<li>call printf and print the string</li>
<li>call OuputDebugString() to print the string to the output window</li>
</ol>
<p>You could do several things to accomplish this goal. First would be to write your own printf function and then call printf and the OuputDebugString()</p>
<pre><code>void my_printf(const char *format, ...)
{
char buf[2048];
// get the arg list and format it into a string
va_start(arglist, format);
vsprintf_s(buf, 2048, format, arglist);
va_end(arglist);
vprintf_s(buf); // prints to the standard output stream
OutputDebugString(buf); // prints to the output window
}
</code></pre>
<p>The code above is mostly untested, but it should get the concepts across.</p>
<p>If you are not doing this in C/C++, then this method won't work for you. :-) </p>
|
<p>System.Diagnostics.Debug.Writeline() or Trace.Writeline()</p>
| 14,938
|
<p>My website is XHTML Transitional compliant <strong>except for one thing</strong>: the & (ampersand) in the URL are written as it is, instead of <code>&amp;</code></p>
<p>That is, all the URLs in my pages are usually like this:</p>
<pre><code><a href="http://www.example.org/page.aspx?x=1&y=2">Foo</a>
</code></pre>
<p>But <a href="http://validator.w3.org/" rel="nofollow noreferrer">XHTML validator</a> generates this error:</p>
<blockquote>
<p>cannot generate system identifier for general entity "y"</p>
</blockquote>
<p>... and it wants the URL to be written like this:</p>
<pre><code><a href="http://www.example.org/page.aspx?x=1&amp;y=2">Foo</a>
</code></pre>
<p>The problem is that Internet Explorer and Firefox don't handle the URL correctly and ignore the y parameter. <strong>How can I make this link work and validate correctly?</strong></p>
<p>It seems to me that it is impossible to write XHTML pages if the browsers don't work with strict encoded XHTML URLs.</p>
<p>Do you want to see in action? See the difference between these two links (copy and paste them as they are):</p>
<pre><code>http://stackoverflow.com/search?q=ff&sort=newest
</code></pre>
<p>and</p>
<pre><code>http://stackoverflow.com/search?q=ff&amp;sort=newest
</code></pre>
|
<p>I have just tried this. What you attempted to do is correct. In HTML if you are writing a link the <code>&</code> characters should be encoded as <code>&amp;</code> You would only encode the <code>&</code> as <code>%26</code> if you wanted a parameter value to contain an ampersand. I just wrote a simple HTML page that contained a link: <code><a href="Default2.aspx?param1=63&amp;param2=hel">Click me</a></code>
and it worked fine: <code>default2.aspx</code> received the parameters intended and the source passed validation.</p>
<p>The encoding of <code>&</code> as <code>&amp;</code> is required in HTML, not in the link. When the browser sees the <code>&amp;</code> in the HTML source for a link it will interpret it as an ampersand and the link target will be as intended. If you paste a URL into your browser address bar it does not expect it to be HTML and does not try to interpret any HTML encoding that it may contain. This is why your example links that you suggest we should copy/paste into a browser don't work and why we wouldn't expect them to work.</p>
<p>If you post a bit more of your actual code we might be able to see what you have done wrong, but you appear to be heading the right direction by using <code>&amp;</code> in your anchor tags.</p>
|
<p>The problem is worse than you think - try it in <a href="https://en.wikipedia.org/wiki/Safari_%28web_browser%29" rel="nofollow noreferrer">Safari</a>. <code>&amp;amp;</code> gets converted to <code>&amp;#38;</code> and the hash ends the URL.</p>
<p>The correct answer is to not output XHTML - there's no reason that justifies spending more time on development and alienating Mac users.</p>
| 34,676
|
<p>Can someone illustrate what really is the difference between the two?</p>
|
<p>Even though they are two very different things, one can argue they <strong>both solve a software architecture problem</strong></p>
<ul>
<li><p>a design pattern solves many software architecture issues (about creation, behavior, concurrency, ...) with different pre-defined <em>design</em>. (design being an <a href="https://stackoverflow.com/questions/268497">implementation of an architecture topic</a>)</p></li>
<li><p>a framework is based on the <a href="http://en.wikipedia.org/wiki/Hollywood_Principle" rel="noreferrer"><strong>Hollywood Principle</strong></a> ("Don't call us, we call you"), where you implement some high level requirements as specified, and leave the framework do the rest of the work, calling your implementations.</p></li>
</ul>
<p>A key difference is the <strong>scope cohesion</strong>:</p>
<ul>
<li><p><strong>design pattern have a</strong> <strong><em>tight</em></strong> <strong>scope</strong>:</p>
<ul>
<li>class design patterns (involves classes)</li>
<li>business design patterns (involves business workflows)</li>
<li>application design patterns (involves applications)</li>
</ul></li>
<li><p><strong>framework has a</strong> <strong><em>large</em></strong> <strong>scope</strong>:<br>
For instance, <strong><a href="http://msdn.microsoft.com/en-us/netframework/default.aspx" rel="noreferrer">.NET is a framework</a></strong> composed of:</p>
<ul>
<li>a language (C#)</li>
<li>a runtime environment (CLR)</li>
<li>a collection of libraries<br>
Just develop what you need and let the .Net framework call your classes.</li>
</ul></li>
</ul>
|
<p>Frameworks are more specific to a problem definition. In order to write one design patterns can be devised or used where ever applicable.</p>
| 41,405
|
<p>I've asked a few <a href="https://stackoverflow.com/questions/150513/html-input-style-to-hide-the-box-but-show-the-contents">other questions</a> here about this system, so I'll try to avoid repeating a lot of detail.</p>
<p>The short version is that I have many html pages, each with a form that accepts input, but never saves the input anywhere- they are only ever printed out for mailing. A previously developer who had never heard of <code>@media print</code> did the initial work on most of them, and so he came up with some... <em>odd</em> solutions to hide the ugly text boxes on the printed page, usually resulting in two completely separate copies of nearly the same html. Unfortunately, that broke the back button in many cases, and so now I must go back and fix them. </p>
<hr>
<p>In some cases, these html forms really are form letters, with text inputs in the middle of the text. I can style the text inputs so that the box doesn't show, but they are still the wrong size. This results in a bunch of extra ugly whitespace where it doesn't belong. How can make the inputs fit the text entered by the user?</p>
<p>The best I can come up with at the moment is to have a hidden <span> next to each input that is styled to show instead of the input when printing, and use javascript to keep it in sync. But this is ugly. I'm looking for something better.</p>
<p><strong>Update:</strong><br>
Most of our users are still in IE6, but we have some IE7 and firefox out there.</p>
<p><strong>Update2:</strong><br>
I re-thought this a little to use a label rather than a span. I'll maintain the relationship using the label's <code>for</code> attribute. See <a href="https://stackoverflow.com/questions/285522/find-html-label-associated-with-a-given-input">this question</a> for my final code.</p>
|
<p>The nearest equivalent is probably the <a href="http://labix.org/python-dateutil" rel="noreferrer">dateutil</a> module. Usage is:</p>
<pre><code>>>> from dateutil.parser import parse
>>> parse("Wed, Nov 12")
datetime.datetime(2008, 11, 12, 0, 0)
</code></pre>
<p>Using the fuzzy parameter should ignore extraneous text. ie</p>
<pre><code>>>> parse("the date was the 1st of December 2006 2:30pm", fuzzy=True)
datetime.datetime(2006, 12, 1, 14, 30)
</code></pre>
|
<p>Why no give <a href="http://code.google.com/p/parsedatetime/" rel="nofollow noreferrer">parsedatetime</a> a try?</p>
| 36,228
|
<p>I'm trying to access the command line and execute a command, and then return the output to my aspx page. A good example would be running dir on page load of an aspx page and returning the output via Response.Write(). I have tried using the code below. When I try debugging this it runs but never finishes loading and no output is rendered.
I am using C# and .NET Framework 3.5sp1. Any help much appreciated.</p>
<p>Thanks,
Bryan</p>
<pre><code>public partial class CommandLine : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Process si = new System.Diagnostics.Process();
si.StartInfo.WorkingDirectory = @"c:\";
si.StartInfo.UseShellExecute = false;
si.StartInfo.FileName = "cmd.exe";
si.StartInfo.Arguments = "dir";
si.StartInfo.CreateNoWindow = true;
si.StartInfo.RedirectStandardInput = true;
si.StartInfo.RedirectStandardOutput = true;
si.StartInfo.RedirectStandardError = true;
si.Start();
string output = si.StandardOutput.ReadToEnd();
si.Close();
Response.Write(output);
}
}
</code></pre>
|
<p>You have a problem with the syntax of commandline arguments to cmd.exe. This is why cmd never exits.<br>
In order to have cmd.exe run a program and then quit, you need to send it the syntax "/c [command]". Try running the same code with the line</p>
<pre><code> si.StartInfo.Arguments = "dir";
</code></pre>
<p>replaced with </p>
<pre><code> si.StartInfo.Arguments = "/c dir";
</code></pre>
<p>and see if it works.</p>
|
<p>This is madness! Use the System.IO namepace to create your file list from inside your C# program! It's very easy to do; although this technique also has authorization issues. </p>
| 30,765
|
<p>I am making a Python gui project that needs to duplicate the look of a Windows gui environment (ie Explorer). I have my own custom icons to draw but they should be selectable by the same methods as usual; click, ctrl-click, drag box etc. Are any of the gui toolkits going to help with this or will I have to implement it all myself. If there aren't any tools to help with this advice would be greatly appreciated.</p>
<p><em>edit</em> I am not trying to recreate explorer, that would be madness. I simply want to be able to take icons and lay them out in a scrollable window. Any number of them may be selected at once. It would be great if there was something that could select/deselect them in the same (appearing at least) way that Windows does. Then all I would need is a list of all the selected icons.</p>
|
<p>Python has extensions for accessing the Win32 API, but good luck trying to re-write explorer in <em>that</em> by yourself. Your best bet is to use a toolkit like <a href="http://doc.trolltech.com/4.4/gallery-windowsxp.html" rel="nofollow noreferrer">Qt</a>, but you'll still have to write the vast majority of the application from scratch.</p>
<p>Is there any way you can re-use explorer itself in your project?</p>
<hr>
<p>Updated for edited question:</p>
<p><a href="http://www.gtk.org/" rel="nofollow noreferrer">GTK+</a> has an <a href="http://library.gnome.org/devel/gtk/unstable/GtkIconView.html" rel="nofollow noreferrer">icon grid widget</a> that you could use. See a reference for <a href="http://www.pygtk.org/" rel="nofollow noreferrer">PyGTK+</a>: <a href="http://www.pygtk.org/docs/pygtk/class-gtkiconview.html" rel="nofollow noreferrer"><code>gtk.IconView</code></a></p>
|
<p>I'll assume you're serious and suggest that you check out the many wonderful <a href="http://wiki.python.org/moin/GuiProgramming" rel="nofollow noreferrer">GUI libraries</a> available for Python.</p>
| 17,500
|
<p>Can/Should I use a LIKE criteria as part of an INNER JOIN when building a stored procedure/query? I'm not sure I'm asking the right thing, so let me explain.</p>
<p>I'm creating a procedure that is going to take a list of keywords to be searched for in a column that contains text. If I was sitting at the console, I'd execute it as such:</p>
<pre><code>SELECT Id, Name, Description
FROM dbo.Card
WHERE Description LIKE '%warrior%'
OR
Description LIKE '%fiend%'
OR
Description LIKE '%damage%'
</code></pre>
<p>But a trick I picked up a little while go to do "strongly typed" list parsing in a stored procedure is to parse the list into a table variable/temporary table, converting it to the proper type and then doing an INNER JOIN against that table in my final result set. This works great when sending say a list of integer IDs to the procedure. I wind up having a final query that looks like this:</p>
<pre><code>SELECT Id, Name, Description
FROM dbo.Card
INNER JOIN @tblExclusiveCard ON dbo.Card.Id = @tblExclusiveCard.CardId
</code></pre>
<p>I want to use this trick with a list of strings. But since I'm looking for a particular keyword, I am going to use the LIKE clause. So ideally I'm thinking I'd have my final query look like this:</p>
<pre><code>SELECT Id, Name, Description
FROM dbo.Card
INNER JOIN @tblKeyword ON dbo.Card.Description LIKE '%' + @tblKeyword.Value + '%'
</code></pre>
<p>Is this possible/recommended?</p>
<p>Is there a better way to do something like this?</p>
<hr>
<p>The reason I'm putting wildcards on both ends of the clause is because there are "archfiend", "beast-warrior", "direct-damage" and "battle-damage" terms that are used in the card texts.</p>
<p>I'm getting the impression that depending on the performance, I can either use the query I specified or use a full-text keyword search to accomplish the same task? </p>
<p>Other than having the server do a text index on the fields I want to text search, is there anything else I need to do?</p>
|
<p>Your first query will work but will require a full table scan because any index on that column will be ignored. You will also have to do some dynamic SQL to generate all your LIKE clauses.</p>
<p>Try a full text search if your using SQL Server or check out one of the <a href="http://lucene.apache.org/java/docs/index.html" rel="noreferrer">Lucene</a> implementations. Joel talked about his success with it recently.</p>
|
<p>Performance will be depend on the actual server than you use, and on the schema of the data, and the amount of data. With current versions of MS SQL Server, that query should run just fine (MS SQL Server 7.0 had issues with that syntax, but <a href="http://support.microsoft.com/kb/225093" rel="nofollow noreferrer">it was addressed in SP2</a>).</p>
<p>Have you run that code through a profiler? If the performance is fast enough and the data has the appropriate indexes in place, you should be all set.</p>
| 4,085
|
<p>I'm currently writing a C# application that does a lot of digital signal processing, which involves a lot of small fine-tuned memory xfer operations. I wrote these routines using unsafe pointers and they seem to perform much better than I first thought. However, I want the app to be as fast as possible.</p>
<p>Would I get any performance benefit from rewriting these routines in C or C++ or should I stick to unsafe pointers? I'd like to know what unsafe pointers brings to the table in terms of performance, compared to C/C++.</p>
<p>EDIT: I'm not doing anything special inside these routines, just the normal DSP stuff: cache friendly data transfers from one array to the other with a lot of multiplications, additions, bit shiftings etc. in the way. I'd expect the C/C++ routines to look pretty much the same (if not identical) as their C# counterparts.</p>
<p>EDIT: Thanks a lot to everyone for all the clever answers. What I've learned is that I won't get any significant boost in performance just by doing a direct port, unless some sort of SSE optimization takes place. Assuming that all modern C/C++ compilers can take advantage of it I'm looking forward to give it a try. If someone is interested in the results just let me know and I'll post them somewhere. (May take a while though).</p>
|
<p>I've actually done pretty much exactly what you're asking, only in an image processing area. I started off with C# unsafe pointers, then moved into C++/CLI and now I code everything in C++. And in fact, from there I changed from pointers in C++ to SSE processor instructions, so I've gone all the way. Haven't reached assembler yet, although I don't know if I need to, I saw an article on CodeProject that showed SSE can be as fast as inline assembler, I can find it if you want me to. </p>
<p>What happened as I went along was my algorithm went from around 1.5-2 frames per second in C# with unsafe pointers, to 40 frames per second now. C# and C++/CLI were definitely slower than C++, even with pointers, I haven't been able to get above 10 frames per second with those languages. As soon as I switched to C++, I got something like 15-20 frames per second instantly. A few more clever changes and SSE got me up to 40 frames per second. So yes, it is worth going down if you want speed in my experience. There is a clear performance gain.</p>
|
<p>I would suggest that if you have any algorithms in your DSP code that <strong>need</strong> to be optimised then you should really be writing them in assembly, not C or C++.</p>
<p>In general, with modern processors and hardware, there aren't that many scenarios that require or warrant the effort involved in optimisation. Have you actually identified any performance issues? If not then it's probably best to stick with what you have. Unsafe C# is unlikely to be significantly slower than C/C++ in most cases of simple arithmetic.</p>
<p>Have you considered C++/CLI? You could have the best of both worlds then. It would even allow you to use inline assembler if required.</p>
| 32,719
|
<p>Is there any way to format a string by name rather than position in C#?</p>
<p>In python, I can do something like this example (shamelessly stolen from <a href="http://docs.python.org/lib/typesseq-strings.html" rel="noreferrer">here</a>):</p>
<pre><code>>>> print '%(language)s has %(#)03d quote types.' % \
{'language': "Python", "#": 2}
Python has 002 quote types.
</code></pre>
<p>Is there any way to do this in C#? Say for instance:</p>
<pre><code>String.Format("{some_variable}: {some_other_variable}", ...);
</code></pre>
<p>Being able to do this using a variable name would be nice, but a dictionary is acceptable too.</p>
|
<p>There is no built-in method for handling this.</p>
<p><a href="http://mo.notono.us/2008/07/c-stringinject-format-strings-by-key.html" rel="noreferrer">Here's one method</a></p>
<pre><code>string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o);
</code></pre>
<p><a href="http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx" rel="noreferrer">Here's another</a></p>
<pre><code>Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user);
</code></pre>
<p><a href="http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx" rel="noreferrer">A third improved method partially based on the two above</a>, from Phil Haack</p>
|
<pre><code>string language = "Python";
int numquotes = 2;
string output = language + " has "+ numquotes + " language types.";
</code></pre>
<p>Edit:
What I should have said was, "No, I don't believe what you want to do is supported by C#. This is as close as you are going to get."</p>
| 19,239
|
<p>Whenever I run any jython program in Eclipse, I got the following error in the beginning of the output: </p>
<blockquote>
<p>" Failed to
get environment, environ will be
empty: (0, 'Failed to execute command
([\'sh\', \'-c\', \'env\']):
java.io.IOException: Cannot run
program "sh": Crea teProcess error=2,
The system cannot find the file
specified')</p>
</blockquote>
<p>First, my environment is:</p>
<p>Windows 2008</p>
<p>JDK 1.6.0u10</p>
<p>jython 2.2.1</p>
<p>I did some digging, and I realized that this message is produced in the function javaos.getenv().
Whenever I call the javaos.getenv() function, it throws the following error:</p>
<p>C:\jython2.2.1>java -jar jython.jar</p>
<blockquote>
<blockquote>
<blockquote>
<p>import javaos</p>
<p>print javaos.getenv("user.name")</p>
</blockquote>
</blockquote>
<p>Failed to get environment, environ
will be empty: (0, 'Failed to execute
command ([\'sh\', \'-c\', \'env\']):
java.io.IOException: Cannot run
program "sh": Crea teProcess error=2,
The system cannot find the file
specified')</p>
</blockquote>
<p>This is strange, because I'm currently using a Windows machine, not an Unix.</p>
|
<p>Try to uncomment and change the os setting in the 'registry' file </p>
<p>(it is in the same directory as your jython.jar / i hope)</p>
<pre><code># python.os determines operating-specific features, similar to and overriding the
# Java property "os.name".
# Some generic values are also supported: 'nt', 'ce' and 'posix'.
# Uncomment the following line for the most generic OS behavior available.
#python.os=None
python.os=nt
# try nt or dos
</code></pre>
|
<p>I ran into the same error, using Windows Vista, and Jython 2.5.1, under Eclipse/PyDev By editing javaos.py, to include "Windows Vista" in the OR statement in getOsType,;
I fixed the error. (I've filed a bug with the fix under the PyDev Tracker at SourceForge.)</p>
<p>Details:</p>
<p>I installed the full version of Jython, and that did not help.
I also tried editing the "registry" file in the Jython tree. That did not help either.</p>
<p>Then I looked at the files in:</p>
<p><code>C:\eclipse-platform-3.5-win32\eclipse\plugins\org.python.pydev.jython_1.4.8.2881\Lib</code></p>
<p>to find "javaos.py" and added a bit of code to read:</p>
<pre><code>def _getOsType( os=None ):
os = os or sys.registry.getProperty( "python.os" ) or \
java.lang.System.getProperty( "os.name" )
_osTypeMap = (
( "nt", r"(nt)|(Windows NT)|(Windows NT 4.0)|(WindowsNT)|"
r"(Windows 2000)|(Windows XP)|(Windows CE)|(Windows Vista)" ),
( "dos", r"(dos)|(Windows 95)|(Windows 98)|(Windows ME)" ),
( "mac", r"(mac)|(MacOS.*)|(Darwin)" ),
( "None", r"(None)" ),
( "posix", r"(.*)" ), # default - posix seems to vary mast widely
)
for osType, pattern in _osTypeMap:
if re.match( pattern, os ):
break
return osType
</code></pre>
| 30,492
|
<p>We are logging any exceptions that happen in our system by writing the Exception.Message to a file. However, they are written in the culture of the client. And Turkish errors don't mean a lot to me.</p>
<p>So how can we log any error messages in English without changing the users culture?</p>
|
<p>This issue can be partially worked around. The Framework exception code loads the error messages from its resources, based on the current thread locale. In the case of some exceptions, this happens at the time the Message property is accessed.</p>
<p>For those exceptions, you can obtain the full US English version of the message by briefly switching the thread locale to en-US while logging it (saving the original user locale beforehand and restoring it immediately afterwards).</p>
<p>Doing this on a separate thread is even better: this ensures there won't be any side effects. For example:</p>
<pre><code>try
{
System.IO.StreamReader sr=new System.IO.StreamReader(@"c:\does-not-exist");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString()); //Will display localized message
ExceptionLogger el = new ExceptionLogger(ex);
System.Threading.Thread t = new System.Threading.Thread(el.DoLog);
t.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
t.Start();
}
</code></pre>
<p>Where the ExceptionLogger class looks something like:</p>
<pre><code>class ExceptionLogger
{
Exception _ex;
public ExceptionLogger(Exception ex)
{
_ex = ex;
}
public void DoLog()
{
Console.WriteLine(_ex.ToString()); //Will display en-US message
}
}
</code></pre>
<p>However, as <a href="https://stackoverflow.com/users/13087/joe">Joe</a> correctly points out in a comment on an earlier revision of this reply, some messages are already (partially) loaded from the language resources at the time the exception is thrown.</p>
<p>This applies to the 'parameter cannot be null' part of the message generated when an ArgumentNullException("foo") exception is thrown, for example. In those cases, the message will still appear (partially) localized, even when using the above code.</p>
<p>Other than by using impractical hacks, such as running all your non-UI code on a thread with en-US locale to begin with, there doesn't seem to be much you can do about that: the .NET Framework exception code has no facilities for overriding the error message locale.</p>
|
<p>You should log the call stack instead of just error message (IIRC, simple exception.ToString() should do that for you). From there, you can determine exactly where the exception originated from, and usually deduce which exception it is.</p>
| 25,658
|
<p><strong>Problem:</strong> a table of coordinate lat/lngs. Two rows can potentially have the same coordinate. We want a query that returns a set of rows with unique coordinates (within the returned set). Note that <code>distinct</code> is not usable because I need to return the id column which is, by definition, distinct. This sort of works (<code>@maxcount</code> is the number of rows we need, <code>intid</code> is a unique int id column):</p>
<pre><code>select top (@maxcount) max(intid)
from Documents d
group by d.geoLng, d.geoLat
</code></pre>
<p>It will always return the same row for a given coordinate unfortunately, which is bit of a shame for my use. If only we had a <code>rand()</code> aggregate we could use instead of <code>max()</code>... Note that you can't use <code>max()</code> with guids created by <code>newid()</code>.</p>
<p>Any ideas?
(there's some more background here, if you're interested: <a href="http://www.itu.dk/~friism/blog/?p=121" rel="nofollow noreferrer">http://www.itu.dk/~friism/blog/?p=121</a>)</p>
<p>UPDATE: Full solution <a href="http://www.itu.dk/~friism/blog/?p=213" rel="nofollow noreferrer">here</a></p>
|
<p>You might be able to use a CTE for this with the ROW_NUMBER function across lat and long and then use rand() against that. Something like:</p>
<pre><code>WITH cte AS
(
SELECT
intID,
ROW_NUMBER() OVER
(
PARTITION BY geoLat, geoLng
ORDER BY NEWID()
) AS row_num,
COUNT(intID) OVER (PARTITION BY geoLat, geoLng) AS TotalCount
FROM
dbo.Documents
)
SELECT TOP (@maxcount)
intID, RAND(intID)
FROM
cte
WHERE
row_num = 1 + FLOOR(RAND() * TotalCount)
</code></pre>
<p>This will always return the first sets of lat and lngs and I haven't been able to make the order random. Maybe someone can continue on with this approach. It will give you a random row within the matching lat and lng combinations though.</p>
<p>If I have more time later I'll try to get around that last obstacle.</p>
|
<p>Where did you get the idea that DISTINCT only works on one column? Anyway, you could also use a GROUP BY clause.</p>
| 46,215
|
<p>Just wondering if any of you guys know of any web-based/browser-based employee scheduling software/tools? </p>
<p>Currently doing it all in Excel, but it just isnt intelligent enough... any product suggestions?</p>
<p>Needs to handle multiple employees time over weeks and months... to schedule in work short-term and long-term, allow me to see possible resourcing issues etc etc. </p>
<p>Its an easy question answer when you work only on projects, but at my agency we work on projects and day-to-day retainer type things that can come in at any time and are usually of the "drop everything and do this now" type. </p>
<p>If it were just projects, then any one of the online Project Management tools (GoPlan, Copper Project, MS Project) would suffice (but definately not Basecamp, I find this ok for very small projects and small teams, but anything larger and I think it falls down completely as a PM tool)</p>
<p>The only thing that came close to doing all that I wanted was Workschedule - <a href="http://www.workschedule.net/" rel="noreferrer">http://www.workschedule.net/</a></p>
<p>Its browser based, low-cost and has a zillion options that really allowed me to plan resource levels for the agency. The only downside is it looks pretty awful, but I soon got over this.</p>
<p>Clarification: Must be general purpose i.e. not just for one industry</p>
|
<p>My girlfriend's employer uses: <a href="http://www.hotschedules.com/" rel="nofollow noreferrer">http://www.hotschedules.com/</a> from what I have seen it seems to be pretty feature-complete...</p>
|
<p>I love WSS (Windows Sharepoint Services). It's free and installs on W2K3 or W2K8 Server. Very easy to use out of the box. And easily customizable. With Intelligantt you can publish your MS Project files there as well. Then by plugging in Microsoft Office Sharepoint Designer you can built some custom workflows. </p>
<p>And of course the favorite integration with Microsoft Office Outlook is always a plus. You can export your calendars and task lists.</p>
| 38,402
|
<p>ASP.NET ASMX service occasionally throws exceptions. However, global.asax Application_Error method do not seem to catch them. The question is, how to configure global error handler to catch and log these exceptions?</p>
|
<p>Basic problem (well it is not a problem) with ASMX web service is that any exception behind the service layer is thrown as SOAP exception to client. You need to catch SOAP exception and then look for inner exception there.</p>
<p>A better and clean approach is you implement SOAP handler in your application. Serialize the SOAP exception through this and on client end deserialize it. This way you will have complete control over exception flow, rather than .net framework.</p>
<p>HTH </p>
|
<p>Is it the ASMX or the AJAX JavaScript which is throwing the exception? </p>
<p>If it's the Javascript, you'll need to write exception handling into your JS, and then push that back to the server to be tracked in your error datastore--possibly via another call to your webservice.</p>
<p>If it's the ASMX then it's probably getting caught by your Application_Error, BUT as ASMX returns XML or JSON it won't necessarily get displayed on your UI unless you're looking for it.</p>
| 24,551
|
<p>Is it recommended that I use an <a href="http://en.wikipedia.org/wiki/Initialization_vector" rel="noreferrer">initialization vector</a> to encrypt/decrypt my data? Will it make things more secure? Is it one of those things that need to be evaluated on a case by case basis?</p>
<p>To put this into actual context, the Win32 Cryptography function, <a href="http://msdn.microsoft.com/en-us/library/aa380272(VS.85).aspx" rel="noreferrer">CryptSetKeyParam</a> allows for the setting of an initialization vector on a key prior to encrypting/decrypting. Other API's also allow for this. </p>
<p>What is generally recommended and why?</p>
|
<p>An IV is essential when the same key might ever be used to encrypt more than one message.</p>
<p>The reason is because, under most encryption modes, two messages encrypted with the same key can be analyzed together. In a simple stream cipher, for instance, XORing two ciphertexts encrypted with the same key results in the XOR of the two messages, from which the plaintext can be easily extracted using traditional cryptanalysis techniques.</p>
<p>A weak IV is part of what made WEP breakable.</p>
<p>An IV basically mixes some unique, non-secret data into the key to prevent the same key ever being used twice.</p>
|
<p>The IV allows for plaintext to be encrypted such that the encrypted text is harder to decrypt for an attacker. Each bit of IV you use will double the possibilities of encrypted text from a given plain text.</p>
<p>For example, let's encrypt 'hello world' using an IV one character long. The IV is randomly selected to be 'x'. The text that is then encrypted is then 'xhello world', which yeilds, say, 'asdfghjkl'. If we encrypt it again, first generate a new IV--say we get 'b' this time--and encrypt like normal (thus encrypting 'bhello world'). This time we get 'qwertyuio'.</p>
<p>The point is that the attacker doesn't know what the IV is and therefore must compute every possible IV for a given plain text to find the matching cipher text. In this way, the IV acts like a <a href="http://en.wikipedia.org/wiki/Password_salt" rel="nofollow noreferrer">password salt</a>. Most commonly, an IV is used with a chaining cipher (either a stream or block cipher). In a chaining block cipher, the result of each block of plain text is fed to the cipher algorithm to find the cipher text for the next block. In this way, each block is chained together.</p>
<p>So, if you have a random IV used to encrypt the plain text, how do you decrypt it? Simple. Pass the IV (in plain text) along with your encrypted text. Using our fist example above, the final cipher text would be 'xasdfghjkl' (IV + cipher text).</p>
<p>Yes you should use an IV, but be sure to choose it properly. Use a good random number source to make it. Don't ever use the same IV twice. And <strong>never</strong> use a constant IV.</p>
<p>The Wikipedia article on <a href="http://en.wikipedia.org/wiki/Initialization_vector" rel="nofollow noreferrer">initialization vectors</a> provides a general overview.</p>
| 9,153
|
<p>I am trying to figure out how a library works and I would like to be able to visualize which methods and lines of code are executed in response to user input (e.g. a keypress or mouse click). Is there a way to do this in .NET?</p>
|
<p>There's a wonderful, free tool from Microsoft called <a href="http://research.microsoft.com/Pex/" rel="nofollow noreferrer">Pex</a>. Once installed, you can right-click a method and select "Run Pex Exploration". It will analyze the code and show you inputs to touch every part of the method.</p>
<p>For more information, see <a href="http://blogs.msdn.com/nikolait/archive/2008/10/21/sneak-preview-code-digger-the-new-pex-experience.aspx" rel="nofollow noreferrer">Pex CodeDigger</a>. Here's a screenshot of it in action:</p>
<p><a href="https://i.stack.imgur.com/FIsHp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FIsHp.png" alt="alt text"></a></p>
|
<p>If you are able to execute the action you want to analyze from within an NUnit test, you can use the NCover utility to visualize which parts of the code were executed and which weren't.</p>
<p><a href="http://www.ncover.com/" rel="nofollow noreferrer">http://www.ncover.com/</a></p>
<p>Hope this helps!</p>
<p>Adam</p>
| 33,759
|
<p>Say you've got a credit card number with an expiration date of 05/08 - i.e. May 2008.</p>
<p>Does that mean the card expires on the morning of the 1st of May 2008, or the night of the 31st of May 2008?</p>
|
<p>It took me a couple of minutes to find a site that I could source for this.</p>
<blockquote>
<p>The card is valid until the last day of the month indicated, after the last [sic]<sup>1</sup>
day of the next month; the card cannot be used to make a purchase if the
merchant attempts to obtain an authorization.
- <a href="http://web.archive.org/web/20081003052424/http://cumemberscard.com/noda/CreditCardGlossary.asp" rel="noreferrer">Source</a></p>
</blockquote>
<p>Also, while looking this up, I found an interesting article on Microsoft's website using an example like this, exec summary: <a href="https://web.archive.org/web/20150113060002/http://support.microsoft.com/kb/210534" rel="noreferrer">Access 2000 for a month/year defaults to the first day of the month, here's how to override that to calculate the end of the month like you'd want for a credit card</a>.</p>
<p>Additionally, this page has <a href="http://euro.ecom.cmu.edu/resources/elibrary/everycc.htm" rel="noreferrer">everything you ever wanted to know about credit cards</a>.</p>
<hr>
<ol>
<li>This is assumed to be a typo and that it should read "..., after the first day of the next month; ..."</li>
</ol>
|
<p>In your example a credit card is expired on 6/2008.</p>
<p>Without knowing what you are doing I cannot say definitively you should not be validating ahead of time but be aware that sometimes business rules defy all logic.</p>
<p>For example, where I used to work they often did not process a card at all or would continue on transaction failure simply so they could contact the customer and get a different card.</p>
| 7,761
|
<p>Are there any replacements for NUnitAsp that anyone knows of for testing ASP.NET pages?</p>
|
<p>You can use <a href="http://watin.sourceforge.net/" rel="nofollow noreferrer">WatiN</a> or <a href="http://code.google.com/p/ieunit/" rel="nofollow noreferrer">IEUnit</a>.</p>
|
<p>Please note that both IeUnit and WatiN are discontinued.</p>
<p>Using Selenium directly in tests is not a good idea, as you may probably need to <a href="http://toolsqa.com/selenium-webdriver/c-sharp/encapsulation-oops-principle/" rel="nofollow noreferrer">encapsulate page objects</a>.</p>
<p>I'd recommend to use the <strong><a href="https://playwright.dev/dotnet/" rel="nofollow noreferrer">Playwright for .NET</a></strong> as a web UI automation test tool.</p>
<p>You may also consider using one of these tools:</p>
<ul>
<li><a href="https://github.com/atata-framework/atata" rel="nofollow noreferrer">Atata Framework</a></li>
<li><a href="http://lefthandedgoat.github.io/canopy/" rel="nofollow noreferrer">Canopy</a> (F#)</li>
<li><a href="https://github.com/featurist/coypu" rel="nofollow noreferrer">Coypu</a></li>
<li><a href="https://github.com/ObjectivityLtd/Test.Automation" rel="nofollow noreferrer">Test.Automation</a></li>
<li><a href="http://seleno.teststack.net/" rel="nofollow noreferrer">TestStack.Seleno</a></li>
</ul>
<h1>See also</h1>
<p>See also the list of Web Application Testing frameworks for .NET that is maintained and up-to-date:</p>
<ul>
<li><a href="https://github.com/dariusz-wozniak/List-of-Testing-Tools-and-Frameworks-for-.NET/blob/master/README.md#web-application-testing" rel="nofollow noreferrer">List of Automated Testing Tools and Frameworks for .NET: Web Application Testing</a>.</li>
</ul>
| 32,511
|
<p>I'm looking for some useful books for a beginner who wants to better understand the Sun JVM</p>
|
<p>Not specific to the Sun Java Virtual Machine implementation, but <a href="http://java.sun.com/docs/books/jvms/second_edition/html/VMSpecTOC.doc.html" rel="nofollow noreferrer">The Java Virtual Machine Specifications</a> from Sun may be an interesting read.</p>
|
<p><a href="http://en.wikipedia.org/wiki/Java_Virtual_Machine" rel="nofollow noreferrer">wikipedia - JVM</a></p>
<blockquote>
<p>A Java Virtual Machine (JVM) is a set of computer software programs and data structures which use a virtual machine model for the execution of other computer programs and scripts. The model used by a JVM accepts a form of computer intermediate language commonly referred to as Java bytecode. This language conceptually represents the instruction set of a stack-oriented, capability architecture. As of 2006, there are an estimated 4 billion JVM enabled devices worldwide.</p>
<p>Java Virtual Machines operate on Java bytecode, which is normally (but not necessarily) generated from Java source code; a JVM can also be used to implement programming languages other than Java. For example, Ada source code can be compiled to Java bytecode, which may then be executed by a JVM. JVMs can also be released by other companies besides Sun (the developer of Java) — JVMs using the "Java" trademark may be developed by other companies as long as they adhere to the JVM specification published by Sun (and related contractual obligations).</p>
<p>The JVM is a crucial component of the Java Platform. Because JVMs are available for many hardware and software platforms, Java can be both middleware and a platform in its own right — hence the trademark write once, run anywhere. The use of the same bytecode for all platforms allows Java to be described as "compile once, run anywhere", as opposed to "write once, compile anywhere", which describes cross-platform compiled languages. The JVM also enables such unique features as Automated Exception Handling which provides 'root-cause' debugging information for every software error (exception) independent of the source code.</p>
<p>The JVM is distributed along with a set of standard class libraries which implement the Java API (Application Programming Interface). The virtual machine and API have to be consistent with each other[dubious – discuss] and are therefore bundled together as the Java Runtime Environment.</p>
</blockquote>
| 45,798
|
<p>First off, this question is ripped out from <a href="https://stackoverflow.com/questions/56215/interesting-interview-questions#56291">this</a> question. I did it because I think this part is bigger than a sub-part of a longer question. If it offends, please pardon me.</p>
<p>Assume that you have a algorithm that generates randomness. Now how do you test it?
Or to be more direct - Assume you have an algorithm that shuffles a deck of cards, how do you test that it's a perfectly random algorithm?</p>
<p>To add some theory to the problem -
A deck of cards can be shuffled in 52! (52 factorial) different ways. Take a deck of cards, shuffle it by hand and write down the order of all cards. What is the probability that you would have gotten exactly that shuffle? Answer: 1 / 52!.</p>
<p>What is the chance that you, after shuffling, will get A, K, Q, J ... of each suit in a sequence? Answer 1 / 52!</p>
<p>So, just shuffling once and looking at the result will give you absolutely no information about your shuffling algorithms randomness. Twice and you have more information, Three even more...</p>
<p>How would you black box test a shuffling algorithm for randomness?</p>
|
<p>Statistics. The de facto standard for testing RNGs is the <a href="https://web.archive.org/web/20150103230339/http://stat.fsu.edu/pub/diehard/" rel="nofollow noreferrer">Diehard suite</a> (originally available at <a href="http://stat.fsu.edu/pub/diehard" rel="nofollow noreferrer">http://stat.fsu.edu/pub/diehard</a>). Alternatively, the <a href="ftp://ftp.fourmilab.ch/web/random/index.html" rel="nofollow noreferrer">Ent program</a> provides tests that are simpler to interpret but less comprehensive.</p>
<p>As for shuffling algorithms, use a well-known algorithm such as <a href="http://en.wikipedia.org/wiki/Knuth_shuffle" rel="nofollow noreferrer">Fisher-Yates</a> (a.k.a "Knuth Shuffle"). The shuffle will be uniformly random so long as the underlying RNG is uniformly random. If you are using Java, this algorithm is available in the standard library (see <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)" rel="nofollow noreferrer">Collections.shuffle</a>).</p>
<p>It probably doesn't matter for most applications, but be aware that most RNGs do not provide sufficient degrees of freedom to produce every possible permutation of a 52-card deck (explained <a href="http://blog.uncommons.org/2008/04/10/a-java-programmers-guide-to-random-numbers-part-3-seeding/" rel="nofollow noreferrer">here</a>).</p>
|
<p>Pondering it myself, what I would do is something like:</p>
<p>Setup (Pseudo code)</p>
<pre><code>// A card has a Number 0-51 and a position 0-51
int[][] StatMatrix = new int[52][52]; // Assume all are set to 0 as starting values
ShuffleCards();
ForEach (card in Cards) {
StatMatrix[Card.Position][Card.Number]++;
}
</code></pre>
<p>This gives us a matrix 52x52 indicating how many times a card has ended up at a certain position. Repeat this a large number of times (I would start with 1000, but people better at statistics than me may give a better number).</p>
<p>Analyze the matrix</p>
<p>If we have perfect randomness and perform the shuffle an infinite number of times then for each card and for each position the number of times the card ended up in that position is the same as for any other card. Saying the same thing in a different way:</p>
<pre><code>statMatrix[position][card] / numberOfShuffle = 1/52.
</code></pre>
<p>So I would calculate how far from that number we are.</p>
| 8,033
|
<p>In a few large projects i have been working on lately it seems to become increasingly important to choose one or the other (XML or Annotation). As projects grow, consistency is very important for maintainability. </p>
<p>My questions are: what are the advantages of XML-based configuration over Annotation-based configuration and what are the advantages of Annotation-based configuration over XML-based configuration?</p>
|
<p>Annotations have their use, but they are not the one silver bullet to kill XML configuration. I recommend mixing the two!</p>
<p>For instance, if using Spring, it is entirely intuitive to use XML for the dependency injection portion of your application. This gets the code's dependencies away from the code which will be using it, by contrast, using some sort of annotation in the code that needs the dependencies makes the code aware of this automatic configuration.</p>
<p>However, instead of using XML for transactional management, marking a method as transactional with an annotation makes perfect sense, since this is information a programmer would probably wish to know. But that an interface is going to be injected as a SubtypeY instead of a SubtypeX should not be included in the class, because if now you wish to inject SubtypeX, you have to change your code, whereas you had an interface contract before anyways, so with XML, you would just need to change the XML mappings and it is fairly quick and painless to do so.</p>
<p>I haven't used JPA annotations, so I don't know how good they are, but I would argue that leaving the mapping of beans to the database in XML is also good, as the object shouldn't care where its information came from, it should just care what it can do with its information. But if you like JPA (I don't have any expirience with it), by all means, go for it.</p>
<p>In general:
If an annotation provides functionality and acts as a comment in and of itself, and doesn't tie the code down to some specific process in order to function normally without this annotation, then go for annotations. For example, a transactional method marked as being transactional does not kill its operating logic, and serves as a good code-level comment as well. Otherwise, this information is probably best expressed as XML, because although it will eventually affect how the code operates, it won't change the main functionality of the code, and hence doesn't belong in the source files.</p>
|
<p>This is the classic 'Configuration versus Convention' question. Personal taste dictates the answer in most cases. However, personally I prefer Configuration (i.e. XML based) over Convention. IMO IDE's are sufficiently robust enough to overcome some of the XML hell people often associate w/ the building and maintaining an XML based approach. In the end, I find the benefits of Configuration (such as building utilities to build, maintain and deploy the XML config file) outweighs Convention in the long run. </p>
| 22,042
|
<p>Is there a way to execute SQL custom functions with Enterpise Library? I've tried Database.ExecuteScalar() but for some reason it returns null.</p>
<p>This is my function:</p>
<pre><code>Database db = DatabaseFactory.CreateDatabase("ConnectionString");
DbCommand cmd = db.GetStoredProcCommand("FunctionName");
db.AddInParameter(cmd, "Value1", DbType.String, Param1Value);
db.AddInParameter(cmd, "Value2", DbType.String, Param2Value);
return Convert.ToBoolean(db.ExecuteScalar(cmd));
</code></pre>
<p>Here the db.ExecuteScalar(cmd) method returns null. This does not happen with Stored Procedures.</p>
<p>By the way, im using version 4.0</p>
<p>Thanks.</p>
|
<p>You have to create a select statement which selects the result from the function and execute that.</p>
<p>"SELECT * FROM FunctionName(@Value1, @Value2)"</p>
<p>Or you can wrap your function call in a procedure and call the procedure, I prefer this.</p>
|
<p>For scalar functions it would be</p>
<pre><code>SELECT FuncName(@Param1)
</code></pre>
<p>whereas a Table-Valued Function would be</p>
<pre><code>SELECT * FROM FuncName(@Param1)
</code></pre>
| 32,040
|
<p>I have an ASP.NET web page that displays a variety of fields that need to be updated best on certain conditions, button clicks and so on. We've implemented AJAX, using the ASP.NET Update Panel to avoid visible postbacks.</p>
<p>Originally there was only <em>one</em> area that needed this ability ... that soon expanded to other fields. Now my web page has multiple UpdatePanels. </p>
<p>I am wondering if it would be best to just wrap the entire form in a single UpdatePanel, or keep the individual UpdatePanels.</p>
<p>What are the best practices for using the ASP.NET UpdatePanel?</p>
|
<p>Multiple panels are much better. One of the main reasons for using UpdatePanels at all is to reduce the traffic and to only send the pieces that you need back and forth across the wire. By only using one update panel, you're pretty much doing a full post back every time, you're just using a little Javascript to update the page without a flicker.</p>
<p>If there are pieces of the page that need to be updated together, there are ways to trigger other panels to update when one does.. but you should definitely be using multiple update panels.</p>
|
<p>Not sure about the best practices, but in my experience multiple panels work well, and reduce the amount of data being sent at one time - resulting in an increase in response time overall. Multiple panels also reduce the complexity of each server call.</p>
| 9,814
|
<p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
|
<p>For some needs, a <a href="https://docs.python.org/library/collections.html#collections.deque" rel="noreferrer">deque</a> may also be useful. You can add and remove items on both ends of a deque at O(1) cost.</p>
<pre><code>from collections import deque
d = deque([1,2,3,4])
print d
for x in d:
print x
print d.pop(), d
</code></pre>
|
<p>My 2 cents </p>
<pre><code>class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.first = None
self.last = None
def add(self, x):
current = Node(x, None)
try:
self.last.next = current
except AttributeError:
self.first = current
self.last = current
else:
self.last = current
def print_list(self):
node = self.first
while node:
print node.value
node = node.next
ll = LinkedList()
ll.add("1st")
ll.add("2nd")
ll.add("3rd")
ll.add("4th")
ll.add("5th")
ll.print_list()
# Result:
# 1st
# 2nd
# 3rd
# 4th
# 5th
</code></pre>
| 35,431
|
<p>I am pretty sure that the settings that I am using are correct, so all possible things can be wrong which I should check out so that I can make authentication with our Active Directory work.</p>
|
<p>Try test if PHP can connect to active directory</p>
<pre><code><?php
$ds = ldap_connect('host.ad.lan', 389);
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
ldap_bind($ds, 'admin@ad.lan', 'xxx');
$sr = ldap_search($ds, 'CN=Cameron Zemek,OU=Users,OU=BRC,DC=ad,DC=lan', '(objectclass=*)', array('cn'));
$entryID = ldap_first_entry($ds, $sr);
$data = ldap_get_attributes($ds, $entryID);
print_r($data);
ldap_close($ds);
</code></pre>
<p>What do you have has your $config['ldap_user'] and $config['ldap_uid'] ? You want to set $config['ldap_uid'] to sAMAccountName</p>
|
<p>@grom... thanks but, yes PHP is working just fine. I have a WordPress and a MediaWiki installation on the same server, and they are both authenticating against the same active directory just fine.</p>
| 6,254
|
<p>How can I check whether a variable is defined in Ruby? Is there an <code>isset</code>-type method available?</p>
|
<p>Use the <code>defined?</code> keyword (<a href="http://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-defined-3F" rel="noreferrer">documentation</a>). It will return a String with the kind of the item, or <code>nil</code> if it doesn’t exist.</p>
<pre><code>>> a = 1
=> 1
>> defined? a
=> "local-variable"
>> defined? b
=> nil
>> defined? nil
=> "nil"
>> defined? String
=> "constant"
>> defined? 1
=> "expression"
</code></pre>
<p>As skalee commented: "It is worth noting that variable which is set to nil is initialized."</p>
<pre><code>>> n = nil
>> defined? n
=> "local-variable"
</code></pre>
|
<p>Also, you can check if it's defined while in a string via interpolation, if you code: </p>
<pre><code>puts "Is array1 defined and what type is it? #{defined?(@array1)}"
</code></pre>
<p>The system will tell you the type if it is defined.
If it is not defined it will just return a warning saying the variable is not initialized.</p>
<p>Hope this helps! :)</p>
| 36,757
|
<p>What are some good resources to learn best practices for Javascript? I'm mainly concerned about when something should be an object vs. when it should just be tracked in the DOM. Also I would like to better learn how to organize my code so it's easy to unit test.</p>
|
<p>Seconding <a href="http://oreilly.com/catalog/9780596517748/" rel="noreferrer">Javascript: The Good Parts</a> and Resig's book <a href="http://jsninja.com/" rel="noreferrer">Secrets of the Javascript Ninja</a>.</p>
<p>Here are some tips for Javascript:</p>
<ul>
<li>Don't pollute the global namespace (put all functions into objects/closures)
<ul>
<li>Take a look at <a href="http://developer.yahoo.com/yui/" rel="noreferrer">YUI</a>, it's a huge codebase with only 2 global objects: YAHOO and YAHOO_config</li>
</ul></li>
<li>Use the Module pattern for singletons (<a href="http://yuiblog.com/blog/2007/06/12/module-pattern/" rel="noreferrer">http://yuiblog.com/blog/2007/06/12/module-pattern/</a>)</li>
<li>Make your JS as reusable as possible (jQuery plugins, YUI modules, basic JS objects.) Don't write tons of global functions.</li>
<li>Don't forget to var your variables</li>
<li>Use JSlint : <a href="http://www.jslint.com/" rel="noreferrer">http://www.jslint.com/</a></li>
<li>If you need to save state, it's probably best to use objects instead of the DOM.</li>
</ul>
|
<p>You can pick up a lot from <a href="https://rads.stackoverflow.com/amzn/click/com/1590597273" rel="nofollow noreferrer" rel="nofollow noreferrer">Pro JavaScript Techniques</a>, and I'm looking forward to Resig's forthcoming <a href="http://jsninja.com/" rel="nofollow noreferrer">Secrets of the JavaScript Ninja</a>.</p>
| 6,080
|
<p>I need to get a count of the number of files in a directory. I could get the names of all the files in the directory using <code>System.IO.Directory.GetFiles()</code> and take the length of that array but that takes too long on large directories. Is there a way to get just the count without having to get the names?</p>
|
<p>I don't believe so, no - at least not in vanilla .NET. I suspect it's not the actual fetching of the names that takes the time - it's the OS walking through the directory internals. There <em>may</em> be a Win32 call you could make via P/Invoke.</p>
<p>How large is the directory you're looking at? In general it's at least <em>traditionally</em> not been a good idea to have more than a few hundred files in a directory. File systems have improved at this in general, but I don't know what the current state is with NTFS and Fat32.</p>
|
<p>So far, in most languages I came across, you get this information only by walking the folder and counting the files. I doubt there is a Windows API call to get only the count (but I can be surprised!).<br>
Advantage of the method: flexibility - you can filter out some file types, walk down recursively or ignore folders, etc.</p>
<p>If the method is slow for you, maybe you should get a better method, like not creating an array filled with directory info (takes time to fill it! not to mention memory cost and garbage collection time) but using an iterator: a bit more work (but once you get the function, it is always there) but much more efficient.</p>
| 45,444
|
<p>I am new to the world of ASP.NET and SQL server, so please pardon my ignorance ...</p>
<p>If I have a data structure in C# (for e.g. let's just say, a vector that stores some strings), is it possible to store the contents of the vector as is in SQL table? I want to do this so that it fast to convert that data back into vector form as fast as possible without having to construct it element by element. Almost like writing binary data to a file and then reading it and copying it to an allocated structure in C.</p>
<p>I've created a table on SQL Server 2008 for which a field is defined as VARBINARY(MAX). I thought I'd start with that.</p>
<p>Could someone show me an example of how I would go about storing and retrieving a vector of, say, 10 strings, into and from that field? Is this even possible (I can't think of why not)?</p>
<p>Thanks!</p>
|
<p>First, there is the obvious route of simply creating a relational structure and mapping the object to fields in the database.</p>
<p>Second, if you have an object that is serializable, you can store it in SQL server. I have done this on occasion, and have used the Text data type in SQL Server to store the XML. </p>
<p><strong><em>Opinion: I prefer to store serialized objects as XML instead of binary data.</em></strong> Why? Because you can actually read what is in there (for debugging), and in SQL Server you can use XQuery to select data from the serialized object. From my experience, the performance gain of using binary data will not be worth it compared to having data that is easier to debug and can be used in a psuedo-relational fashion. Take a look at <a href="http://msdn.microsoft.com/en-us/library/ms345122(SQL.90).aspx" rel="noreferrer">SQL Server's XQuery capabilities</a>. Even if you don't plan on using it right away, there is no reason to put yourself in a corner.</p>
<p>You might look at some examples using the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.netdatacontractserializer.aspx" rel="noreferrer">NetDataContractSerializer</a>.</p>
<p>I believe what you call a vector is a List<> in C#. Take a look in System.Collections.Generic. You can use the NetDataContractSerializer to serialize a List of 3 strings like:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
namespace SerializeThingy
{
class Program
{
static void Main(string[] args)
{
List<string> myList = new List<string>();
myList.Add("One");
myList.Add("Two");
myList.Add("Three");
NetDataContractSerializer serializer = new NetDataContractSerializer();
MemoryStream stream = new MemoryStream();
serializer.Serialize(stream, myList);
stream.Position = 0;
Console.WriteLine(ASCIIEncoding.ASCII.GetString(stream.ToArray()));
List<string> myList2 = (List<string>)serializer.Deserialize(stream);
Console.WriteLine(myList2[0]);
Console.ReadKey();
}
}
}
</code></pre>
<p>This example just serializes a list, outputs the serialization to the console, and then proves it was hydrated correctly on the flip side. I think you can see that from here you could either dump the memory stream into a string and write that to the database, or use another stream type than a memory stream to do it.</p>
<p>Remember to reference System.Runtime.Serialization to get access to the NetDataContractSerializer.</p>
|
<p>I have more experience with relational databases than c#, but binary serialization is an acceptable way to go, as it allows the entire object's state to be saved into the database. XML serialization is pretty much the same, although generic types are not allowed.</p>
| 26,694
|
<p>I have a control that is modelled on a <strong>ComboBox</strong>. I want to render the control so that the control <strong>border</strong> looks like that of a standard <strong>Windows ComboBox</strong>. Specifically, I have followed the MSDN documentation and all the rendering of the control is correct except for rendering when the control is disabled.</p>
<p>Just to be clear, this is for a system with <strong>Visual Styles</strong> enabled. Also, all parts of the control render properly except the border around a disabled control, which does not match the disabled <strong>ComboBox border</strong> colour.</p>
<p>I am using the <strong>VisualStyleRenderer</strong> class. MSDN suggests using the <code>VisualStyleElement.TextBox</code> element for the <strong>TextBox</strong> part of the <strong>ComboBox</strong> control but a standard disabled <strong>TextBox</strong> and a standard disabled <strong>ComboBox</strong> draw slightly differently (one has a light grey border, the other a light blue border).</p>
<p>How can I get correct rendering of the control in a disabled state?</p>
|
<p>I'm not 100% sure if this is what you are looking for but you should check out the <strong>VisualStyleRenderer</strong> in the System.Windows.Forms.VisualStyles-namespace.</p>
<ol>
<li><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.visualstyles.visualstylerenderer.aspx" rel="noreferrer">VisualStyleRenderer class</a> (MSDN)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms171735.aspx" rel="noreferrer">How to: Render a Visual Style Element</a> (MSDN)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.visualstyles.visualstyleelement.combobox.dropdownbutton.disabled.aspx" rel="noreferrer">VisualStyleElement.ComboBox.DropDownButton.Disabled</a> (MSDN)</li>
</ol>
<p>Since VisualStyleRenderer won't work if the user don't have visual styles enabled (he/she might be running 'classic mode' or an operative system prior to Windows XP) you should always have a fallback to the ControlPaint class.</p>
<pre><code>// Create the renderer.
if (VisualStyleInformation.IsSupportedByOS
&& VisualStyleInformation.IsEnabledByUser)
{
renderer = new VisualStyleRenderer(
VisualStyleElement.ComboBox.DropDownButton.Disabled);
}
</code></pre>
<p>and then do like this when drawing:</p>
<pre><code>if(renderer != null)
{
// Use visual style renderer.
}
else
{
// Use ControlPaint renderer.
}
</code></pre>
<p>Hope it helps!</p>
|
<p>Are any of the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.controlpaint_members.aspx" rel="nofollow noreferrer">ControlPaint</a> methods useful for this? That's what I usually use for custom-rendered controls.</p>
| 2,503
|
<p>ShellExecute() allows me to perform simple shell tasks, allowing the system to take care of opening or printing files. I want to take a similar approach to sending an email attachment programmatically.</p>
<p>I don't want to manipulate Outlook directly, since I don't want to assume which email client the user uses by default. I don't want to send the email directly, as I want the user to have the opportunity to write the email body using their preferred client. Thus, I really want to accomplish exactly what Windows Explorer does when I right click a file and select Send To -> Mail Recipient.</p>
<p>I'm looking for a C++ solution.</p>
|
<p>This is my MAPI solution:</p>
<pre><code>#include <tchar.h>
#include <windows.h>
#include <mapi.h>
#include <mapix.h>
int _tmain( int argc, wchar_t *argv[] )
{
HMODULE hMapiModule = LoadLibrary( _T( "mapi32.dll" ) );
if ( hMapiModule != NULL )
{
LPMAPIINITIALIZE lpfnMAPIInitialize = NULL;
LPMAPIUNINITIALIZE lpfnMAPIUninitialize = NULL;
LPMAPILOGONEX lpfnMAPILogonEx = NULL;
LPMAPISENDDOCUMENTS lpfnMAPISendDocuments = NULL;
LPMAPISESSION lplhSession = NULL;
lpfnMAPIInitialize = (LPMAPIINITIALIZE)GetProcAddress( hMapiModule, "MAPIInitialize" );
lpfnMAPIUninitialize = (LPMAPIUNINITIALIZE)GetProcAddress( hMapiModule, "MAPIUninitialize" );
lpfnMAPILogonEx = (LPMAPILOGONEX)GetProcAddress( hMapiModule, "MAPILogonEx" );
lpfnMAPISendDocuments = (LPMAPISENDDOCUMENTS)GetProcAddress( hMapiModule, "MAPISendDocuments" );
if ( lpfnMAPIInitialize && lpfnMAPIUninitialize && lpfnMAPILogonEx && lpfnMAPISendDocuments )
{
HRESULT hr = (*lpfnMAPIInitialize)( NULL );
if ( SUCCEEDED( hr ) )
{
hr = (*lpfnMAPILogonEx)( 0, NULL, NULL, MAPI_EXTENDED | MAPI_USE_DEFAULT, &lplhSession );
if ( SUCCEEDED( hr ) )
{
// this opens the email client with "C:\attachment.txt" as an attachment
hr = (*lpfnMAPISendDocuments)( 0, ";", "C:\\attachment.txt", NULL, NULL );
if ( SUCCEEDED( hr ) )
{
hr = lplhSession->Logoff( 0, 0, 0 );
hr = lplhSession->Release();
lplhSession = NULL;
}
}
}
(*lpfnMAPIUninitialize)();
}
FreeLibrary( hMapiModule );
}
return 0;
}
</code></pre>
|
<p>You'll need to implement a <a href="http://msdn.microsoft.com/en-us/library/ms527046.aspx" rel="nofollow noreferrer">MAPI client.</a> This will let you prefill the document, add attachments, etc.. before presenting the message to the user to send off. You can use the default message store to use their default mail client.</p>
| 32,854
|
<p>I'm working on a web app that needs an ActiveX control to function. It installs just fine when the user has admin privileges, but fails to load otherwise. Is this by design and if so, is this documented somewhere? (preferably MSDN)</p>
|
<p>Actually, none of these answers are completely correct; if you install an ActiveX control in a per-user basis it will work just fine without Administrative privileges, regardless of the group that the user is in. Bascially this involves installing it to HKEY_CURRENT_USER instead of HKEY_LOCAL_MACHINE.</p>
<p>Depending on what your activex control is written in this may be easy or it may be hard to change; with ATL 9 it's pretty easy, as you just have to call a function:</p>
<pre><code>AtlSetPerUserRegistration(perUser);
</code></pre>
<p><a href="https://www.firebreath.org" rel="nofollow">FireBreath</a> does this by default so that admin privileges aren't neccesary to install the plugin/control; it also has a <a href="https://github.com/firebreath/FireBreath/blob/master/src/ActiveXCore/axutil.cpp#L48" rel="nofollow">workaround for older versions of ATL</a> (ATL 9 is VS 2008). This is all C++, so if your control is written in something else I don't know how to fix it, but that should at least get you started.</p>
|
<p><strong>Complex answer: Yes.</strong> The user's account needs to be part of a group that affords the privelege of registering libraries (dll) or controls (ocx) or needs to be directly assigned the privelege.</p>
<p><strong>Simple answer: No.</strong> Only accounts with the administrative privelege to install OCXs or DLLs can install Active-X controls (by <em>default</em> those accounts are part of the Administrators, Domain Administrators or Power Users groups).</p>
<p>Edit: I guess this question was changed... Yes, this is by design.</p>
| 43,965
|
<p>I would like to create a link between a winMo device and a server, so that they can pass information back and forth to each other. I actually don't really know where to start, I've had SOAP, RPC and creating a TCP link suggested to me. If someone could provide a link to an example that would be great.</p>
<p>Thanks!</p>
<p>Thanks for the responses. Updates:</p>
<ul>
<li>It's not critical that the server initiate the communications, I could have the mobile device poll the server</li>
<li>timing is not ultra critical </li>
<li>I would prefer that it uses some open standard, if I wanted to also communicate with a palm device as well for example.</li>
<li>I had the idea that webservices were one way, unless the mobile device runs a server also?!</li>
</ul>
|
<p>Your best bet is to set up an ASP.NET web service on the server, and then have your PDA application talk to it.</p>
<p>You can also use the web service to talk back to the PDA. Essentially, the PDA has to initially call the web service and pass in a delegate method that the server then calls when it needs to talk to the PDA. I do not recommend this latter method, especially in an environment where the PDA is not continuously connected to the network. It's usually better to have the PDA initiate each contact with the server.</p>
|
<p>I'm setting up a project doing exactly this, and I'm using a web service to do the talking. </p>
<p>You can also access SQL Server directly using <i>sqlClient</i>, synchronize data with the SQL Server 2005 Compact Edition "Remote Data Access" or use SQL Server Merge Replication. </p>
<p>I'm not sure what the differences are between these things, but I got the list from <a href="http://www.microsoft.com/MSPress/books/10294.aspx" rel="nofollow noreferrer">"Microsoft Mobile Development Handbook"</a> by Wigley, Moth & Foot. </p>
| 28,940
|
<p>I know that jQuery and prototype have a $.each() function for iterating over each element in an array. Does YUI offer any help with this?</p>
|
<p>What keeps you from simply <em>iterating</em> the array?</p>
<pre><code>for(var i=0; i<ary.length; i++)
// assuming that ary[] contains objects with a DoSometing() method
ary[i].doSomething();
</code></pre>
|
<p>In YUI3:</p>
<pre><code>Y.Array.each(myArray, function(element) {
Y.log(element);
});
</code></pre>
<p>or even:</p>
<pre><code>Y.Array.each(myArray, function(element, index, array) {
...
});
</code></pre>
| 36,640
|
<p>I need to replace the standard Overflow function in a ToolStrip to a "More..." button which would then pop up a menu with the overflowed items. Does anyone have any ideas about how to accomplish this?</p>
|
<p>I wrote something very similar to this awhile ago. The code I used is pasted below, and you are free to modify it to suit your needs. </p>
<p>The ToolStripCustomiseMenuItem is basically your "More" button that populates a DropDown Context Menu when clicked. Hope this helps you, at the very least this should be a good starting point…</p>
<pre><code> public class ToolStripCustomiseMenuItem : ToolStripDropDownButton {
public ToolStripCustomiseMenuItem()
: base("Add Remove Buttons") {
this.Overflow = ToolStripItemOverflow.Always;
DropDown = CreateCheckImageContextMenuStrip();
}
ContextMenuStrip checkImageContextMenuStrip = new ContextMenuStrip();
internal ContextMenuStrip CreateCheckImageContextMenuStrip() {
ContextMenuStrip checkImageContextMenuStrip = new ContextMenuStrip();
checkImageContextMenuStrip.ShowCheckMargin = true;
checkImageContextMenuStrip.ShowImageMargin = true;
checkImageContextMenuStrip.Closing += new ToolStripDropDownClosingEventHandler(checkImageContextMenuStrip_Closing);
checkImageContextMenuStrip.Opening += new CancelEventHandler(checkImageContextMenuStrip_Opening);
DropDownOpening += new EventHandler(ToolStripAddRemoveMenuItem_DropDownOpening);
return checkImageContextMenuStrip;
}
void checkImageContextMenuStrip_Opening(object sender, CancelEventArgs e) {
}
void ToolStripAddRemoveMenuItem_DropDownOpening(object sender, EventArgs e) {
DropDownItems.Clear();
if (this.Owner == null) return;
foreach (ToolStripItem ti in Owner.Items) {
if (ti is ToolStripSeparator) continue;
if (ti == this) continue;
MyToolStripCheckedMenuItem itm = new MyToolStripCheckedMenuItem(ti);
itm.Checked = ti.Visible;
DropDownItems.Add(itm);
}
}
void checkImageContextMenuStrip_Closing(object sender, ToolStripDropDownClosingEventArgs e) {
if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked) {
e.Cancel = true;
}
}
}
internal class MyToolStripCheckedMenuItem : ToolStripMenuItem {
ToolStripItem tsi;
public MyToolStripCheckedMenuItem(ToolStripItem tsi)
: base(tsi.Text) {
this.tsi = tsi;
this.Image = tsi.Image;
this.CheckOnClick = true;
this.CheckState = CheckState.Checked;
CheckedChanged += new EventHandler(MyToolStripCheckedMenuItem_CheckedChanged);
}
void MyToolStripCheckedMenuItem_CheckedChanged(object sender, EventArgs e) {
tsi.Visible = this.Checked;
}
}
</code></pre>
|
<p>You can trap the paint event on the button by calling</p>
<pre><code>toolStrip1.OverflowButton.Paint += new PaintEventHandler(OverflowButton_Paint);
</code></pre>
<p>Which in theory should allow you to make it say "More...", but I was unable to set the width of the Overflow Button to be anything but the (narrow) default width.</p>
<p>Also, another idea was that you can trap <code>VisibleChanged</code> on the OverflowButton then manually inject a split button into the toolstrip. The tricky part is figuring out where to put that button.</p>
| 29,101
|
<p>Does anyone have a method to understand complex SQL statements? When reading structural / OO code there are usually layers of abstraction that help you break it down into manageable chunks. Often in SQL, though, it seems that you have to keep track of what's going on in multiple parts of a query all at the same time.</p>
<p>The impetus for this question is the SQL query discussed in <a href="https://stackoverflow.com/questions/378548/need-help-with-a-complex-join-statement-in-sql">this question about a complex join</a>. After staring at the answer queries for a number of minutes I finally decided to step through the query using particular records to see what was going on. That was the only way I could think of to understand the query piece by piece.</p>
<p>Is there a better way to break a SQL query down into manageable pieces?</p>
|
<p>When I look at a complex bit of SQL Code, this is what I do.</p>
<p>First, if it is an update or delete, I add code (if it isn't there and commented out) to make it a select. Never try an update or delete for the first time without seeing the results in a select first. If it is an update, I make sure the select shows the current value and what I will be setting it to in order to make sure that I'm getting the desired result.</p>
<p>Understanding the joins is critical to understanding complex SQL. For every join I ask myself why is this here? There are four basic reasons. You need a column for the select, you need a field for the where clause, you need the join as a bridge to a third table, or you need to join to the table to filter records (such as retrieving details on customer who have orders but not needing the order details, this can often be done better with an IF EXISTS where clause). If it is a left or right join (I tend to rewrite so everything is a left join which makes life simpler.), I consider whether an inner join would work. Why do I need a left join? If I don't know the answer, I will run it both ways and see what the difference is within the data. If there are derived tables, I will look at those first (running just that part of the select to see what the result is) to understand why it is there. If there are sub-queries, I will try to understand them and if they are slow will try to convert to a derived table instead as those are often much faster.</p>
<p>Next, I look at the <code>where</code> clauses. This is one place where a solid foundation in your particular database will come in handy. For instance, I know in my databases what occasions I might need to see only the mailing address and what occasions I might need to see other addresses. This helps me to know if something is missing from the where clause. Otherwise I consider each item in the <code>where</code> clause and figure out why it would need to be there, then I consider whether there is anything missing that should be there. After looking it over, I consider if I can make adjustments to make the query sargable.</p>
<p>I also consider any complex bits of the select list next. What does that case statement do? Why is there a subquery? What do those functions do? (I always look up the function code for any function I'm not already familiar with.) Why is there a distinct? Can it be gotten rid of by using a derived table or aggregate function and group by statements?</p>
<p><strong>Finally and MOST important</strong>, I run the select and determine if the results look correct based on my knowledge of the business. <em>If you don't understand your business, you won't know if the query is correct</em>. Syntactically correct doesn't mean the right results. Often there is a part of your existing user interface that you can use as a guide to whether your results are correct. If I have a screen that shows the orders for a customer and I'm doing a report that includes the customer orders, I might spot check a few individual customers to make sure it is showing the right result.</p>
<p>If the current query is filtering incorrectly, I will remove bits of it to find out what is getting rid of the records I don't want or adding ones I don't want. Often you will find that the join is one to many and you need one to one (use a derived table in this case!) or you will find that some piece of information that you think you need in the <code>where</code> clause isn't true for all the data you need or that some piece of the <code>where</code> clause is missing. It helps to have all the fields in the <code>where</code> clause (if they weren't in the select already) in the select at the time you do this. It may even help to show all the fields from all the joined tables and really look at the data. When I do this, I often add a small bit to the where clause to grab just some of the records that I have that shouldn't be there rather than all the records.</p>
<p>One sneaky thing that will break a lot of queries is the <code>where</code> clause referencing a field in a table on the right side of a left join. That turns it into an inner join. If you really need a left join, you should add those kinds of conditions to the join itself.</p>
|
<p>Query optimizers can handle a lot, including implementing your sub-query as a join. These days, they can even handle non-correlated sub-queries.</p>
<p>Clarity is more important than performance in most cases, and sub-queries are easier to debug.</p>
<p>BTW: why do you use confusing table aliases?</p>
| 49,657
|
<p>Is it possible to configure <a href="http://www.apachefriends.org/en/xampp.html" rel="noreferrer">xampp</a> to serve up a file outside of the <code>htdocs</code> directory?</p>
<p>For instance, say I have a file located as follows:</p>
<p><code>C:\projects\transitCalculator\trunk\TransitCalculator.php</code></p>
<p>and my <a href="http://www.apachefriends.org/en/xampp.html" rel="noreferrer">xampp</a> files are normally served out from:</p>
<p><code>C:\xampp\htdocs\</code></p>
<p>(because that's the default configuration) Is there some way to make Apache recognize and serve up my <code>TransitCalculator.php</code> file without moving it under <code>htdocs</code>? Preferably I'd like Apache to serve up/have access to the entire contents of the projects directory, and I don't want to move the projects directory under <code>htdocs</code>.</p>
<p>edit: edited to add Apache to the question title to make Q/A more "searchable"</p>
|
<p>Ok, per <a href="https://stackoverflow.com/questions/1408/#2471">pix0r</a>'s, <a href="https://stackoverflow.com/questions/1408/#1413">Sparks</a>' and <a href="https://stackoverflow.com/questions/1408/#1414">Dave</a>'s answers it looks like there are three ways to do this:</p>
<hr>
<h2><a href="https://stackoverflow.com/questions/1408/#2471">Virtual Hosts</a></h2>
<ol>
<li>Open C:\xampp\apache\conf\extra\httpd-vhosts.conf.</li>
<li>Un-comment ~line 19 (<code>NameVirtualHost *:80</code>).</li>
<li><p>Add your virtual host (~line 36):</p>
<pre><code><VirtualHost *:80>
DocumentRoot C:\Projects\transitCalculator\trunk
ServerName transitcalculator.localhost
<Directory C:\Projects\transitCalculator\trunk>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
</code></pre></li>
<li><p>Open your hosts file (C:\Windows\System32\drivers\etc\hosts).</p></li>
<li><p>Add</p>
<pre><code>127.0.0.1 transitcalculator.localhost #transitCalculator
</code></pre>
<p>to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed).</p></li>
<li>Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble).</li>
<li>Restart Apache.</li>
</ol>
<p>Now you can access that directory by browsing to <a href="http://transitcalculator.localhost/" rel="noreferrer">http://transitcalculator.localhost/</a>.</p>
<hr>
<h2><a href="https://stackoverflow.com/questions/1408/#1413">Make an Alias</a></h2>
<ol>
<li><p>Starting ~line 200 of your <code>http.conf</code> file, copy everything between <code><Directory "C:/xampp/htdocs"></code> and <code></Directory></code> (~line 232) and paste it immediately below with <code>C:/xampp/htdocs</code> replaced with your desired directory (in this case <code>C:/Projects</code>) to give your server the correct permissions for the new directory.</p></li>
<li><p>Find the <code><IfModule alias_module></IfModule></code> section (~line 300) and add</p>
<pre><code>Alias /transitCalculator "C:/Projects/transitCalculator/trunk"
</code></pre>
<p>(or whatever is relevant to your desires) below the <code>Alias</code> comment block, inside the module tags.</p></li>
</ol>
<hr>
<h2><a href="https://stackoverflow.com/questions/1408/#1414">Change your document root</a></h2>
<ol>
<li><p>Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change <code>DocumentRoot "C:/xampp/htdocs"</code> to <code>#DocumentRoot "C:/Projects"</code> (or whatever you want).</p></li>
<li><p>Edit ~line 203 to match your new location (in this case <code>C:/Projects</code>).</p></li>
</ol>
<hr>
<p><strong>Notes:</strong> </p>
<ul>
<li>You have to use forward slashes "/" instead of back slashes "\".</li>
<li>Don't include the trailing "/" at the end.</li>
<li><em>restart your server</em>.</li>
</ul>
|
<p>Solution to allow Apache 2 to host websites outside of htdocs:</p>
<p>Underneath the "DocumentRoot" directive in httpd.conf, you should see a directory block. Replace this directory block with:</p>
<pre><code><Directory />
Options FollowSymLinks
AllowOverride All
Allow from all
</Directory>
</code></pre>
<p><strong><em>REMEMBER NOT TO USE THIS CONFIGURATION IN A REAL ENVIRONMENT</em></strong></p>
| 2,381
|
<p>If I query a table with a condition on the key field as in:</p>
<pre><code> var user = from u in dc.Users
where u.UserName == usn
select u;
</code></pre>
<p>I know that I will either get zero results or one result. Should I still go ahead and retrieve the results using a for-each or is there another preferred way to handle this kind of situation. </p>
|
<p>Try something like this:</p>
<pre><code>var user = (from u in dc.Users
where u.UserName == usn
select u).FirstOrDefault();
</code></pre>
<p>The <a href="http://msdn.microsoft.com/en-us/library/bb549141.aspx" rel="noreferrer">FirstOrDefault</a> method returns the first element of a sequence that satisfies a specified condition or a default value if no such element is found.</p>
|
<p>Another option is to use Contains(username) as opposed to "=="</p>
<pre><code>var user = (from u in dc.UserInfo
where u.Users.Contains(username)
select u).SingleOrDefault();
</code></pre>
| 25,058
|
<p>I'm planning to install Drupal. Is there any reason not to install the latest 6.x version as opposed to the 5.x branch? Are there any really good modules that are 5.x only?</p>
|
<p>I've found enough modules to happily run my site on Drupal 6.x I think the only 5.x module I miss is one that did very easy Google ad integration, and that may have been updated I just haven't checked recently. I don't get enough traffic to make the ads worth the time in setting them up, so I just use the search part of the ad campaign.</p>
<p>Drupal 7.x is under development now, so I would expect that anything that hasn't been moved from 5.x to 6.x is just not being developed anymore, and is probably not really that needed.</p>
<p>Ultimately, take a look at what modules you may need. With an account on Drupal's site, you can filter by install type. I found that 6.x is much easier to work with in some regards (managing and upgrading modules) and overall I've had a much easier time maintaining my site under Drupal 6.x than I did under 4.x or 5.x.</p>
<p>I also think that 6.x runs much faster.</p>
|
<p>The one significant CCK-related module that's not D6 production ready is <a href="http://www.drupal.org/project/filefield" rel="nofollow noreferrer">filefield</a>. This may not be an issue if you're not doing anything substantial with images and media, but might be worth considering if you're going to do any serious DAM. Otherwise, I think we're (finally!) to the point where it's making more sense to go with D6 than D5. Either way, it's definitely worth the time to architect the site according to your specific needs, figure out what modules you'll need and find out if any of them have yet to be updated.</p>
| 13,530
|
<p>this c# code is probably not the most efficient but gets what I want done. </p>
<p>How do I accomplish the same thing in F# code?</p>
<pre><code> string xml = " <EmailList> " +
" <Email>test@email.com</Email> " +
" <Email>test2@email.com</Email> " +
" </EmailList> ";
XmlDocument xdoc = new XmlDocument();
XmlNodeList nodeList;
String emailList = string.Empty;
xdoc.LoadXml(xml);
nodeList = xdoc.SelectNodes("//EmailList");
foreach (XmlNode item in nodeList)
{
foreach (XmlNode email in item)
{
emailList += email.InnerText.ToString() + Environment.NewLine ;
}
}
</code></pre>
|
<pre><code>let doc = new XmlDocument() in
doc.LoadXml xml;
doc.SelectNodes "/EmailList/Email/text()"
|> Seq.cast<XmlNode>
|> Seq.map (fun node -> node.Value)
|> String.concat Environment.NewLine
</code></pre>
<p>If you actually want the final trailing newline you can add it in the map and String.concat with the empty string.</p>
|
<p>If you look at your code, you have a couple of things going on. The first is loading the collection for the Email nodes, and the second is actually doing something meaningful with them.</p>
<p>First, you'd want to have your function return a collection. Something like (and I'm on my Mac, so this may not work):</p>
<pre><code>
List<string> EmailAddresses(string xml)
{
XmlDocument xdoc = new XmlDocument();
XmlNodeList nodeList;
String emailList = string.Empty;
xdoc.LoadXml(xml);
nodeList = xdoc.SelectNodes("//EmailList");
foreach (XmlNode item in nodeList)
{
foreach (XmlNode email in item)
{
yield email.InnerText.ToString();
}
}
}
</code></pre>
<p>Now the question comes around what you want to do with that collection. In your example above, you were concatenating it, or basically storing state. </p>
<p>From a C# perspective, you can then start using things like the answers from <a href="https://stackoverflow.com/questions/217805/using-linq-to-concatenate-strings">this question</a> (using LINQ) and <a href="https://stackoverflow.com/questions/145856/how-to-join-int-to-a-charcter-separated-string-in-c">this one</a>. </p>
<p>From an F# perspective, you now have a list and can simply use the normal procedures for a list like <a href="http://blogs.msdn.com/chrsmith/archive/2008/07/10/mastering-f-lists.aspx" rel="nofollow noreferrer">this one</a> or <a href="http://www.fsharphelp.com/Lists.aspx" rel="nofollow noreferrer">here</a>.</p>
<p>You can also look at <a href="http://msdn.microsoft.com/en-us/library/bb387098.aspx" rel="nofollow noreferrer">LINQ to XML</a> (or at the <a href="http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx" rel="nofollow noreferrer">5 minute overview</a>) to get some more ideas.</p>
| 43,143
|
<p>I'm really new to .NET, and I still didn't get the hang about how configuration files work.</p>
<p>Every time I search on Google about it I get results about web.config, but I'm writing a Windows Forms application.</p>
<p>I figured out that I need to use the System.Configuration namespace, but the documentation isn't helping.</p>
<p>How do I define that my configuration file is XYZ.xml? Or does it have a "default" name for the configuration file? I still didn't get that.</p>
<p>Also, how do I define a new section? Do I really need to create a class which inherits from ConfigurationSection?</p>
<p>I would like to just have a configuration file with some values like this:</p>
<pre><code><MyCustomValue>1</MyCustomValue>
<MyCustomPath>C:\Some\Path\Here</MyCustomPath>
</code></pre>
<p>Is there a simple way to do it? Can you explain in a simple way how to read and write from/to a simple configuration file?</p>
|
<p>You want to use an App.Config.</p>
<p>When you add a new item to a project there is something called Applications Configuration file. Add that.</p>
<p>Then you add keys in the configuration/appsettings section</p>
<p>Like:</p>
<pre><code><configuration>
<appSettings>
<add key="MyKey" value="false"/>
</code></pre>
<p>Access the members by doing</p>
<pre><code>System.Configuration.ConfigurationSettings.AppSettings["MyKey"];
</code></pre>
<p>This works in .NET 2 and above.</p>
|
<p>What version of .NET and Visual Studio are you using?</p>
<p>When you created the new project, you should have a file in your solution called <em>app.config</em>. That is the default configuration file.</p>
| 13,983
|
<p>I'm discovering a simple solution for singular-plural keywords searches. I heard about stemming but I don't want to use all its features, only plural/singular transformation. The language is Dutch. Have looked at <a href="http://www.snowball.tartarus.org" rel="nofollow noreferrer">http://www.snowball.tartarus.org</a> before. Does anyone know the simple solution for singular|plural relevant searches?
Thanks in advance.</p>
|
<p>Use a dictionary, a list of stopwords (those you don't want to singularize) plus the rules for the language. If you don't know Dutch then I cannot help you, but show you how it'd be done in Spanish, for instance:</p>
<ul>
<li>Plurals end with s, if it doesn't then it's done
<ul>
<li>If it ends with s,
<ul>
<li>check if it's a verb or conjugation ending with s if it is one, then it's done (verbs could be added to the stopwords list)</li>
<li>if it's not a verb, remove s </li>
<li>if the word exists in the dictionary, done</li>
<li>if it doesn't remove the previous letter, and check it in the dictionary.</li>
<li>if it's still not there it's an exception you'll need to check manually to code in the exceptions (I cannot right now think of any, but they always exist :)</li>
</ul></li>
</ul></li>
</ul>
<p>Of course this will not translate directly to Dutch.</p>
<p>In general stemmers are already done and provide most of what you need, why don't you want them?</p>
|
<p>Stemmers caused much user annoyance, so if I use one of them, all functionality except singular/plural should be disabled. So the requirement is to use only plural/singular transformations.</p>
| 19,053
|
<p>I like <a href="http://code.msdn.microsoft.com/sourceanalysis" rel="noreferrer">StyleCop</a>'s static code analysis and rules enforcement. However, it is severely lacking in several key departments. </p>
<ul>
<li>Adding new rules isn't officially supported and from what I hear pretty difficult.</li>
<li>Automatic "fixing" of trivial rules violations would be nice! Perhaps not with variable naming but with method ordering (static, etc) this would be a huge time saver.</li>
<li>Microsofts "one-size-fits-all" approach to StyleCop is kind of restrictive. I would like to have a custom set of rules for our in-house standards.</li>
</ul>
<p>Is there such a commercial product out there?</p>
<p><a href="http://blogs.interakting.co.uk/images/blogs_interakting_co_uk/dominicz/WindowsLiveWriter/MicrosoftStyleCopSourcecodeanalysisforfo_D8EF/styleCopErrors_6.gif" rel="noreferrer">alt text http://blogs.interakting.co.uk/images/blogs_interakting_co_uk/dominicz/WindowsLiveWriter/MicrosoftStyleCopSourcecodeanalysisforfo_D8EF/styleCopErrors_6.gif</a></p>
|
<p>Adding rules is, or is going to be, <a href="http://blogs.msdn.com/sourceanalysis/archive/2008/08/19/stylecop-4-3-is-released.aspx" rel="noreferrer">officially supported</a>:</p>
<blockquote>
<p>As promised, we will also be releasing
SDK documentation for StyleCop
explaining how to author custom rules
and how to integrate the tool into
custom build environments. The SDK
documentation is currently under final
review and we hope to release it very
soon.
-- <a href="http://blogs.msdn.com/sourceanalysis/archive/2008/08/19/stylecop-4-3-is-released.aspx" rel="noreferrer">JasonAll</a></p>
</blockquote>
<p>In terms of our "in-house" style, I got pretty close by disabling a handful of StyleCop rules:</p>
<ul>
<li>File Headers (SA1633-SA-1640)</li>
<li>Code ordering (SA1200-SA1202)</li>
<li>Requiring "this" (SA1101)</li>
</ul>
<p>You can do this globally by modifying the Settings.StyleCop file in the installation directory, though I've taken the approach of putting one at the root of our source tree in each project.</p>
<p>The end effect is much what we want. There are a handful of "in-house" choices that would be nice to flag, but even without them StyleCop is delivering a lot of value for us.</p>
|
<p>I often write unit tests to reflect over my types and check for violations of my custom rules.</p>
<p>Here's an example for verifying that certain types are immutable: <a href="http://blogs.msdn.com/kevinpilchbisson/archive/2007/11/20/enforcing-immutability-in-code.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/kevinpilchbisson/archive/2007/11/20/enforcing-immutability-in-code.aspx</a></p>
<p>Here's another, for rules about unit test naming:
<a href="http://jbazuzicode.blogspot.com/2008/11/keeping-test-fixture-and-class-names.html" rel="nofollow noreferrer">http://jbazuzicode.blogspot.com/2008/11/keeping-test-fixture-and-class-names.html</a></p>
<p>EDIT: The 2nd link seems to be lost to the sands of time. </p>
| 36,360
|
<p>I'm using Apache.</p>
<p>I'm auto gzipping my HTML & CSS files on the fly using the following directive in my .htaccess file.</p>
<pre><code># Enable ETag
FileETag MTime Size
# Set expiration header
ExpiresActive on
ExpiresDefault "access plus 1 year"
ExpiresByType image/gif A2592000
ExpiresByType image/png A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType text/css A2592000
ExpiresByType text/javascript A2592000
ExpiresByType text/js A2592000
# Compress some text file types
AddOutputFilterByType DEFLATE text/html text/css text/xml application/x-javascript text/javascript text/js
# Deactivate compression for buggy browsers
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</code></pre>
<p>However, when I use the Firebug plugin for Firefox, I notice that my javascript files are NOT being gzipped (only my HTML and CSS files are).</p>
<p><strong>Any ideas why my JavaScript files are not being gzipped on the fly by Apache?</strong></p>
|
<p>I figured it out, looks like I need it to be:</p>
<pre><code>AddOutputFilterByType DEFLATE text/html text/plain text/css text/xml application/x-javascript text/javascript application/javascript
</code></pre>
<p>To get javascript to compress/gzip</p>
|
<p>Have you declared the text/javascript MIME type in Apache? If your server configuration points to, say, a <code>mime.types</code> file with one of these:</p>
<pre><code>TypesConfig /private/etc/apache2/mime.types
</code></pre>
<p>then said file should include this line:</p>
<pre><code>application/javascript js
</code></pre>
<p>Otherwise, you should see one of these somewhere:</p>
<pre><code>AddType application/javascript .js
</code></pre>
<p>At least, this is my first guess, if HTML and CSS files are being compressed and JavaScript files aren't.</p>
| 48,870
|
<p>I have a dataset that contains 2 datatables they link together using a DataRelation.</p>
<p>it it possible to select from those tables into into one result set? </p>
<p>thanks,
Ofer</p>
|
<p>Microsoft's suggestion is to create a helper class. See:</p>
<p><a href="http://support.microsoft.com/kb/326080/en-us" rel="nofollow noreferrer">http://support.microsoft.com/kb/326080/en-us</a></p>
<p>This is a general purpose tool that can be used no matter what the source.</p>
|
<p>You can create JOIN tables with the VS DataSet editor, whcih combine your results - you can then write Select queries against that and call them from within your app.</p>
<p>To do it, simply create a new TableAdapter, then add BOTH tables into the editor (use the visual one), and select the fields you want to use from both tables, then write the relevant select functions.</p>
| 33,333
|
<p>What is a good challenge to improve your skills in object oriented programming?</p>
<p>The idea behind this poll is to provide an idea of which exercises are useful for learning OOP.</p>
<p>The challenge should be as language agnostic as possible, requiring either little or no use of specific libraries, or only the most common of libraries. Try to include only one challenge per answer, so that a vote will correspond to the merits of that challenge alone. Would also be nice if a level of skill required was indicated, and also the rationale behind why it is a useful exercise.</p>
<p>Solutions to the challenges could then be posted as answers to a "How to..." question and linked to from here.</p>
<p>For example:</p>
<ul>
<li>Challenge - implement a last-in-first-out stack</li>
<li>Skill level - beginner</li>
<li>Rationale - gives experience of how to reference objects</li>
</ul>
|
<p><a href="https://www.itmaybeahack.com/homepage/books" rel="nofollow noreferrer">Building Skills in Object-Oriented Design</a> is a free book that might be of use.</p>
<p>The description is as follows:</p>
<p>"The intent of this book is to help the beginning designer by giving them a sequence of interesting and moderately complex exercises in OO design. This book can also help managers develop a level of comfort with the process of OO software development. The applications we will build are a step above trivial, and will require some careful thought and design. Further, because the applications are largely recreational in nature, they are interesting and engaging. This book allows the reader to explore the processes and artifacts of OO design before project deadlines make good design seem impossible."</p>
|
<p>A given task has very little to do with being "OOP", it's more in how you grade it.</p>
<p>I would look at the Refactoring book, chapter 3, and make sure none of the bad code smells exist in the solution. Or, more importantly, go over ones that do apply.</p>
<p>Most importantly, watch for the existence of setters and getters (indicating that you are operating on values from a class and not asking the class to operate on it's own values)--or using "extends" without applying the Liskov Substitution Principle, stuff like that.</p>
| 8,492
|
<p>My application runs under CF 2.0 locally and i would like to know how to connect and send something to print in the embedded printer of a http://www.milliontech.com/home/content/view/195/95/'>Bluebird BIP-1300 device.</p>
<p>Ideally i would like an example in C#.</p>
<p>Thank you in advance.</p>
|
<p>I'm not familiar with this particular device, but in general, printers in this class require you to send RAW data, as they don't have Windows drivers.</p>
<p><a href="http://support.microsoft.com/kb/322091" rel="nofollow noreferrer">This KB article</a> outlines how to send data to the device using C#: whether this is useful for you depends on whether the unmanaged APIs used are available in the environment your CF app runs on.</p>
<p>In case the APIs are supported, what you need next are the correct escape codes for the device in order to get the on-paper results you want. These are usually well-documented in the printer manual.</p>
<p>If the Spooler API is not available, or you run into other issues that make this approach more trouble than it's worth, the third-party <a href="http://www.fieldsoftware.com/PrinterCE_NetCF.htm" rel="nofollow noreferrer">PrinterCE.NetCF SDK</a> may also be worth looking into.</p>
|
<p>Use bbpdaapi.dll (search by google)
and in c#</p>
<pre><code>using Bluebird.BIP.Printer;
...
this.prn1 = new Bluebird.BIP.Printer.Printer();
if (!this.prn1.Open(0))
{
MessageBox.Show("Can not open Printer", "Printer problem");
}
this.prn1.PrintText("sdfgidfui", 0);
this.prn1.PrintBitmap(@"\My Documents\sample.bmp", 0);
if (this.prn1.WaitUntilPrintEnd() == 1)
{
MessageBox.Show("No paper in Printer", "Printer problem");
}
}
this.prn1.Close();
</code></pre>
<p>and etc..</p>
| 22,032
|
<p>I need to include a copyright statement at the top of every Python source file I produce:</p>
<pre><code># Copyright: © 2008 etc.
</code></pre>
<p>However, when I then run such a file I get this message:</p>
<p>SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <a href="http://www.python.org/peps/pep-0263.html" rel="noreferrer">http://www.python.org/peps/pep-0263.html</a> for details.</p>
<p>Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:</p>
<pre><code># -*- coding: iso-8859-1 -*-
</code></pre>
<p>to tell Python I'm using Latin encoding, or I can change the copyright statement to: </p>
<pre><code># Copyright: \xa9 2008 etc.
</code></pre>
<p>which just possibly doesn't have the same legal standing.</p>
<p>Is there a more elegant solution?</p>
|
<p>The copyright symbol in ASCII is spelled <code>(c)</code> or "<code>Copyright</code>".</p>
<p>See circular 61, <a href="http://www.copyright.gov/circs/circ61.pdf" rel="noreferrer">Copyright Registration for Computer Programs</a>. </p>
<p>While it's true that the legal formalism (see Circular 1, <a href="http://www.copyright.gov/circs/circ01.pdf" rel="noreferrer">Copyright Basics</a>) is </p>
<blockquote>
<p>The symbol © (the letter C in a
circle), or the word “Copyright,” or
the abbreviation “Copr.”; and...</p>
</blockquote>
<p>And it's also true that</p>
<blockquote>
<p>To guarantee protection for a
copyrighted work in all UCC member
countries, the notice must consist of
the symbol © (the word “Copyright” or
the abbreviation is not acceptable)</p>
</blockquote>
<p>You can dig through circular <a href="http://www.copyright.gov/circs/circ03.html" rel="noreferrer">3</a> and <a href="http://www.copyright.gov/circs/circ38a.html" rel="noreferrer">38a</a>.</p>
<p>This has, however, already been tested in court. It isn't an interesting issue. If you do a search for "(c) acceptable for c-in-a-circle", you'll find that lawyers all agree that (c) is an acceptable substitute. See Perle and Williams. See Scott on Information Technology Law.</p>
|
<p>You can always revert to good old (c)</p>
| 27,280
|
<p>Let's say:</p>
<pre><code><div>
pre text
<div class="remove-just-this">
<p>child foo</p>
<p>child bar</p>
nested text
</div>
post text
</div>
</code></pre>
<p>to this:</p>
<pre><code><div>
pre text
<p>child foo</p>
<p>child bar</p>
nested text
post text
</div>
</code></pre>
<p>I've been figuring out using Mootools, jQuery and even (raw) JavaScript, but couldn't get the idea how to do this.</p>
|
<p>Using <a href="http://jquery.com/" rel="noreferrer">jQuery</a> you can do this:</p>
<pre><code>var cnt = $(".remove-just-this").contents();
$(".remove-just-this").replaceWith(cnt);
</code></pre>
<p>Quick links to the documentation:</p>
<ul>
<li><a href="http://docs.jquery.com/Traversing/contents" rel="noreferrer">contents</a>( ) : <em>jQuery</em></li>
<li><a href="http://docs.jquery.com/Manipulation/replaceWith" rel="noreferrer">replaceWith</a>( <em>content</em> : [<em>String</em> | <em>Element</em> | <em>jQuery</em>] ) : <em>jQuery</em></li>
</ul>
|
<p>if you'd like to do this same thing in pyjamas, here's how it's done. it works great (thank you to eyelidness). i've been able to make a proper rich text editor which properly does styles without messing up, thanks to this.</p>
<pre><code>def remove_node(doc, element):
""" removes a specific node, adding its children in its place
"""
fragment = doc.createDocumentFragment()
while element.firstChild:
fragment.appendChild(element.firstChild)
parent = element.parentNode
parent.insertBefore(fragment, element)
parent.removeChild(element)
</code></pre>
| 20,518
|
<p>This is a follow-up question to <a href="https://stackoverflow.com/questions/369220/why-should-you-not-use-number-as-a-constructor">this one</a>.</p>
<p>Take a look at these two examples: </p>
<pre><code>var number1 = new Number(3.123);
number1 = number1.toFixed(2);
alert(number1);
var number2 = 3.123;
number2 = number2.toFixed(2);
alert(number2);
</code></pre>
<p>I realize they both end up with the same value, but is it correct thinking to refer to a method of a primitive value? (In other words, 3.123.method as opposed to object.method?)</p>
|
<p>Technically, no. You can treat it like it is a method of the primative value, because number2 is will be converted to a <code>Number</code> object, then <code>toFixed</code> is gets called on that object.</p>
<p>The same thing happens when you call methods on strings.</p>
<p>To illustrate what's happening, you can run this code:</p>
<pre><code>Object.prototype.type = function() { return typeof this; }
var string = "a string";
var number = 42;
alert(typeof string); // string
alert(string.type()); // object
alert(typeof number); // number
alert(number.type()); // object
</code></pre>
|
<p>Calling a method on a literal value or variable initialized with a primitive value has the same effect as first coercing the value to an Object of appropriate type and then calling the method on it. The following experiment is better than trying to explain this in words:</p>
<pre><code>Object.prototype.getPrototype = function() { return "Object"; };
Number.prototype.getPrototype = function() { return "Number"; };
function test(v) {
alert("proto: " + v.getPrototype()
+ ", type: " + typeof v
+ ", is a Number: " + (v instanceof Number)
+ ", is an Object: " + (v instanceof Object));
}
// proto: Number, type: number, is a Number: false, is an Object: false
test(42);
// proto: Number, type: number, is a Number: false, is an Object: false
test(Number(42));
// proto: Number, type: object, is a Number: true, is an Object: true
test(Object(42));
// proto: Number, type: object, is a Number: true, is an Object: true
test(new Number(42));
</code></pre>
| 48,249
|
<p>how can access the binary data file(.DAT). i am using geonames API. can anyone help me? </p>
|
<p>If you are referring to the binary flat file format used by MaxMinds GeoLocation database, they offer some handy utility classes in C# and Java to access it.</p>
<p><a href="http://www.maxmind.com/app/api" rel="nofollow noreferrer">http://www.maxmind.com/app/api</a></p>
|
<p>Assuming you are using C# (from the tag), you can use <a href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx" rel="nofollow noreferrer"><code>BinaryReader</code> class</a> to read binary data. See <a href="http://www.tanguay.info/web/codeExample.php?id=817" rel="nofollow noreferrer">How to read and write to a binary file</a>:</p>
<pre><code>FileStream fs = File.Open(Environment.CurrentDirectory + @"\settings.bin", FileMode.Open);
BinaryReader reader = new BinaryReader(fs);
long number = reader.ReadInt64();
byte[] bytes = reader.ReadBytes(3);
string s = reader.ReadString();
reader.Close();
fs.Close();
Console.WriteLine(number);
foreach (byte b in bytes)
{
Console.Write("[{0}]", b);
}
Console.WriteLine();
Console.WriteLine(s);
</code></pre>
| 42,188
|
<p>I've been trying to refactor a "bit" of code that I'd previously developed. Basically, the project was my response to not knowing how to use XSLT effectively, so I developed an XML transformation system in PHP. The program reads through the tags of an XML file and does something along these lines to convert it to HTML:</p>
<pre><code>private function getTemplate(...) {
switch ($nodeName) {
case "a" :
// code here to generate a link tag
break;
case "box" :
// code here to generate the divs and whatnot to create a box
break;
case "ref" :
// look up an external reference file and include a bibliography
break;
default :
// do the default thing
}
}
</code></pre>
<p>That was all working great, except that I ended up with 26 branches to my switch, and that once switch block was over 1000 lines of code. Needless to say, it made maintenance slightly more difficult.</p>
<p>What I've done now is to pull the code of each branch out into its own file (named "a.php", "box.php", "ref.php" ...) and <code>include</code> that file each time:</p>
<pre><code>if (file_exists("templates/$nodeName.php")) {
include "templates/$nodeName.php";
} else {
// do the default thing
}
</code></pre>
<p>Again, this works, but benchmarking it shows that it has slowed down processing times by 50%. I'm assuming that this is because there's now up to 4000 <code>include</code>s being done now.</p>
<p>What I was considering was to put the code for each template into a function, and if the function hasn't been declared then include the file, and then run the function - the only problem with that is that the existing code has been written in the scope of the original function, using <code>$this</code>, etc.</p>
<p>Given that this code is not run in real time (eg: it merely processes the XML into static HTML files which are stored - it's not done on the fly), do you have any advice for me here?</p>
|
<p>caveat: i don't know PHP, but I can <a href="http://us3.php.net/manual/en/functions.variable-functions.php" rel="nofollow noreferrer">google</a> and i like function pointers better than huge switch statements, so if you can't just use XSLT...</p>
<p>...one option would be to adopt a naming convention for your 'worker' functions that incorporated the html node's tag name, e.g. <tagname>_converter, include all the functions, and replace your switch statement with something like:</p>
<pre><code>private function getTemplate(...)
{
$func = $nodeName + "_converter";
if (function_exists($func)) //see if function is defined, somehow...
{
$func(); //call conversion function (pass whatever is needed)
}
}
</code></pre>
|
<p>Try something like this:</p>
<pre>
//utils.php
function handle_box($node)
{
//...
}
function handle_link($node)
{
//....
}
?\>
</pre>
<p>then:</p>
<pre>
require_once 'templates/utils.php';
function getTemplate()
{
switch($node)
{
case "a" :
handle_link($node,$otherParams);
break;
}
}
}
</pre>
<p>Basically this refactors all the functionality for each node into its own function. From here you can work on a more generalized solution. It is very similar to what you had original but the switch/case statements will be a lot more manageable without a ton of code inside of them. You can then look towards potentially implementing the <a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="nofollow noreferrer">Stratgy design pattern</a> if you feel it is necessary.</p>
| 44,575
|
<p>I really feel that I should learn <a href="http://en.wikipedia.org/wiki/Lisp_(programming_language)" rel="noreferrer">Lisp</a> and there are plenty of good resources out there to help me do it.</p>
<p>I'm not put off by the complicated syntax, but where in "traditional commercial programming" would I find places it would make sense to use it instead of a procedural language.</p>
<p>Is there a commercial killer-app out there that's been written in Lisp ?</p>
|
<p>One of the main uses for Lisp is in Artificial Intelligence. A friend of mine at college took a graduate AI course and for his main project he wrote a "<a href="http://en.wikipedia.org/wiki/Lights_Out_(video_game)" rel="noreferrer">Lights Out</a>" solver in Lisp. Multiple versions of his program utilized slightly different AI routines and testing on 40 or so computers yielded some pretty neat results (I wish it was online somewhere for me to link to, but I don't think it is).</p>
<p>Two semesters ago I used Scheme (a language based on Lisp) to write an interactive program that simulated Abbott and Costello's "Who's on First" routine. Input from the user was matched against some pretty complicated data structures (resembling maps in other languages, but much more flexible) to choose what an appropriate response would be. I also wrote a routine to solve a 3x3 <a href="http://en.wikipedia.org/wiki/Sliding_puzzle" rel="noreferrer">slide puzzle</a> (an algorithm which could easily be extended to larger slide puzzles).</p>
<p>In summary, learning Lisp (or Scheme) may not yield many practical applications beyond AI but it is an extremely valuable learning experience, as many others have stated. Programming in a functional language like Lisp will also help you think recursively (if you've had trouble with recursion in other languages, this could be a great help).</p>
|
<p>Syntax is irrelevant, readability is not!</p>
| 2,673
|
<p>How do I tell if my application (compiled in Visual Studio 2008 as <em>Any CPU</em>) is running as a 32-bit or 64-bit application?</p>
|
<pre><code>if (IntPtr.Size == 8)
{
// 64 bit machine
}
else if (IntPtr.Size == 4)
{
// 32 bit machine
}
</code></pre>
|
<p>In .Net Standard you can use <code>System.Runtime.InteropServices.RuntimeInformation.OSArchitecture</code></p>
| 33,363
|
<p>From the reading I've done I'm under the impression the DataContractSerializer handles versionong issues by, if members in the request are not there it will set the default value, and if addional members are in the request but not in the definition the serializer will simply ignores these fields and not process them.</p>
<p>Firstly, is this assumption correct?</p>
<p>Secondly, could you use this DataContractSerializer instead of the XMLSerializer so you can add this versioning ability to old asmx web services? Basically, if you add new members to your web service schema request you won't need to send to every client? When you receive the request from the client you can Deserialize using the DataContractSerializer into your object.</p>
<p>Hope this makes sense</p>
|
<p>I ended up solving this in a thoroughly Rails fashion -- patching :attribute_fu to meet my needs. Hopefully I'll be able to release my patches to the community fairly soon.</p>
|
<p>The behavior you describe above seems like it must be a bug in attribute_fu, since the local isn't getting properly passed along, which it definitely should. I'd be interested to know what you did to patch it.</p>
| 33,187
|
<p>I'm used to coding Java Swing UIs, and in those if you have some properties that change, and you want your UI to update, you would implement the observer/observable pattern. In Java you do this normally by having your class maintain a list of listeners that it notifies of different events.</p>
<p>I've played with Objective-C on the Mac, and that has KVC and binding which seems to work very nicely, and requires less code. The iPhone SDK doesn't seem to have this functionality though, so my question is:
If I have a class that holds data that changes, what's the best way for me to register a UI component with that class so that it can be notified of changes in the data that it needs to display?</p>
|
<p>There are two built-in ways of doing observation in Cocoa: Key-Value Observing and notifications. In neither system do you need to maintain or notify a collection of observers yourself; the framework will handle that for you.</p>
<p>Key-Value Observing (KVO) lets you observe a property of an object — including even a property that represents a collection — and be notified of changes to that property. You just need to send the object <code>-addObserver:forKeyPath:options:context:</code> passing the object you want to receive updates, the key path of the property (relative to the receiver) for which you want to receive updates, and the types of updates you want to receive. (There are similar methods you can use if you want to observe a property representing a collection.)</p>
<p>Notifications are older and heavier-weight. You register with an <code>NSNotificationCenter</code> — usually the default center — an object and selector pair to be passed a notification when an event occurs. The notification object itself can contain arbitrary data via its <code>userInfo</code> property, and you can choose to observe all notifications of a specific name rather than those that apply to a particular object.</p>
<p>Which should you use in any particular case? In general, if you care about changes to a specific property of a specific object, use Key-Value Observing. That's what it's designed for and it's intentionally lightweight. (Among other uses, it is the foundation on which Cocoa Bindings are built.) If you care about a change in state that isn't represented by a property, then notifications are more appropriate.</p>
<p>For example, to stay in sync when the user changes the name of a model object, I'd use KVO. To know when an entire object graph was saved, I'd use notifications.</p>
|
<p>That's not generally the way that it's done. Take a look at the discussion <a href="https://stackoverflow.com/questions/95567/is-there-any-benefit-to-using-cocoas-version-of-mvc-with-net">here</a>, in particular the link to the Apple documentation.</p>
<p>If you still want to do it the way you say you do, it's not particularly hard to implement something like bindings "by hand". You'd just create a "binding" object that knows how to subscribe to changes, and connects to a property of a view.</p>
<p>To actually answer how it's done - normally, you have a controller object that monitors the state of the model (acting something like an Observer), and updates the view object(s) as necessary.</p>
| 20,023
|
<p>I user sun jdk 1.5 ThreadPoolExecutor( 24, 24,60,TimeUnit.SECONDS, new LinkedBlockingQueue()). soemtime I use jdb tool to find the status of all threads in thread pool are " waiting in a monitor", the code is : </p>
<pre><code> String key = getKey(dt.getPrefix(), id);
synchronized (key.intern()) { ----->
</code></pre>
<p>Is there a problem in "synchronized (key.intern()) " ?</p>
<hr>
<p>I get following informatnio using jdb tool, the status of 24 threads is "waiting in a monitor", it means 24 threads are deadlock at "key.intern()".</p>
<p>(java.lang.Thread)0x28 pool-3-thread-2 waiting in a monitor</p>
<p>(java.lang.Thread)0x27 pool-3-thread-3 waiting in a monitor</p>
<p>(java.lang.Thread)0x1b pool-3-thread-4 waiting in a monitor</p>
<p>(java.lang.Thread)0x1a pool-3-thread-5 waiting in a monitor</p>
<p>(java.lang.Thread)0x19 pool-3-thread-6 waiting in a monitor</p>
<p>(java.lang.Thread)0x18 pool-3-thread-7 waiting in a monitor</p>
<p>(java.lang.Thread)0x17 pool-3-thread-8 waiting in a monitor
...</p>
<p>so the result is : in multi-threads environment, Sting intern() method may be deadlock, ok ?</p>
|
<p>I posted a related question to this once that you might want to take a look at: <a href="https://stackoverflow.com/questions/133988/problem-with-synchronizing-on-string-objects">Problem with synchronizing on String objects?</a></p>
<p>What I learned was: using intern'ed Strings for synchronization is a <strong>bad</strong> practice.</p>
|
<p>key.intern() guarantee uniqueness because key.intern() returns a string from String constants pool.</p>
<p><a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#intern()" rel="nofollow noreferrer">http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#intern()</a>
intern</p>
<p>public String intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.</p>
| 45,408
|
<p>It is slow to load anything other than a small project. It is slow to quit; it can sometimes take minutes. It can be slow to open new files. The record macro feature used to be useful. It is now so slow to start up it's almost always quicker to do it manually!</p>
<hr>
<blockquote>
<p>More info would be helpful. How big are your solutions? What platform are you on. What 3rd party plugins are you running? What else is running on your pc? </p>
</blockquote>
<p>3.2GHz P4 Hyperthreaded, 2GB RAM. Running Outlook, Perforce, IE7, directory browsers. Usually have 1-3 instances of VS running. It's much slower than VC6, say. It seems to take a long time to load projects and close down. I'm interested in if people know reasons why this happens, because of the way VS is written. Is it using .net internally and GC slows it down?</p>
|
<p>it might be that you have a plugin that is misbehaving. Try the <a href="http://msdn.microsoft.com/en-us/library/xee0c8y7(VS.80).aspx" rel="nofollow noreferrer">safemode</a> switch to see if this improves performance </p>
|
<p>here's ya problem:</p>
<blockquote>
<p>3.2GHz P4 Hyperthreaded, 2GB RAM</p>
</blockquote>
<p>Hypertheaded means "doesn't actually have two CPU's, but it fakes it". If you have a process with just one thread running, then you get bad performance. It was a good short-term measure, but compared to having two REAL CPU's, it's a slow hack.</p>
<p>2GB of RAM would be an issue too, based on what you said you run. If you have a basic 5400RPM disk, then it's going to make it all worse.</p>
<p>I'd recommend, based on what you posted:</p>
<ul>
<li>A good core2 machine, maybe a quad if you have the budget.</li>
<li>3GB of ram if you are running a 32bit OS, 4+GB if you are running x64. 4GB means you waste 1GB under 32bit.</li>
<li>Get 7200RPM disks, or better. If you can, RAID0 them (stripe) or RAID0+1 (stripe+mirror) if you can get 4 drives (stripe == split content over the two disks, so you can read from both at the same time. stripe+mirror == the safe version of striping, so your code is on TWO disks at all times) </li>
</ul>
<p>I have a 2.0ghz Core2 (so roughly 3-4x the performance of your P4, if you count 2 CPU's(cores) to be 2x) with 2GB, and the most I can run well is 2 instances of VS.NET 2008. This is normal - nothing wrong with VS.NET, it's just a huge app.</p>
<p>More RAM. More CPU. More Screen. More. More. More :)</p>
| 6,513
|
<p>Or more generally, how do I remove an item from a colon-separated list in a Bash environment variable?</p>
<p>I thought I had seen a simple way to do this years ago, using the more advanced forms of Bash variable expansion, but if so I've lost track of it. A quick search of Google turned up surprisingly few relevant results and none that I would call "simple" or "elegant". For example, two methods using sed and awk, respectively:</p>
<pre><code>PATH=$(echo $PATH | sed -e 's;:\?/home/user/bin;;' -e 's;/home/user/bin:\?;;')
PATH=!(awk -F: '{for(i=1;i<=NF;i++){if(!($i in a)){a[$i];printf s$i;s=":"}}}'<<<$PATH)
</code></pre>
<p>Does nothing straightforward exist? Is there anything analogous to a split() function in Bash?</p>
<p><strong>Update:</strong><br/>
It looks like I need to apologize for my intentionally-vague question; I was less interested in solving a specific use-case than in provoking good discussion. Fortunately, I got it!</p>
<p>There are some very clever techniques here. In the end, I've added the following three functions to my toolbox. The magic happens in path_remove, which is based largely on Martin York's clever use of <code>awk</code>'s RS variable.</p>
<pre><code>path_append () { path_remove $1; export PATH="$PATH:$1"; }
path_prepend () { path_remove $1; export PATH="$1:$PATH"; }
path_remove () { export PATH=`echo -n $PATH | awk -v RS=: -v ORS=: '$0 != "'$1'"' | sed 's/:$//'`; }
</code></pre>
<p>The only real cruft in there is the use of <code>sed</code> to remove the trailing colon. Considering how straightforward the rest of Martin's solution is, though, I'm quite willing to live with it!</p>
<hr>
<p>Related question: <A href="https://stackoverflow.com/questions/273909/how-do-i-manipulate-path-elements-in-shell-scripts"><a href="https://stackoverflow.com/questions/273909/how-do-i-manipulate-path-elements-in-shell-scripts">How do I manipulate $PATH elements in shell scripts?</a></A></p>
|
<p>A minute with awk:</p>
<pre><code># Strip all paths with SDE in them.
#
export PATH=`echo ${PATH} | awk -v RS=: -v ORS=: '/SDE/ {next} {print}'`
</code></pre>
<h3>Edit: It response to comments below:</h3>
<pre><code>$ export a="/a/b/c/d/e:/a/b/c/d/g/k/i:/a/b/c/d/f:/a/b/c/g:/a/b/c/d/g/i"
$ echo ${a}
/a/b/c/d/e:/a/b/c/d/f:/a/b/c/g:/a/b/c/d/g/i
## Remove multiple (any directory with a: all of them)
$ echo ${a} | awk -v RS=: -v ORS=: '/a/ {next} {print}'
## Works fine all removed
## Remove multiple including last two: (any directory with g)
$ echo ${a} | awk -v RS=: -v ORS=: '/g/ {next} {print}'
/a/b/c/d/e:/a/b/c/d/f:
## Works fine: Again!
</code></pre>
<h3>Edit in response to security problem: (that is not relevant to the question)</h3>
<pre><code>export PATH=$(echo ${PATH} | awk -v RS=: -v ORS=: '/SDE/ {next} {print}' | sed 's/:*$//')
</code></pre>
<p>This removes any trailing colons left by deleting the last entries, which would effectively add <code>.</code> to your path.</p>
|
<p>Let's "remove" references to /path/to/something from the PATH:</p>
<p>Bash:</p>
<pre><code>PATH=${PATH/something/nope/}
</code></pre>
<p>Bonus answer for Windows Batch:</p>
<pre><code>set PATH=%PATH:something=nope%
</code></pre>
<p>Anyone has a simpler solution? :)</p>
| 48,335
|
<p>I've got a siluation where i need to access a SOAP web service with WSE 2.0 security. I've got all the generated c# proxies (which are derived from Microsoft.Web.Services2.WebServicesClientProtocol), i'm applying the certificate but when i call a method i get an error:</p>
<pre><code>System.Net.WebException : The request failed with HTTP status 405: Method Not Allowed.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
</code></pre>
<p>I've done some googling and it appears that this is a server configuration issue.
However this web service is used many clients without any problem (the web service is provided by a Telecom New Zealand, so it's bound to be configured correctly. I believe it's written in Java)</p>
<p>Can anyone shed some light on this issue?</p>
|
<p>Ok, found what the problem was. I was trying to call a .wsdl url instead of .asmx url.
Doh!</p>
|
<p>hmm are those other clients also using C#/.NET?</p>
<p>Method not allowed --> could this be a REST service, instead of a SOAP web service?</p>
| 18,250
|
<p>We develop Java Web-aps (Websphere, DB2) which display graphical and databased information. We would also like to offer the same application offline (distribution via CD/DVD) with online data-update. We have tried a number of alternatives in the past, but nothing has been really stable. What are the new best practices to take a Web ap plus data (in a small database) offline?</p>
|
<p>I don't know how well it works with the CD/DVD distribution front, but the first thing that comes to mind is <a href="http://code.google.com/p/gears/" rel="nofollow noreferrer">Gears</a>. On the .NET side of the fence there's <a href="http://www.microsoft.com/silverlight/" rel="nofollow noreferrer">Silverlight 2</a>. Then there's the <a href="http://labs.mozilla.com/projects/prism/" rel="nofollow noreferrer">Mozilla Prism</a> project, although I don't know how far advanced that is.</p>
<p>These are all designed for not just offline access, but mixed offline/online, talking to a server when it's available and working locally when necessary.</p>
|
<p>You could create an image of your server as a VMware instance and distribute it with a copy of VMware player (licensing allowing of course). Personally I'd build it on top of a Linux distribution like CentOS5.</p>
| 42,901
|
<p>I've recently been exposed to the fluent interface in nUnit and I love it; however, I am using msTest. </p>
<p>Does anyone know if there is a fluent interface that is either testing framework agnostic or for msTest? </p>
|
<p>See <a href="http://www.fluentassertions.com/" rel="nofollow noreferrer">Fluent Assertions</a>. You can do stuff like</p>
<pre><code>"ABCDEFGHI".Should().StartWith("AB").And.EndWith("HI").And.Contain("EF").And.HaveLength(9);
new[] { 1, 2, 3 }.Should().HaveCount(4, "because we thought we put three items in the
collection"))
dtoCollection.Should().Contain(dto => dto.Id != null);
collection.Should().HaveCount(c => c >= 3);
dto.ShouldHave().AllPropertiesBut(d => d.Id).EqualTo(customer);
dt1.Should().BeWithin(TimeSpan.FromHours(50)).Before(dt2);
Action action = () => recipe.AddIngredient("Milk", 100, Unit.Spoon);
action
.ShouldThrow<RuleViolationException>()
.WithMessage("Cannot change the unit of an existing ingredient")
.And.Violations.Should().Contain(BusinessRule.CannotChangeIngredientQuanity
</code></pre>
|
<p>Based on my research there isn't one, but if your willing to sacrifice the better reportability as far as why an assert failed and willing to add a new dll you can reference nunit and use theirs....</p>
| 38,793
|
<p>I see many user interface control libraries for .NET, but where can I get similar stuff for win32 using simply C/C++?</p>
<p>Things like prettier buttons, dials, listviews, graphs, etc.</p>
<p>Seems every Win32 programmers' right of passage is to end up writing his own collection. :/</p>
<hr>
<p>No MFC controls please. I only do pure C/C++. And with that said, I also don't feel like adding a multi-megabyte framework to my application just so that I can have a prettier button.</p>
<hr>
<p>I apologize for leaving out one tiny detail, and that is that my development is for Windows Mobile.</p>
<p>So manifest files are out.</p>
<p>I just notice how many developer companies have gone crazy with making pretty looking .NET components and wondered where the equivalent C/C++ Win32 components have gone?</p>
<p>I read about how many people ended up writing their own gradient button class, etc. So you would think that there would be some commercial classes for this stuff. It's just weird.</p>
<p>I'll take a closer look at QT and investigate its GUI support for such things. This is the challenge when you're the one man in your own uISV. No other developers to help you "get things done".</p>
|
<p>I've used <a href="http://trolltech.com/products/qt/" rel="noreferrer">Trolltech's Qt framework</a> in the past and had great success with it:
In addition, it's also cross-platform, so in theory you can target Win, Mac, & Linux (provided you don't do anything platform-specific in the rest of your code, of course ;) )</p>
<p>Edit: I notice that you're targeting Windows Mobile; that definitely adds to Qt's strength, as its cross-platform support extends to <a href="http://trolltech.com/products/qt/features/platforms/index" rel="noreferrer">WinCE and Embedded Linux</a> as well.</p>
|
<p>The MFC feature pack is derived from <a href="http://www.bcgsoft.com/" rel="nofollow noreferrer">BCGSoft components</a>.</p>
| 8,871
|
<p>I need generate <a href="https://stackoverflow.com/questions/27921/what-is-the-best-way-to-create-a-thumbnail-using-aspnet">thumbnails</a> for a bunch of jpegs (200,000+) but I want to make sure all of my thumbs have a equal height and width. However, I don't want to change the proportions of the image so I need to add empty space to the shorter dimension to "square it up". The empty space's background color is variable. </p>
<p>Here's the code snippet I'm using to generate the thumbs. What's the best way to do the squaring?</p>
<pre><code> Dim imgDest As System.Drawing.Bitmap = New Bitmap(ScaleWidth, ScaleHeight)
imgDest.SetResolution(TARGET_RESOLUTION, TARGET_RESOLUTION)
Dim grDest As Graphics = Graphics.FromImage(imgDest)
grDest.DrawImage(SourceImage, 0, 0, imgDest.Width, imgDest.Height)
</code></pre>
|
<p>How about this. Maybe you should draw a black (or whichever color) rectangle on the Bitmap first.</p>
<p>And then when you are placing the resized image, just calculate the placement of the image based on whichever dimension is shorter, and then move that dimension by half the difference (and keep the other on 0).</p>
<p>Wouldn't that work?</p>
|
<p>Like <strong>Vaibhav</strong> said, first paint the entire thumbnail area with black. This will be simpler than first fitting the image into the thumbnail and then determining which rectangles to paint black to achieve <a href="http://en.wikipedia.org/wiki/Pillarbox" rel="nofollow noreferrer">pillarboxing</a> or <a href="http://en.wikipedia.org/wiki/Letterbox" rel="nofollow noreferrer">letterboxing</a>.</p>
<p>Pseudo-code for a general solution to fit an <code>imageWidth</code> x <code>imageHeight</code> image into a <code>thumbWidth</code> x <code>thumbHeight</code> (doesn't have to be a square) area:</p>
<pre><code>imageRatio = imageWidth / imageHeight;
thumbRatio = thumbWidth / thumbHeight;
zoomFactor = imageRatio >= thumbRatio
? thumbWidth / imageWidth
: thumbHeight / imageHeight;
destWidth = imageWidth * zoomFactor;
destHeight = imageHeight * zoomFactor;
drawImage(
(thumbWidth - destWidth) >> 1,
(thumbHeight - destHeight) >> 1,
destWidth,
destHeight);
</code></pre>
| 26,150
|
<p>I'm in the middle of building a D-Bot printer, and have run into a bit of an issue when it comes to the heat bed wires. The heated bed is an aluminum plate with a silicon heater attached to it, and the heater wires are not long enough to make it through the drag chain when the Z-axis is fully extended.</p>
<p>The silicon pad is 120 V AC / 750 W and will be turned on/off by a Fotek SSR. The heater wires are cloth-covered and are probably 22-24 AWG. (Gauge is not labelled)</p>
<p>I suspect I'll need to extend the wires by putting in some sort of coupler at the top of the drag chain, but I'm not certain if there are specific requirements for the wires for an AC powered heat bed. </p>
<p>To this end, I was wondering:</p>
<ul>
<li>Is there a specific wire gauge that I should use for the heater wires, and should it have a specific cladding?</li>
<li>What type of connector would be best for connecting the wires together securely in this case?</li>
</ul>
<p>Thanks in advance!</p>
|
<p>750 W at 120 V is 6.3 A. 22-24 AWG is on the thin side for this. I would recommend 18 AWG or thicker. You don't need a specific style of insulation for this (other than something that is rated for the voltage and temperature the wire will need to withstand, but most commonly found wire should be good).</p>
<p>A good way of connecting the wires would be to solder them. If you do not want to solder, there are many products on the market for connecting wires. A butt connector that you crimp could be a good option, or you could use a WAGO clamp. Whatever option you end up using, be sure to provide adequate strain relief as the connection point (be it soldered or with a connector) is more likely to fail from fatigue.</p>
|
<p>750 W at 120 V is around 6.3 A.</p>
<p>You can use a <a href="https://www.calculator.net/voltage-drop-calculator.html" rel="nofollow noreferrer">voltage drop calculator</a> to find out how much power is lost in the wires, and therefore their temperature increase.</p>
<p>I did it for you. With 10 feet (2x5 feet) 20AWG wire and 6 A current, 7 W are dissipated on the wires.</p>
<p>It's 0.7 W/foot which is ok for silicone wires, also because the bed doesn't operate at 100% except for the initial heating up (and then the heat goes to the air around, which is fine anyway).</p>
<p>If you use <a href="https://www.is-rayfast.com/news/wire-cable/temperature-rise-by-current/" rel="nofollow noreferrer">another website</a>, you can see that 20 AWG with 6 A current produces, in free air, around 10 degrees temperature increase. Silicone insulation will worsen that, but silicone holds well over 100 °C...</p>
<p>Use thicker wires if you can, or go on if you cannot.</p>
<p>The most important thing is to very effectively join the two, so that no extra resistance is introduced. I would place them next to each other and physically solder them. Then heat shrink tube around the joint.</p>
<p>See for info what not to use for the joining</p>
<p><div class="youtube-embed"><div>
<iframe width="640px" height="395px" src="https://www.youtube.com/embed/unxEdyW8RP8?start=0"></iframe>
</div></div></p>
| 1,685
|
<p>Hey right now I'm using jQuery and I have some global variables to hold a bit of preloaded ajax stuff (preloaded to make pages come up nice and fast):</p>
<pre><code>
$.get("content.py?pageName=viewer", function(data)
{viewer = data;});
$.get("content.py?pageName=artists", function(data)
{artists = data;});
$.get("content.py?pageName=instores", function(data)
{instores = data;});
$.get("content.py?pageName=specs", function(data)
{specs = data;});
$.get("content.py?pageName=about", function(data)
{about = data;});
</code></pre>
<p>As you can see, we have a huge violation of the DRY principle, but... I don't really see a way to fix it... any ideas?</p>
<p>maybe an array?</p>
|
<p>You don't need <code>eval()</code> or <code>Function()</code> for this. An array, as you suspected, will do the job nicely:</p>
<pre><code>(function() // keep outer scope clean
{
// pages to load. Each name is used both for the request and the name
// of the property to store the result in (so keep them valid identifiers
// unless you want to use window['my funky page'] to retrieve them)
var pages = ['viewer', 'artists', 'instores', 'specs', 'about'];
for (var i=0; i<pages.length; ++i)
{
// "this" refers to the outer scope; likely the window object.
// And will result in page contents being stored in global variables
// with the same names as the pages being loaded. We use the with({})
// construct to create a local scope for each callback with the
// appropriate context and page name.
with ({context: this, pageName: pages[i]})
$.get("content.py?pageName=" + pageName, function(data)
{context[pageName] = data;});
}
})(); // close scope, execute anonymous function
// at this point, viewer, artists, etc. are populated with page contents
// (assuming all requests completed successfully)
</code></pre>
|
<p>You can call only one time that page, and returning a json object instead of text</p>
<pre><code>{
viewer:'me',
artists:'you',
instores:'instores',
specs:'specs',
about:'about'
}
</code></pre>
<p>and eval that
Since now you're calling N times your server, this slow down all, you should reconsider your logic!</p>
<p>PS. as I write i saw the RoBorg answer, you see, when using new Function you are using eval under the hood, so if you want to use it go for it (in some browser is faster too)</p>
| 24,657
|
<p>I'm trying to make an XML questions editor in flash.
Basically I load in the XML into a Tree component - XML like so:</p>
<pre><code><questions>
<question id="1" type="radio" text="This is question 1" isBranch="true">
<option id="1.1" correct="false" text="This is option 1" />
<option id="1.2" correct="false" text="This is option 2" />
<option id="1.1" correct="false" text="This is option 1" />
<option id="1.2" correct="false" text="This is option 2" />
<option id="1.3" correct="true" text="This is option 3" />
<option id="1.4" correct="false" text="This is option 4" />
</question>
<question id="2" type="check" text="This is question 2" isBranch="true">
<option id="2.1" correct="true" text="This is option 1" />
<option id="2.2" correct="false" text="This is option 2" />
<option id="2.3" correct="true" text="This is option 3" />
</question>
</questions>
</code></pre>
<p>So that goes into the tree. On change I get a list of the options for the selected question (item..option) - and that XMLList is passed into a (custom) component.
That component (not sure if this is the best way to go about it but still...) - has a couple of Repeater controls - one which is bound to the XMLList for a radio question, the other bound to the XMLList of a cheque box question.
Each repeater loops the number of options, placing a TextInput in (to edit the option text) and either a radio or cheque box (depending on the question type)</p>
<p>So - what I am after is when the text is edited for an option, the XML in that TextInput is bound to the XML which is the dataProvider for the tree. So for example if "This is option 1" is changed to "This is option Foo" - the Tree updates with that.</p>
<p>So far my repeater (eg. for the radios) is like this</p>
<pre><code><mx:Repeater id="repeaterRadio" dataProvider="{optionsListRadio}">
<mx:TextInput width="359" id="radioText"
editable="true" enabled="true" text="{repeaterRadio.currentItem.@text}"/>
<mx:RadioButton id="radioArray"
data="{repeaterRadio.currentItem.@id}"
selected="{repeaterRadio.currentItem.@correct=='true'}"/>
</mx:Repeater>
</code></pre>
<p>No binding works - all I get here is warnings like:</p>
<pre><code>warning: unable to bind to property 'text' on class 'XML' (class is not an IEventDispatcher)
</code></pre>
<p>I sort of get why this is the case, but am at a loss how to go about binding the data the user can edit back to the source xml. I know I can make the tree itself editable but that's not really an option here.</p>
<p>So any pointers or ideas would be very appreciated!</p>
|
<p>Take a look at ksh93, it supports associative arrays and is a much more complete/correct implementation of ksh.</p>
<p>See: <a href="http://kornshell.com/" rel="nofollow noreferrer">kornshell.com</a></p>
|
<p>Why not just use bash? It might not have explicit associative arrays, but you can <a href="http://linuxshellaccount.blogspot.com/2008/05/how-to-fake-associative-arrays-in-bash.html" rel="nofollow noreferrer">fake them</a>.</p>
<p>Alternatively, zsh has <a href="http://zsh.dotsrc.org/Doc/Release/zsh_14.html#SEC72" rel="nofollow noreferrer">excellent associative array support</a>.</p>
| 44,477
|
<p>A customer sometimes sends POST requests with <code>Content-Length: 0</code> when submitting a form (10 to over 40 fields).</p>
<p>We tested it with different browsers and from different locations but couldn't reproduce the error. The customer is using Internet Explorer 7 and a proxy.</p>
<p>We asked them to let their system administrator see into the problem from their side. Running some tests without the proxy, etc..</p>
<p>In the meantime (half a year later and still no answer) I'm curious if somebody else knows of similar problems with a <code>Content-Length: 0</code> request. Maybe from inside some Windows network with a special proxy for big companies.</p>
<p>Is there a known problem with Internet Explorer 7? With a proxy system? The Windows network itself?</p>
<p>Google only showed something in the context of NTLM (and such) authentication, but we aren't using this in the web application. Maybe it's in the way the proxy operates in the customer's network with Windows logins? (I'm no Windows expert. Just guessing.)</p>
<p>I have no further information about the infrastructure.</p>
<p><strong>UPDATE:</strong> In December 2010 it was possible to inform one administrator about this, incl. links from the answers here. Contact was because of another problem which was caused by the proxy, too. No feedback since then. And the error messages are still there. I'm laughing to prevent me from crying.</p>
<p><strong>UPDATE 2:</strong> This problem exists since mid 2008. Every few months the customer is annoyed and wants it to be fixed ASAP. We send them all the old e-mails again and ask them to contact their administrators to either fix it or run some further tests. In December 2010 we were able to send some information to 1 administrator. No feedback. Problem isn't fixed and we don't know if they even tried. And in May 2011 the customer writes again and wants this to be fixed. The same person who has all the information since 2008.</p>
<p>Thanks for all the answers. You helped a lot of people, as I can see from some comments here. Too bad the real world is this grotesque for me.</p>
<p><strong>UPDATE 3:</strong> May 2012 and I was wondering why we hadn't received another demand to fix this (see UPDATE 2). Looked into the error protocol, which only reports this single error every time it happened (about 15 a day). It stopped end of January 2012. Nobody said anything. They must have done something with their network. Everything is OK now. From summer 2008 to January 2012. Too bad I can't tell you what they have done.</p>
<p><strong>UPDATE 4:</strong> September 2015. The website had to collect some data and deliver it to the main website of the customer. There was an API with an account. Whenever there was a problem they contacted us, even if the problem was clearly on the other side. For a few weeks now we can't send them the data. The account isn't available anymore. They had a relaunch and I can't find the pages anymore that used the data of our site. The bug report isn't answered and nobody complaint. I guess they just ended this project.</p>
<p><strong>UPDATE 5:</strong> March 2017. The API stopped working in the summer of 2015. The customer seems to continue paying for the site and is still accessing it in February 2017. I'm guessing they use it as an archive. They don't create or update any data anymore so this bug probably won't reemerge after the mysterious fix of January 2012. But this would be someone else's problem. I'm leaving.</p>
|
<p>Internet Explorer does not send form fields if they are posted from an authenticated site (NTLM) to a non-authenticated site (anonymous).</p>
<p>This is feature for challange-response situations (NTLM- or Kerberos- secured web sites) where IE can expect that the first POST request immediately leads to an <em>HTTP 401 Authentication Required</em> response (which includes a challenge), and only the second POST request (which includes the response to the challange) will actually be accepted. In these situations IE does not upload the possibly large request body with the first request for performance reasons. Thanks to <a href="https://stackoverflow.com/questions/328281/why-content-length-0-in-post-requests/630059?noredirect=1#comment24906051_630059">EricLaw</a> for posting that bit of information in the comments.</p>
<p>This behavior occurs every time an HTTP POST is made from a NTLM authenticated (i.e. Intranet) page to a non-authenticated (i.e. Internet) page, or if the non-authenticated page is part of a frameset, where the frameset page is authenticated.</p>
<p>The work-around is either to use a GET request as the form method, or to make sure the non-authenticated page is opened in a fresh tab/window (favorite/link target) without a partly authenticated frameset. As soon as the authentication model for the whole window is consistent, IE will start to send form contents again.</p>
<hr />
<ul>
<li>Definitely related: <a href="http://www.websina.com/bugzero/kb/browser-ie.html" rel="nofollow noreferrer">http://www.websina.com/bugzero/kb/browser-ie.html</a></li>
<li>Possibly related: <a href="https://web.archive.org/web/20130925033628/http://support.microsoft.com:80/kb/923155" rel="nofollow noreferrer">KB923155</a></li>
<li><strong>Full Explanation</strong>: <a href="https://web.archive.org/web/20151109032611/http://blogs.msdn.com:80/b/ieinternals/archive/2010/11/22/internet-explorer-post-bodies-are-zero-bytes-in-length-when-authentication-challenges-are-expected.aspx" rel="nofollow noreferrer">IEInternals Blog – Challenge-Response Authentication and Zero-Length Posts</a></li>
</ul>
|
<p>Google also shows this as an IE (some versions, anyway) bug after an https connection hits the keepalive timeout and reconnects to the server. The solution seems to be configuring the server to not use keepalive for IE under https.</p>
| 42,541
|
<p>I am using the WMD markdown editor in a project for a large number of fields that correspond to a large number of properties in a large number of Entity classes. Some classes may have multiple properties that require the markdown.</p>
<p>I am storing the markdown itself since this makes it easier to edit the fields later. However, I need to convert the properties to HTML for display later on. The question is: is there some pattern that I can use to avoid writing markdown conversion code in all my entity classes?</p>
<p>I created a utility class with a method that accepts a markdown string and returns the HTML. I am using markdownj and this works fine.</p>
<p>The problem is for each property of each class that stores markdown I may need another method that converts to HTML:</p>
<pre><code>public class Course{
private String description;
.
.
.
public String getDescription(){
return description;
}
public String getDescriptionAsHTML(){
return MarkdownUtil.convert(getDescription());
}
.
.
.
}
</code></pre>
<p>The problem there is that if the Course class has 2 more properties Tuition and Prerequisites say, that both need converters then I will have to write getTuitionAsHTML() and getPrerequisiteAsHTML().</p>
<p>I find that a bit ugly and would like a cleaner solution. The classes that require this are not part of a single inheritance hierarchy. </p>
<p>The other option I am considering is doing this in the controller rather than the model. What are your thoughts on this? </p>
<p>Thanks.</p>
<p>[EDIT]: New thoughts (Thanks Jasper). Since the project uses struts2 (I did not say this before) I could create a view component say that will convert the markdown for me. Then I use that wherever I need to display the value as HTML.</p>
|
<blockquote>
<p>The classes that require this are not part of a single inheritance hierarchy.</p>
</blockquote>
<p>They should at least implement a common interface, otherwise coming up with a clean generic solution is going to be cumbersome.</p>
<blockquote>
<p>The other option I am considering is doing this in the controller rather than the model. What are your thoughts on this?</p>
</blockquote>
<p>This clearly is a responsibility of the View. The #1 MVC rule is that the Model doesn't care about its representation, the markdown in this case.</p>
<p>However, I feel that there is to little detail about your current architecture to give a meaningful answer to your question.</p>
|
<p>You do have one option for doing this if you can't use inheritance or an interface. I know, I know refactor but this is reality and *hit happens.</p>
<p>You can use reflection to iterate over your properties and apply the formatting to them. You could either tag them with an attribute or you could adopt a naming scheme (brittle, but still an option).</p>
| 31,677
|
<p>I recently upgraded to Delphi 2009 and was disappointed to find out that I couldn't easily replace one VCL component with another. The best answer back was that <a href="http://www.gexperts.org" rel="nofollow noreferrer">GExperts</a> could be used to do this. </p>
<p>Is it worthwhile to petition Embarcadero to incorporate some or all of the capabilities of GExperts right into Delphi? Which of their "Experts" do you use most and would like to see in Delphi?</p>
<p>Or is GExperts best left as a community Open Source addon?</p>
|
<p>What features in GExperts would you most like to be included in Delphi itself? I would suggest that you come up with prioritized list of your, say, top 10 features. Then pop on over to Quality Central (<a href="http://qc.codegear.com" rel="nofollow noreferrer">http://qc.codegear.com</a>) and see if they've already been added as suggestions and if so, vote for them. If not feel free to go ahead and add them. This information is regularly mined and queried not only for product defects, but also as a way for us to hear from our customers about product enhancements. The voting system helps us prioritize the planning of our work and product cycles.</p>
|
<p>Most used features for me are: Grep Search and Replace Components.</p>
<p>But, i think it's not a good idea to include gExperts functionality in IDE at all. Because:</p>
<ol>
<li>gExperts are independent product
which can be easily installed in
less then minute</li>
<li>There are too much unfixed bugs in
QC, to spend Codegear's team time
for reinventing bicycles.</li>
<li>And main thing is <a href="http://www.gexperts.org/license.html" rel="nofollow noreferrer">GExperts
license</a>, which has the following
line:</li>
</ol>
<blockquote>
<p>You may not use the GExperts source
code to develop proprietary or
commercial products including plugins
or libraries for those products. You
may use the GExperts source code in an
Open Source project, under the terms
listed below.</p>
</blockquote>
<p>This means, that CodeGear should write this functionality from scratch.</p>
| 38,997
|
<p>As I learn more about Computer Science, AI, and Neural Networks, I am continually amazed by the cool things a computer can do and learn. I've been fascinated by projects new and old, and I'm curios of the interesting projects/applications other SO users have run into.</p>
|
<p><a href="http://www.numenta.com/" rel="noreferrer">The Numenta Platform for Intelligent Computing</a>. They are implementing the type of neuron described in "On Intelligence" by Jeff Hawkins. For an idea of the significance, they are working on software neurons that can visually recognize objects in about 200 steps instead of the thousands and thousands necessary now.</p>
<p>Edit: Apparently version 1.6.1 of the SDK is available now. Exciting times for learning software!!</p>
|
<p><a href="http://alice.pandorabots.com/" rel="nofollow noreferrer">http://alice.pandorabots.com/</a>
- This bot is able to have pretty intelligent conversation with us.</p>
| 40,851
|
<p>I'm working on a project where we're doing a lot of remote object transfer between a Java service and clients written in other various languages. Given our current constraints I've decided to see what it would take to generate code based on an existing Java class. Basically I need to take a <code>.class</code> file (or a collection of them) parse the bytecode to determine all of the data members and perhaps getters/setters and then write something that can output code in a different language to create a class with the same structure.</p>
<p>I'm not looking for standard decompilers such as JAD. I need to be able to take a <code>.class</code> file and create an object model of its data members and methods. Is this possible at all?</p>
|
<p>I've used BCEL and find it really quite awkward. <a href="http://asm.objectweb.org/" rel="noreferrer">ASM</a> is much better. It very extensively uses visitors (which can be a little confusing) and does not create an object model. Not creating an object model turns out to be a bonus, as any model you do want to create is unlikely to look like a literal interpretation of all the data.</p>
|
<p>I think javassist might help you too. </p>
<p><a href="http://www.jboss.org/javassist/" rel="nofollow noreferrer">http://www.jboss.org/javassist/</a></p>
<p>I have never had the need of using it, but if you give it a try, would you let us know your comments about it?</p>
<p>Although I think it is more for bytecode manipulation than .class inspection.</p>
| 19,873
|
<p>Tomcat fails to start even if i remove all my applications from the WEBAPPS directory leaving everything just like after the OS installation.</p>
<p>The log (catalina.out) says:</p>
<pre><code>Using CATALINA_BASE: /usr/share/tomcat5
Using CATALINA_HOME: /usr/share/tomcat5
Using CATALINA_TMPDIR: /usr/share/tomcat5/temp
Using JRE_HOME:
Created MBeanServer with ID: -dpv07y:fl4s82vl.0:hydrogenium.timberlinecolorado.com:1
java.lang.NoClassDefFoundError: org.apache.catalina.core.StandardService
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.newInstance(libgcj.so.7rh)
at org.apache.catalina.startup.Bootstrap.init(bootstrap.jar.so)
at org.apache.catalina.startup.Bootstrap.main(bootstrap.jar.so)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.modeler.Registry not found in org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/server/classes/,file:/usr/share/java/tomcat5/catalina-cluster-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-storeconfig-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-optional-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-coyote-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-jkstatus-ant-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-ajp-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-default-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-invoker-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-ant-jmx-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-http-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-util-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-apr-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/servlets-webdav-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-5.5.23.jar], parent=org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/common/classes/,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-ja.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-fr.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-en.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-es.jar,file:/usr/share/java/tomcat5/naming-resources-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/naming-factory-5.5.23.jar], parent=gnu.gcj.runtime.SystemClassLoader{urls=[file:/usr/lib/jvm/java/lib/tools.jar,file:/usr/share/tomcat5/bin/bootstrap.jar,file:/usr/share/tomcat5/bin/commons-logging-api.jar,file:/usr/share/java/mx4j/mx4j-impl.jar,file:/usr/share/java/mx4j/mx4j-jmx.jar], parent=gnu.gcj.runtime.ExtensionClassLoader{urls=[], parent=null}}}}
at java.net.URLClassLoader.findClass(libgcj.so.7rh)
at java.lang.ClassLoader.loadClass(libgcj.so.7rh)
at java.lang.ClassLoader.loadClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
...5 more
</code></pre>
|
<p>Seems like you've implemented a JMX service and tried to install it on your server.xml file but forgot to add the apache commons modeler jar to the server/lib directory (therefore the <code>ClassNotFoundException</code> for <code>org.apache.commons.modeler.Registry</code>). Check your server.xml file for anything you might have added, and try to add the proper jar file to your server classpath.</p>
|
<p>This screams class path issue, to me. Where exactly is your tomcat installed? (Give us command line printouts of where the home directory is.) Also, how are you starting it?</p>
| 8,788
|
<p>Considering there are so many draconian firewalls in the world, is there any reason I shouldn't run server software on port 80 to guarantee greatest possible accessibility? It seems that the most common firewall exception is to allow outbound connections on port 80. I understand that any sort of packet inspection would still block my non-HTTP traffic but if that is the case I'm sure the firewall wouldn't have any other open outgoing ports anyway.</p>
<p>If the server already has a webserver on port 80 is it possible to use some sort of virtual host listening on port 80 (i.e. myDomain.com:80 <em>and</em> myApp.myDomain.com:80 on the same machine)?</p>
|
<p>If you need to do this, why not just wrap your network comms code with a SOAP interface or an HTTPHandler?</p>
<p>Then your packets will conform to HTTP, you'll get through firewalls and everyone's happy?</p>
<p>It will be much easier than resolving all the installation and operations issues you'll get from multi-purposing port 80.</p>
|
<p>I will confess to having worked around a Draconian firewall by having an ssh server listen on port 80 back home and using <strong>ssh tunnelling to provide access to other servers and services</strong>. I hasten to add that I did this with the blessing of the people administering the firewall---we all agreed that it was the best solution to the problems at hand.</p>
<p>I hasten to add that this tactic <strong>renders port 80 useless for its intended purpose</strong>, which was fine with me since it was my personal workstation anyway. If you have only one machine in your domain it would be a problem. But having a machine I could dedicate to serve ssh from port 80 created <strong>no installation or operations issues</strong>. I just ran <code>/etc/init.d/apache stop</code> and then ran an <code>sshd</code> to listen to port 80. Then I was good to go for the few months I needed to do this.</p>
<p>Automated scanners who come knocking on port 80 of my personal workstation can go hang :-)</p>
| 49,316
|
<p>I'm using the following query, but I currently have to enter a value in every parameter for the query to work. Is there a way of making the parameters optional, so that 1 or more values will return a result?</p>
<pre><code>SELECT * FROM film
WHERE day LIKE '%day%'
AND month LIKE '%month%'
AND year LIKE '%year%'
</code></pre>
<hr>
<p>something like</p>
<pre><code> function queryData(year,month,day)
declare Y
if year == nothing
Y = '%'
else
Y = '%' + year + '%'
declare M
if month == nothing
M = '%'
else
M = '%' + month + '%'
declare D
if day == nothing
D = '%'
else
D = '%' + day + '%'
return result of :
SELECT * FROM film
WHERE day LIKE D
OR month LIKE M
OR year LIKE Y
</code></pre>
|
<p>Why don't you create your query dynamically?
Depending on the parameters you have, append the filters dynamically. </p>
<p>e.g.:</p>
<pre><code>string query = "SELECT * FROM film";
string paramenters = string.empty;
if(day!= string.empty)
parameters = " Where day LIKE '%day%'";
if(month != string.empty)
{
if(parameters != string.empty)
parameters += "AND month LIKE '%month%'";
else
parameters = "WHERE month LIKE '%month%'";
}
</code></pre>
<p>and so on....</p>
<p>In this case you won't get extra results that you will get with <code>OR</code>.</p>
|
<pre><code>SELECT * FROM film
WHERE day LIKE '%day%'
OR month LIKE '%month%'
OR year LIKE '%year%'
</code></pre>
<p>You will still be providing all three parameters, but it won't matter if they are blank or NULL, matches will still return from the ones that aren't blank.</p>
| 42,840
|
<p>I'm a huge fan of bzr and I'm glad they're working on tortoise for it, but currently it's WAY too slow to be useful. The icons are almost always incorrect and when I load a directory in explorer with a lot of branches it locks up my entire system for anywhere from 10 seconds to 2 minutes. I look forward to trying it again in the future, but for now I'd like to disable it.</p>
<p>Unfortunately I don't see it in add/remove programs and I can't find a way to disable it in the bazaar config directory. When I right click the icon in the task panel (by the clock) and choose "Exit Program" it just restarts moments later. I don't see it in the Services panel either. Is there any way to disable it?</p>
<p>I'm running Windows XP on the system in question.</p>
|
<p>I think you can do:</p>
<pre><code>regsvr32 /u tbzrshellext_x86.dll
</code></pre>
<p>I also killed tbzrcachew.exe in memory, but since, like enobrev, I couldn't find it with AutoRuns, I will suppose it is the shell extension that runs this cache.</p>
<p>Will know for sure when I will reboot my computer...</p>
<p>I agree that currently these icons are slow, doesn't update in real time, and options in context menu are often limited. I hope all these points will improve in the future.</p>
<p>[EDIT] It works! No need to kill the cache too.</p>
|
<p><a href="https://stackoverflow.com/questions/151587/how-do-i-disable-tortoise-bzr#151911">Jason's answer</a> seemed valid, so I spent some time looking for the py file. It's nowhere to be found. It seems when installing bzr via the setup it also installs tbzr binaries. I've looked through as many panels as I can find. Process Explorer (sysinternals), AutoRuns (sysinternals), Some Shell Extension browser, etc. I couldn't find a formal entry anywhere.</p>
<p>I found the registry entries, but I've no idea where they came from or how to "formally" get rid of them. I'm not in the mood to just start killing off registry entries as I actually have to get work done this week.</p>
<p>I'm just going to run the uninstall and then install the latest version (with TBZR unchecked). As far as I can tell that's the only way to resolve this.</p>
| 18,266
|
<p>I know MSDE is no longer supported on Vista, is this also the case for Windows Server 2008?</p>
|
<p>The status is the same for Vista and all OS after Vista, which includes both Windows 2008 and Windows 7.</p>
<p>I do not know if you can somehow "make it work", but you will not get any Support from Microsoft.</p>
<p>Edit: Source is <a href="http://blogs.msdn.com/sqlexpress/archive/2006/08/09/693650.aspx" rel="nofollow noreferrer">here</a>, the two important bits:</p>
<blockquote>
<p>MSDE 2000 will exit mainstream support on 4/8/2008 and no new deployment agreements will be allowed after June 30, 2007.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>Yes, MSDE will be supported through the end of it's life cycle on the operating systems it is currently designed to run on.</p>
</blockquote>
<p>(That was up to Windows XP and 2003 Server)</p>
|
<p>The status is the same for Vista and all OS after Vista, which includes both Windows 2008 and Windows 7.</p>
<p>I do not know if you can somehow "make it work", but you will not get any Support from Microsoft.</p>
<p>Edit: Source is <a href="http://blogs.msdn.com/sqlexpress/archive/2006/08/09/693650.aspx" rel="nofollow noreferrer">here</a>, the two important bits:</p>
<blockquote>
<p>MSDE 2000 will exit mainstream support on 4/8/2008 and no new deployment agreements will be allowed after June 30, 2007.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>Yes, MSDE will be supported through the end of it's life cycle on the operating systems it is currently designed to run on.</p>
</blockquote>
<p>(That was up to Windows XP and 2003 Server)</p>
| 35,255
|
<p>I think there must be something subtle going on here that I don't know about. Consider the following:</p>
<pre><code>public class Foo<T> {
private T[] a = (T[]) new Object[5];
public Foo() {
// Add some elements to a
}
public T[] getA() {
return a;
}
}
</code></pre>
<p>Suppose that your main method contains the following:</p>
<pre><code>Foo<Double> f = new Foo<Double>();
Double[] d = f.getA();
</code></pre>
<p>You will get a <code>CastClassException</code> with the message <code>java.lang.Object</code> cannot be cast to <code>java.lang.Double</code>.</p>
<p>Can anyone tell me why? My understanding of <code>ClassCastException</code> is that it is thrown when you try to cast an object to a type that cannot be casted. That is, to a subclass of which it is not an instance (to quote the documentation). e.g.:</p>
<pre><code>Object o = new Double(3.);
Double d = (Double) o; // Working cast
String s = (String) o; // ClassCastException
</code></pre>
<p>And it seems I can do this. If <code>a</code> was just a <code>T</code> instead of an array <code>T[]</code>, we can get <code>a</code> and cast it without a problem. Why do arrays break this?</p>
<p>Thanks.</p>
|
<pre><code>Foo<Double> f = new Foo<Double>();
</code></pre>
<p>When you use this version of the generic class Foo, then for the member variable <code>a</code>, the compiler is essentially taking this line:</p>
<pre><code>private T[] a = (T[]) new Object[5];
</code></pre>
<p>and replacing <code>T</code> with <code>Double</code> to get this:</p>
<pre><code>private Double[] a = (Double[]) new Object[5];
</code></pre>
<p>You cannot cast from Object to Double, hence the ClassCastException.</p>
<p><strong>Update and Clarification:</strong> Actually, after running some test code, the ClassCastException is more subtle than this. For example, this main method will work fine without any exception:</p>
<pre><code>public static void main(String[] args) {
Foo<Double> f = new Foo<Double>();
System.out.println(f.getA());
}
</code></pre>
<p>The problem occurs when you attempt to assign <code>f.getA()</code> to a reference of type <code>Double[]</code>:</p>
<pre><code>public static void main(String[] args) {
Foo<Double> f = new Foo<Double>();
Double[] a2 = f.getA(); // throws ClassCastException
System.out.println(a2);
}
</code></pre>
<p>This is because the type-information about the member variable <code>a</code> is erased at runtime. Generics only provide type-safety at <em>compile-time</em> (I was somehow ignoring this in my initial post). So the problem is not </p>
<pre><code>private T[] a = (T[]) new Object[5];
</code></pre>
<p>because at run-time this code is really</p>
<pre><code>private Object[] a = new Object[5];
</code></pre>
<p>The problem occurs when the result of method <code>getA()</code>, which at runtime actually returns an <code>Object[]</code>, is assigned to a reference of type <code>Double[]</code> - this statement throws the ClassCastException because Object cannot be cast to Double.</p>
<p><strong>Update 2</strong>: to answer your final question "why do arrays break this?" The answer is because the language specification does not support generic array creation. <a href="http://forums.sun.com/thread.jspa?threadID=530823" rel="noreferrer">See this forum post for more</a> - in order to be backwards compatible, nothing is known about the type of T at runtime.</p>
|
<p>@matt b: Thanks for the answer! Very helpful.</p>
<p>I have found a workaround for those interested: give the getA method an initialized array to populate. That way the type info is available.</p>
<pre><code>public class Foo<T> {
private T[] a = (T[]) new Object[5];
public Foo() {
// Add some elements to a
}
public T[] getA(T[] holdA) {
// Check whether holdA is null and handle it...then:
holdA = (T[]) Array.newInstance(holdA.getClass().getComponentType(), a.length);
System.arraycopy(a, 0, holdA, 0, a.length);
return holdA;
}
}
</code></pre>
<p>Then for your main method:</p>
<pre><code>public static void main(String[] args) {
Foo<Double> f = new Foo<Double>();
Double[] a2 = new Double[1];
a2 = f.getA(a2);
}
</code></pre>
| 48,659
|
<p>I have a custom control that implements IPostBackEventHandler. Some client-side events invoke __doPostBack(controlID, eventArgs).</p>
<p>The control is implemented in two different user controls. In one control, RaisePostBackEvent is fired on the server-side when <code>__doPostBack</code> is invoked. In the other control, RaisePostBackEvent is never invoked. I checked the <code>__EVENTTARGET</code> parameter and it does match the ClientID of the control... where else might I look to troubleshoot this?</p>
|
<p>There's a lot of ways this can fall apart. Are you adding the control to the page dynamically in code behind? If so alot of times your UniqueID can be off - even though the client id's are equal. Do you have a code sample that might demonstrate what you're doing?</p>
|
<p>Double check that it is indeed a derivation of the UserControl class, not the WebControl one.<br>
This one has had me by surprise many times. If you need to use WebControl for the styling, you need to let your control implement INamingContainer. (Don't worry, its a marker interface)</p>
<p>So..</p>
<pre><code>public class MyControl : UserControl {}
</code></pre>
<p>Or</p>
<pre><code>public class MyControl : WebControl, INamingContainer {}
</code></pre>
| 3,089
|
<pre><code>$("#dvMyDIV").bind("resize", function(){
alert("Resized");
});
</code></pre>
<p>or</p>
<pre><code>$("#dvMyDIV").resize(function(){
alert("Resized");
});
</code></pre>
<p>The questions</p>
<ol>
<li>Why is this not working at FireFox, Chrome and Safari?</li>
<li>Can this be considered a jQuery bug since the resize is not handled for other browsers?</li>
<li>Could the only workaround be calling a SetTimeout function checking the clientHeight and clientWidth?</li>
<li>Any workarounds using jQuery?</li>
</ol>
|
<p>I believe the JavaScript resize event only applies to frames or windows, not to DIVs.</p>
<p>e.g. see <a href="http://devguru.com/technologies/javascript/10929.asp" rel="noreferrer">this page</a>:</p>
<blockquote>
<p>The onResize even handler is use to execute specified code whenever a user or script resizes a window or frame. This allows you to query the size and position of window elements, dynamically reset SRC properties etc. </p>
</blockquote>
<p>So if you want to detect when the window is resized, in jQuery you should probably use <code>$(window).resize(function() { });</code></p>
<p><b>Edit:</b> if you want to watch the size of a DIV, it depends on what your intention is. If you're resizing with JavaScript then you could implement a method to perform the resize and have that handle calling any other resize code.</p>
<p>Otherwise, if you're just watching for the DIV to resize when someone resizes the window, wouldn't it just work to attach the resize listener to the window and then check if the DIV had been resized (i.e. store the old values of width / height and check them on resize)?</p>
<p>Finally, you could consider using <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/watch" rel="noreferrer">watch</a> on the width / height properties, although I don't know whether this is fully browser-compatible (think this might be Mozilla-only). I did find <a href="http://www.west-wind.com/Weblog/posts/453942.aspx" rel="noreferrer">this jQuery plugin</a> which looks like it might do the same thing though (with some slight modification).</p>
|
<p>Why do you expect #dvMyDIV to be resized? Is maybe resizing of that element a result of something else, maybe the window being resized? If so, try</p>
<pre><code>$(window).resize(function(){alert("Resized");});
</code></pre>
| 28,345
|
<p>(If anything here needs clarification/ more detail please let me know.)</p>
<p>I have an application (C#, 2.* framework) that interfaces with a third-party webservice using SOAP. I used thinktecture's WSCF add-in against a supplied WSDL to create the client-side implementation. For reasons beyond my control the SOAP message exchange uses WSE2.0 for security (the thinctecture implementation had to be modified to include the WSE2.0 reference). In addition to the 'normal' data package I attach a stored X509 cert and a binary security token from a previous call to a different web service. We are using SSL encryption of some sort - I don't know the details. </p>
<p>All the necessary serialization/deserialization is contained in the web service client - meaning when control is returned to me after calling the client the entire XML string contained in the SOAP response is not available to me - just the deserialized components. Don't get me wrong - I think that's good because it means I don't have to do it myself.</p>
<p>However, in order for me to have something worth storing/archiving I am having to re-serialize the data at the root element. This seems like a waste of resources since my result was in the SOAP response. </p>
<p><strong>Now for my question:
How can I get access to a 'clear' version of the SOAP response so that I don't have to re-serialize everything for storage/archiving?</strong></p>
<p>Edit- My application is a 'formless' windows app running as a network service - triggered by a WebsphereMQ client trigger monitor. I don't <em>think</em> ASP.NET solutions will apply.</p>
<p>Edit - Since the consensus so far is that it doesn't matter whether my app is ASP.NET or not then I will give CodeMelt's (and by extension Chris's) solution a shot.</p>
|
<p>You can utilize SoapExtension from existing WSE2.0 framework to intercept the responses from the server.</p>
<pre><code>public class MyClientSOAPExtension : SoapExtension
{
Stream oldStream;
Stream newStream;
// Save the Stream representing the SOAP request or SOAP response into
// a local memory buffer.
public override Stream ChainStream( Stream stream )
{
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
public override void ProcessMessage(SoapMessage message)
{
switch (message.Stage)
{
case SoapMessageStage.BeforeDeserialize:
// before the XML deserialized into object.
break;
case SoapMessageStage.AfterDeserialize:
break;
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
break;
default:
throw new Exception("Invalid stage...");
}
}
}
</code></pre>
<p>At stage of SoapMessageStage.BeforeDeserialize,
You can read the expected data you want from oldstream (e.g. use XmlReader).
Then store the expected data somewhere for yourself to use and also you need
forward the old stream data to the newstream for web service later stage to use the data, e.g. deserialize XML into objects.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension(VS.85).aspx" rel="noreferrer">The sample of logging all the traffic for the web service from MSDN</a></p>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension(VS.85).aspx" rel="nofollow noreferrer">MSDN Library</a> includes example code for obtaining the XML of both the request and the response that you can use to archive it. Obviously you'll have to make some changes since the example stores data in a text file, but it isn't too complicated.</p>
| 31,975
|
<p>Which language for quick GUI app + sqlite database CRUD (2-4 tables). Java, Python? (Please no jokes like VBasic), some reference, source code to look on?</p>
<p>added:</p>
<p>First idea:
1 database SQLite (Win) + client GUI app (Win)
clients table + orders table + others
import, export database
add, del, edit, etc. entries</p>
<p>Second idea:
1 hosted database (PostgreSQL ,MySQL) + web app client
clients table + orders table + others
import, export database
add, del, edit, etc. entries</p>
<p>Thinking about Django, RoR or local Java(Netbeans), Python(wxPython+ORM).</p>
<p>???</p>
|
<p>Ruby on Rails will do simple CRUD operations <strong>very</strong> easily - although doing more than that can be a little more complex (would require some reading about RoR's way of doing things). The latest version of Rails automatically uses sqlite databases, and in fact the whole database, and CRUD GUI code can be created with one command (<code>scaffold</code>).</p>
<p>If this is to be deployed then that can be a bit more difficult (although I hear that Capistrano is good) - but for local or intranet use then that's what I'd do.</p>
|
<p>C# and WPF, it;s preatty easy and good to know (I've been playing with it for 1 week and fully wrote a twitter client in a few hours.</p>
<p>now Cocoa, and the interface Builder, that is a cool approach even for a simple app.</p>
| 31,184
|
<p>Python has several ways to parse XML...</p>
<p>I understand the very basics of parsing with <strong>SAX</strong>. It functions as a stream parser, with an event-driven API.</p>
<p>I understand the <strong>DOM</strong> parser also. It reads the XML into memory and converts it to objects that can be accessed with Python.</p>
<p>Generally speaking, it was easy to choose between the two depending on what you needed to do, memory constraints, performance, etc.</p>
<p>(Hopefully I'm correct so far.)</p>
<p>Since Python 2.5, we also have <strong>ElementTree</strong>. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?</p>
|
<p>ElementTree is much easier to use, because it represents an XML tree (basically) as a structure of lists, and attributes are represented as dictionaries.</p>
<p>ElementTree needs much less memory for XML trees than DOM (and thus is faster), and the parsing overhead via <code>iterparse</code> is comparable to SAX. Additionally, <code>iterparse</code> returns partial structures, and you can keep memory usage constant during parsing by discarding the structures as soon as you process them.</p>
<p>ElementTree, as in Python 2.5, has only a small feature set compared to full-blown XML libraries, but it's enough for many applications. If you need a validating parser or complete XPath support, lxml is the way to go. For a long time, it used to be quite unstable, but I haven't had any problems with it since 2.1.</p>
<p>ElementTree deviates from DOM, where nodes have access to their parent and siblings. Handling actual documents rather than data stores is also a bit cumbersome, because text nodes aren't treated as actual nodes. In the XML snippet</p>
<pre><code><a>This is <b>a</b> test</a>
</code></pre>
<p>The string <code>test</code> will be the so-called <code>tail</code> of element <code>b</code>.</p>
<p>In general, I recommend ElementTree as the default for all XML processing with Python, and DOM or SAX as the solutions for specific problems.</p>
|
<p>ElementTree's parse() is like DOM, whereas iterparse() is like SAX. In my opinion, ElementTree is better than DOM and SAX in that it provides API easier to work with.</p>
| 23,442
|
<p>I have a workstation with Windows 2008 x64, MS Access 2007 and Oracle 11g x64
I use Access to connect to Oracle via ODBC.
I am the administrator (in the administrator group) on the workstation. I run Access as administrator but when I want to make an ODBC call to Oracle it does not work.</p>
<p>How do I do it:
I start MS Access and creates a direct query. In the properties dialog I go to add new and the Select datasource dialog appears. I then use machine datasource and click New, System datasource - but the driver for Oracle is not there.</p>
<p>Regards Robert :-) </p>
|
<p>Solved! Create a Virtual PC (Hyper-V) and install the 32 bit version of OS and client - it works!</p>
|
<p>If you want to use the Oracle supplied ODBC driver, you need to install the oracle client. The default client install does not include the driver, so you either need to add it when you do the install or re-run the universal installer to add it later.</p>
| 25,617
|
<p>I have a program that I need to run under *nix and windows. because the program takes file paths from files the issue is what to do about the <code>\</code> vs <code>/</code> issue. </p>
<p>My current thought is to put in a regex that converts the wrong one to the right one depending on what system I'm on. This will have the effect of letting either type work on either system. Aside from the fact that <a href="http://fishbowl.pastiche.org/2003/08/18/beware_regular_expressions/" rel="nofollow noreferrer">now I have two problems</a>, does anyone see any other problems?</p>
<p>(Other better solutions are more than welcome)</p>
<p>Edit: the primary issue is getting windows paths to work on unix rather than the other way around.</p>
|
<p>The / is fully supported in win32 too.</p>
<p>Also see this <a href="https://stackoverflow.com/questions/122455/handling-file-paths-cross-platform">related question</a></p>
|
<p>Create a parser for your input to create a tree structure of nodes representing directories. Then you can 'save' by walking the tree and writing whatever delimiters you want or optionally doing different things, like checking if the directory exists or writing meta files. This is actually something that I am just now thinking would be useful for my own application :-)</p>
| 35,325
|
<p>If our organisation were to switch from a central-server VCS like subversion to a distributed VCS like git, how do I make sure that all my code is safe from hardware failure?</p>
<p>With a central-server VCS I just need to backup the repository every day. If we were using a DVCS then there'd be loads of code branches on all the developer machines, and if that hardware were to fail (or a dev were to lose his laptop or have it stolen) then we wouldn't have any backups.</p>
<p>Note that I don't consider it a good option to "make the developers push branches to a server" -- that's <a href="http://www.mattblodgett.com/2008/02/matt-blodgett-first-law-of-software.html" rel="nofollow noreferrer">tedious</a> and the developers will end up not doing it.</p>
<p>Is there a common way around this problem?</p>
<p><strong>Some clarification:</strong></p>
<p>With a natively-central-server VCS then <em>everything</em> has to be on the central server except the developer's most recent changes. So, for example, if a developer decides to branch to do a bugfix, that branch is on the central server and available for backup immediately.</p>
<p>If we're using a DVCS then the developer can do a local branch (and in fact many local branches). None of those branches are on the central server and available for backup until the developer thinks, "oh yeah, I should push that to the central server".</p>
<p>So the difference I'm seeing (correct me if I'm wrong!): Half-implemented features and bugfixes will probably not available for backup on the central server if we're using a DVCS, but are with a normal VCS. How do I keep that code safe?</p>
|
<p>I think that you will find that in practice developers will prefer to use a central repository than pushing and pulling between each other's local repositories. Once you've cloned a central repository, while working on any tracking branches, fetching and pushing are trivial commands. Adding half a dozen remotes to all your colleagues' local repositories is a pain and these repositories may not always be accessible (switched off, on a laptop taken home, etc.).</p>
<p>At some point, if you are all working on the same project, all the work needs to be integrated. This means that you need an integration branch where all the changes come together. This naturally needs to be somewhere accessible by all the developers, it doesn't belong, for example, on the lead developer's laptop.</p>
<p>Once you've set up a central repository you can use a cvs/svn style workflow to check in and update. cvs update becomes git fetch and rebase if you have local changes or just git pull if you don't. cvs commit becomes git commit and git push.</p>
<p>With this setup you are in a similar position with your fully centralized VCS system. Once developers submit their changes (git push), which they need to do to be visible to the rest of the team, they are on the central server and will be backed up.</p>
<p>What takes discipline in both cases is preventing developers keeping long running changes out of the central repository. Most of us have probably worked in a situation where one developer is working on feature 'x' which needs a fundamental change in some core code. The change will cause everyone else to need to completely rebuild but the feature isn't ready for the main stream yet so he just keeps it checked out until a suitable point in time.</p>
<p>The situation is very similar in both situations although there are some practical differences. Using git, because you get to perform local commits and can manage local history, the need to push to the central repository may not be felt as much by the individual developer as with something like cvs.</p>
<p>On the other hand, the use of local commits can be used as an advantage. Pushing all local commits to a safe place on the central repository should not be very difficult. Local branches can be stored in a developer specific tag namespace.</p>
<p>For example, for Joe Bloggs, An alias could be made in his local repository to perform something like the following in response to (e.g.) <code>git mybackup</code>.</p>
<pre><code>git push origin +refs/heads/*:refs/jbloggs/*
</code></pre>
<p>This is a single command that can be used at any point (such as the end of the day) to make sure that all his local changes are safely backed up.</p>
<p>This helps with all sorts of disasters. Joe's machine blows up and he can use another machine and fetch is saved commits and carry on from where he left off. Joe's ill? Fred can fetch Joe's branches to grab that 'must have' fix that he made yesterday but didn't have a chance to test against master.</p>
<p>To go back to the original question. Does there need to be a difference between dVCS and centralized VCS? You say that half-implemented features and bugfixes will not end up on the central repository in the dVCS case but I would contend that there need be no difference.</p>
<p>I have seen many cases where a half-implemented feature stays on one developers working box when using centralized VCS. It either takes a policy that allows half written features to be checked in to the main stream or a decision has to be made to create a central branch.</p>
<p>In the dVCS the same thing can happen, but the same decision should be made. If there is important but incomplete work, it needs to be saved centrally. The advantage of git is that creating this central branch is almost trivial.</p>
|
<p>You could have developer home directories mount remote devices over the local network. Then you only have to worry about making the network storage safe. Or maybe you could use something like <a href="http://www.getdropbox.com/" rel="nofollow noreferrer">DropBox</a> to copy your local repo elsewhere seamlessly.</p>
| 13,553
|
<p>I just installed an application on a win2003 server and I'm getting this error:</p>
<pre><code>Line 149: <roleManager>
Line 150: <providers>
Line 151: <add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
Line 152: <add name="AspNetWindowsTokenRoleProvider" applicationName="/" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
Line 153: </providers>
Source File: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Config\machine.config Line: 151
</code></pre>
<p>I'm using a RoleProvider and it's properly configured in web.config (it works on other servers) as follows:</p>
<pre><code><membership defaultProvider="AdminMembershipProvider">
<providers>
<clear/>
<add name="AdminMembershipProvider" connectionStringName="SiteSqlServer" type="MyApp.Providers.AdminMembershipProvider" applicationName="MyApp" writeExceptionsToEventLog="false" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" PasswordFormat="Clear" MinRequiredNonAlphanumericCharacters="1" MinRequiredPasswordLength="8" MaxInvalidPasswordAttempts="5" PasswordAttemptWindow="10">
</add>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="AdminRoleProvider" cacheRolesInCookie="true">
<providers>
<add name="AdminRoleProvider" type="MyApp.Providers.AdminRoleProvider" writeExceptionsToEventLog="true"/>
</providers>
</roleManager>
</code></pre>
<p>Any hint on why it's looking for configuration on machine.config instead of web.config? How can I debug this?</p>
<p>Thank you.</p>
|
<p>A dynamic language rules for this. Why? The mappings are easy to code and change. You don't have to recompile and rebuild.</p>
<p>Indeed, with a little cleverness, you can have your "XML XPATH to a Tag -> DB table-field" mappings as disjoint blocks of Python code that your main application imports.</p>
<p>The block of Python code <strong>is</strong> your configuration file. It's not an <code>.ini</code> file or a <code>.properties</code> file that describes a configuration. It <strong>is</strong> the configuration.</p>
<p>We use Python, xml.etree and the SQLAlchemy (to separate the SQL out of your programs) for this because we're up and running with very little effort and a great deal of flexibility.</p>
<hr>
<p><strong>source.py</strong></p>
<pre><code>"""A particular XML parser. Formats change, so sometimes this changes, too."""
import xml.etree.ElementTree as xml
class SSXML_Source( object ):
ns0= "urn:schemas-microsoft-com:office:spreadsheet"
ns1= "urn:schemas-microsoft-com:office:excel"
def __init__( self, aFileName, *sheets ):
"""Initialize a XML source.
XXX - Create better sheet filtering here, in the constructor.
@param aFileName: the file name.
"""
super( SSXML_Source, self ).__init__( aFileName )
self.log= logging.getLogger( "source.PCIX_XLS" )
self.dom= etree.parse( aFileName ).getroot()
def sheets( self ):
for wb in self.dom.getiterator("{%s}Workbook" % ( self.ns0, ) ):
for ws in wb.getiterator( "{%s}Worksheet" % ( self.ns0, ) ):
yield ws
def rows( self ):
for s in self.sheets():
print s.attrib["{%s}Name" % ( self.ns0, ) ]
for t in s.getiterator( "{%s}Table" % ( self.ns0, ) ):
for r in t.getiterator( "{%s}Row" % ( self.ns0, ) ):
# The XML may not be really useful.
# In some cases, you may have to convert to something useful
yield r
</code></pre>
<p><strong>model.py</strong></p>
<pre><code>"""This is your target object.
It's part of the problem domain; it rarely changes.
"""
class MyTargetObject( object ):
def __init__( self ):
self.someAttr= ""
self.anotherAttr= ""
self.this= 0
self.that= 3.14159
def aMethod( self ):
"""etc."""
pass
</code></pre>
<p><strong>builder_today.py</strong> One of many mapping configurations</p>
<pre><code>"""One of many builders. This changes all the time to fit
specific needs and situations. The goal is to keep this
short and to-the-point so that it has the mapping and nothing
but the mapping.
"""
import model
class MyTargetBuilder( object ):
def makeFromXML( self, element ):
result= model.MyTargetObject()
result.someAttr= element.findtext( "Some" )
result.anotherAttr= element.findtext( "Another" )
result.this= int( element.findtext( "This" ) )
result.that= float( element.findtext( "that" ) )
return result
</code></pre>
<p><strong>loader.py</strong></p>
<pre><code>"""An application that maps from XML to the domain object
using a configurable "builder".
"""
import model
import source
import builder_1
import builder_2
import builder_today
# Configure this: pick a builder is appropriate for the data:
b= builder_today.MyTargetBuilder()
s= source.SSXML_Source( sys.argv[1] )
for r in s.rows():
data= b.makeFromXML( r )
# ... persist data with a DB save or file write
</code></pre>
<hr>
<p>To make changes, you can correct a builder or create a new builder. You adjust the loader source to identify which builder will be used. You can, without too much trouble, make the selection of builder a command-line parameter. Dynamic imports in dynamic languages seem like overkill to me, but they are handy.</p>
|
<p>If you are well versed in Java, you can try out <a href="https://vtd-xml.sourceforge.io/" rel="nofollow noreferrer">VTD</a> XML Parser for parsing large volumes of XML data.</p>
| 38,685
|
<p>Are DES Encryption called "One Way Encryption" or "two way Encryption" ?
Are there a PHP class or method to decrypt the DES Encryption ?</p>
|
<p>The php <a href="http://us2.php.net/crypt" rel="nofollow noreferrer">crypt</a> function is a one-way hashing function, if you want to be able to decrypt, take a look at the <a href="http://us2.php.net/manual/en/book.mcrypt.php" rel="nofollow noreferrer">mcrypt</a> extension which supports <a href="http://us2.php.net/manual/en/mcrypt.ciphers.php" rel="nofollow noreferrer">a range of algorithms</a></p>
|
<p>I am not familiar with the "one way encryption" or "two way encryption" terms. There is a term "one time password" (totally irrelevant for DES), and there are "symmetric" and "assymetric" encryption algorithms, meaning whether the same key is used for encryption and decryption (symmetric) or a set of two different keys is used one for encryption and another for decryption (assymetric). DES is a symmetric algorithm. As for PHP, crypt() since to be doing the job:</p>
<p><a href="http://us2.php.net/crypt" rel="nofollow noreferrer">http://us2.php.net/crypt</a></p>
| 32,066
|
<p>I have a JavaScript resource that has the possibility of being edited at any time. Once it is edited I would want it to be propagated to the user's browser relatively quickly (like maybe 15 minutes or so), however, the frequency of this resource being editing is few and far between (maybe 2 a month).</p>
<p>I'd rather the resource to be cached in the browser, since it will be retrieved frequently, but I'd also like the cache to get reset on the browser at a semi-regular interval.</p>
<p>I know I can pass a no-cache header when I request for the resource, but I was wondering when the cache would automatically reset itself on the browser if I did not pass no-cache.</p>
<p>I imagine this would be independent for each browser, but I'm not sure.</p>
<p>I tried to Google this, but most of the hits I found were about clearing the browser's cache... which isn't what I'm looking for.</p>
|
<p>You may pass a version string as a get parameter to the URL of your script tag. The parameter won't be evaluated by the static JavaScript file but force the browser to get the new version. </p>
<p>If you do not want to assign the version string every time you edited the source you may compute it based on the file system time stamp or your subversion commit number:</p>
<pre><code><script src="/script.js?time_stamp=1224147832156" type="text/javascript"></script>
<script src="/script.js?svn_version=678" type="text/javascript"></script>
</code></pre>
<p> </p>
|
<p>Put a version on your javascript code like this that is updated when you make a change</p>
<pre><code><script src="/code.js?ver=123" type="text/javascript"></script>
</code></pre>
<p>They will then always get new version.</p>
| 25,336
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.