instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>We built a grant application system for a client. They've now asked for some simple workflow functionality (two approvals needed before the application is submitted). </p> <p>I've given some thought to the database design that I'd use to encode the workflow requirements in a way that would offer maximum flexibility and reusability, and I'd be interested to know if there are any existing design patterns or best practices out there for this type of system. Any suggestions?</p> <p><strong>Note:</strong> This is a custom ASP.NET application, and we'll definitely be rolling our own workflow solution. I'm not interested in buying into a component, or much less moving this whole thing to a platform like SharePoint. </p>
<p>To not look at the <a href="http://msdn.microsoft.com/en-us/netframework/aa663328.aspx" rel="nofollow noreferrer">Windows Workflow Foundation</a> would be foolish. It was made for exactly what you require.</p> <p>Here's an <a href="http://www.devx.com/dotnet/Article/29992" rel="nofollow noreferrer">ASP.NET specific link</a>.</p>
<p>one solution that has worked well in the past is to create approval groups with members, approval codes as a simple lookup table, and soft-code the approval state-machine so that each step results from the assigning of an approval code to an item by a group member. This allows the group membership to change and the approval paths to change without having to re-code anything. You could also add code triggers and endpoints (via reflection, e.g. assembly name + class name + method name) to perform side-effect and commit/notification actions at each step</p>
28,508
<p>I have a function that is declared and defined in a header file. This is a problem all by itself. When that function is not inlined, every translation unit that uses that header gets a copy of the function, and when they are linked together there are duplicated. I "fixed" that by making the function inline, but I'm afraid that this is a fragile solution because as far as I know, the compiler doesn't guarantee inlining, even when you specify the "inline" keyword. If this is not true, please correct me.</p> <p>Anyways, the real question is, what happens to static variables inside this function? How many copies do I end up with?</p>
<p>I guess you're missing something, here.</p> <h2>static function?</h2> <p>Declaring a function static will make it "hidden" in its compilation unit.</p> <blockquote> <p>A name having namespace scope (3.3.6) has internal linkage if it is the name of</p> <p>— a variable, function or function template that is explicitly declared static;</p> <p>3.5/3 - C++14 (n3797)</p> <p>When a name has internal linkage , the entity it denotes can be referred to by names from other scopes in the same translation unit.</p> <p>3.5/2 - C++14 (n3797)</p> </blockquote> <p>If you declare this static function in a header, then all the compilation units including this header will have their own copy of the function.</p> <p>The thing is, if there are static variables inside that function, each compilation unit including this header will also have their own, personal version.</p> <h2>inline function?</h2> <p>Declaring it inline makes it a candidate for inlining (it does not mean a lot nowadays in C++, as the compiler will inline or not, sometimes ignoring the fact the keyword inline is present or absent):</p> <blockquote> <p>A function declaration (8.3.5, 9.3, 11.3) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.</p> <p>7.1.2/2 - C++14 (n3797)</p> </blockquote> <p>In a header, its has an interesting side effect: The inlined function can be defined multiple times in the same module, and the linker will simply join "them" into one (if they were not inlined for compiler's reason).</p> <p>For static variables declared inside, the standard specifically says there one, and only one of them:</p> <blockquote> <p>A static local variable in an extern inline function always refers to the same object.</p> <p>7.1.2/4 - C++98/C++14 (n3797)</p> </blockquote> <p>(functions are by default extern, so, unless you specifically mark your function as static, this applies to that function)</p> <p>This has the advantage of "static" (i.e. it can be defined in a header) without its flaws (it exists at most once if it is not inlined)</p> <h2>static local variable?</h2> <p>Static local variables have no linkage (they can't be referred to by name outside their scope), but has static storage duration (i.e. it is global, but its construction and destruction obey to specific rules).</p> <h2>static + inline?</h2> <p>Mixing inline and static will then have the consequences you described (even if the function is inlined, the static variable inside won't be, and you'll end with as much static variables as you have compilation units including the definition of your static functions).</p> <h2>Answer to author's additional question</h2> <blockquote> <p>Since I wrote the question I tried it out with Visual Studio 2008. I tried to turn on all the options that make VS act in compliance with standards, but it's possible that I missed some. These are the results:</p> <p>When the function is merely "inline", there is only one copy of the static variable.</p> <p>When the function is "static inline", there are as many copies as there are translation units.</p> <p>The real question is now whether things are supposed to be this way, or if this is an idiosyncrasy of the Microsoft C++ compiler.</p> </blockquote> <p>So I suppose you have something like that:</p> <pre><code>void doSomething() { static int value ; } </code></pre> <p>You must realise that the static variable inside the function, simply put, a global variable hidden to all but the function's scope, meaning that only the function it is declared inside can reach it.</p> <p>Inlining the function won't change anything:</p> <pre><code>inline void doSomething() { static int value ; } </code></pre> <p>There will be only one hidden global variable. The fact the compiler will try to inline the code won't change the fact there is only one global hidden variable.</p> <p>Now, if your function is declared static:</p> <pre><code>static void doSomething() { static int value ; } </code></pre> <p>Then it is "private" for each compilation unit, meaning that every CPP file including the header where the static function is declared will have its own private copy of the function, including its own private copy of global hidden variable, thus as much variables as there are compilation units including the header.</p> <p>Adding "inline" to a "static" function with a "static" variable inside:</p> <pre><code>inline static void doSomething() { static int value ; } </code></pre> <p>has the same result than not adding this "inline" keyword, as far as the static variable inside is concerned.</p> <p><b>So the behaviour of VC++ is correct, and you are mistaking the real meaning of "inline" and "static".</b></p>
<p>I believe you will end up with one per translation unit. You've effectively got many versions of that function (and its declared static variable), one for every translation unit that includes the header.</p>
22,456
<p>we have several <em>"production environments"</em> (three servers each, with the same version of our system. Each one has a SQL Server Database as production database). </p> <p>In one of this environment the <em>tempdb</em> transaction log starts to grow fast and infinitely, we can´t find why. Same version of SO, SQL Server, application. No changes in the environment.</p> <p>Someone know how to figure what´s happening ou how to fix this?</p>
<p>You might be in Full recovery model mode - if you are doing regular backups you can change this to simple and it will reduce the size of the log after the backup.</p> <p>Here is <a href="http://support.microsoft.com/kb/873235" rel="nofollow noreferrer">some more info</a>.</p>
<p>Your best bet is to fire up SQL Server Profiler and see what's going on. Look for high values in the "Writes" column or Spool operators, these are both likely to cause high temp usage.</p> <p>If it is only the transaction log growing then try this, open transactions prevent the log from being shrunk down as it goes. This should be run in tempdb:</p> <pre><code>DBCC OPENTRAN </code></pre>
11,398
<p>I can split editor panes horizontally or vertically, but it does not seem possible to view code in two separate physical windows. I am aware that Idea can open multiple <strong>projects</strong> in separate windows, but I'd like to be able to do this for two files in a <strong>single</strong> project. </p> <p>One answer suggested unpinning the tab, but I haven't been able to make that work (I'm on Mac OSX if that matters.)</p> <p>This seems like a basic feature in today's world of multi-headed workstations. Before moving to an IDE I used to do this regularly with good old Emacs. Is there some trick I am not aware of to make this happen?</p>
<p>Unfortunately there is no way (as of IDEA 8.0.1) to do what you're asking for. As you pointed out, you can split the editor pane but there is always exactly one editor per IDEA project.</p> <p>UPDATE: As of IDEA 10 (currently the latest is 10.5), the answer is yes, you can :-)</p>
<p>Yes- with <a href="http://www.jetbrains.com/idea/training/demos/detachable_tabs/index.html" rel="nofollow noreferrer">IDEA X</a>, it is finally possible to open multiple editor windows. </p>
49,043
<p>I wrote a small web app using ruby on rails, its main purpose is to upload, store, and display results from xml(files can be up to several MB) files. After running for about 2 months I noticed that the mongrel process was using about 4GB of memory. I did some research on debugging ruby memory leaks and could not find much. So I have two questions.</p> <ul> <li>Are there any good tools that can be used to find memory leaks in Ruby/rails?</li> <li>What type of coding patterns cause memory leaks in ruby?</li> </ul>
<p>Some tips to find memory leaks in Rails:</p> <ul> <li>use the <a href="http://www.rubyinside.com/bleakhouse-tool-to-find-memory-leaks-in-your-rails-applications-470.html" rel="nofollow noreferrer">Bleak House</a> plugin</li> <li>implement <a href="https://scoutapm.com/" rel="nofollow noreferrer">Scout monitoring</a> specifically the memory usage profiler</li> <li>try another <a href="https://github.com/binarylogic/memorylogic/tree/master" rel="nofollow noreferrer">simple memory usage logger</a></li> </ul> <p>The first is a graphical exploration of memory usage by objects in the ObjectSpace.</p> <p>The last two will help you identify specific usage patterns that are inflating memory usage, and you can work from there.</p> <p>As for specific coding-patterns, from experience you have to watch anything that's dealing with file io, image processing, working with massive strings and the like.</p> <p>I would check whether you are using the most appropriate XML library - ReXML is known to be slow and believed to be leaky (I have no proof of that!). Also check whether you can <a href="https://web.archive.org/web/20160418141426/http://unintelligible.org/blog/2007/08/16/one-line-ruby-memoization/" rel="nofollow noreferrer">memoize</a> expensive operations.</p>
<p>These gems worked for me:</p> <p><a href="https://github.com/binarylogic/memorylogic" rel="nofollow">MemoryLogic</a></p> <blockquote> <p>Adds in proccess id and memory usage in your rails logs, great for tracking down memory leaks</p> </blockquote> <p><a href="https://github.com/noahd1/oink" rel="nofollow">Oink</a></p> <blockquote> <p>Log parser to identify actions which significantly increase VM heap size</p> </blockquote>
19,497
<p>I'm using Entity Framework O/R mapper from Microsoft and using entity classes (generated classes that are mapped to DB objects) as a business objects. Is this OK? Please state your cons or pros. What to do in a case of WCF communication between business layer and presentation, how to send those objects as data members?</p>
<p>I am using EF in this fashion and one nice feature is that generated entities are partial classes, allowing them to be extended in a way that is fairly protected from regeneration issues.</p> <p>Also take a look at <a href="http://msdn.microsoft.com/en-us/library/cc716789.aspx" rel="noreferrer">this link on MSDN</a> which describes some common usage scenarios with EF in regards to Business Logic.</p>
<p>In my experience, we've used EF objects within the business layer of our application, but when we make the transition into the presentation layer through our WCF service layer, we will create view objects from the EF objects. </p> <p>In our case, only the view is passed to the presentation layer. We do this to control how the data is presented and apply defensive validation for data coming in from the presentation layer. </p> <p>In the case of ueing EF objects in the WCF transaction, you'll lose the object context that the EF object was associated. There are some efforts in CodePlex that try to help with this but I havn't kept up with their efforts.</p>
26,747
<p>Is there a mod_rewrite equivalent for IIS 7.0 that's </p> <p>a) more or less complete </p> <p>b) suitable for a production environment, i.e. battle-tested/dependable/secure</p> <p>Do you have an experience-based recommendation?</p>
<p>Check out the <a href="http://www.iis.net/downloads/microsoft/url-rewrite" rel="noreferrer">URL Rewrite Module for IIS 7</a> created by Microsoft</p>
<p><a href="http://www.isapirewrite.com/" rel="nofollow noreferrer">ISAPI Rewrite</a> is suitable for IIS 5 or 6. There's a Lite version available for free, or you can pay for the full version to get more features, such as proxying capabilities. It's been a while since I've used it, but it worked fine at the time.</p>
8,590
<p>When I create a view in SQL Server 2005 and someone later opens it in the GUI modify mode it sometimes completely rearranges my joins. Often to the point it's virtually no longer readable. If I look at it in the GUI it's changed as well from what I originally wrote. Sometimes the join lines no longer even point to a field and the join symbol has "fx". I assume it has "optimized" it for me. Is there a way to prevent this from happening? And what does "fx" mean? </p> <p>Originally it was something like this:</p> <p>FROM dbo.Stop LEFT OUTER JOIN dbo.StopType ON dbo.Stop.StopTypeID = dbo.StopType.StopTypeID LEFT OUTER JOIN dbo.CityState ON dbo.Stop.City = dbo.CityState.City AND dbo.Stop.State = dbo.CityState.State LEFT OUTER JOIN dbo.vwDrivers ON dbo.Stop.DriverID = dbo.vwDrivers.DriverID LEFT OUTER JOIN dbo.truck ON dbo.Truck.TruckID = dbo.Stop.TruckID INNER JOIN dbo.vwTicketIDFirstStopLastStop ON dbo.vwTicketIDFirstStopLastStop.TicketID = dbo.stop.ticketid LEFT OUTER JOIN dbo.Company ON dbo.Company.CompanyID = dbo.vwTicketIDFirstStopLastStop.BillToCompanyID</p> <p>Now it's this.</p> <p>FROM dbo.Truck RIGHT OUTER JOIN dbo.Stop INNER JOIN dbo.StopType ON dbo.Stop.StopTypeID = dbo.StopType.StopTypeID LEFT OUTER JOIN dbo.CityState ON dbo.Stop.City = dbo.CityState.City AND dbo.Stop.State = dbo.CityState.State LEFT OUTER JOIN dbo.vwDrivers ON dbo.Stop.DriverID = dbo.vwDrivers.DriverID ON dbo.Truck.TruckID = dbo.Stop.TruckID LEFT OUTER JOIN dbo.vwTicketIDFirstStopLastStop LEFT OUTER JOIN dbo.Company ON dbo.Company.CompanyID = dbo.vwTicketIDFirstStopLastStop.BillToCompanyID ON dbo.vwTicketIDFirstStopLastStop.TicketID = dbostop.ticketid</p>
<p>No you cannot. That's why you should never, ever use it.</p> <p>"Fx" means that the join is not a simple column-to-column link, but involves a function (that's also why it can't point to a field, of course). It should NOT do that by itself, though,</p>
<p>It's the result of the view GUI parsing the SQL into it's own internal DOM style format and then writing it back out - much in the same way that HTML editors take in XHTML and emit stuff differently to how you wanted it :(</p>
32,873
<p>In the following piece of code (taken from the <a href="http://groovy-lang.org/semantics.html#_while_loop" rel="noreferrer">Groovy Semantics Manual page</a>), why prefix the assignment with the keyword <code>def</code>?</p> <pre><code>def x = 0 def y = 5 while ( y-- &gt; 0 ) { println "" + x + " " + y x++ } assert x == 5 </code></pre> <p>The <code>def</code> keyword can be removed, and this snippet would produce the same results. So what's the <strong>effect</strong> of the keyword <code>def</code> ?</p>
<p>It's syntactic sugar for basic scripts. Omitting the "def" keyword puts the variable in the bindings for the current script and groovy treats it (mostly) like a globally scoped variable:</p> <pre><code>x = 1 assert x == 1 assert this.binding.getVariable("x") == 1 </code></pre> <p>Using the def keyword instead does not put the variable in the scripts bindings:</p> <pre><code>def y = 2 assert y == 2 try { this.binding.getVariable("y") } catch (groovy.lang.MissingPropertyException e) { println "error caught" } </code></pre> <p>Prints: "error caught"</p> <p>Using the def keyword in larger programs is important as it helps define the scope in which the variable can be found and can help preserve encapsulation.</p> <p>If you define a method in your script, it won't have access to the variables that are created with "def" in the body of the main script as they aren't in scope:</p> <pre><code> x = 1 def y = 2 public bar() { assert x == 1 try { assert y == 2 } catch (groovy.lang.MissingPropertyException e) { println "error caught" } } bar() </code></pre> <p>prints "error caught" </p> <p>The "y" variable isn't in scope inside the function. "x" is in scope as groovy will check the bindings of the current script for the variable. As I said earlier, this is simply syntactic sugar to make quick and dirty scripts quicker to type out (often one liners).</p> <p>Good practice in larger scripts is to always use the "def" keyword so you don't run into strange scoping issues or interfere with variables you don't intend to.</p>
<p>Actually, I <strong>don't</strong> think it would behave the same... </p> <p>variables in Groovy still require declaration, just not TYPED declaration, as the right-hand side generally contains enough information for Groovy to type the variable.</p> <p>When I try to use a variable that I haven't declared with def or a type, I get an error "No such property", since it assumes that I'm using a member of the class containing the code.</p>
22,249
<p>I have this piece of code (summarized)...</p> <pre><code>AnsiString working(AnsiString format,...) { va_list argptr; AnsiString buff; va_start(argptr, format); buff.vprintf(format.c_str(), argptr); va_end(argptr); return buff; } </code></pre> <p>And, on the basis that pass by reference is preferred where possible, I changed it thusly.</p> <pre><code>AnsiString broken(const AnsiString &amp;format,...) { ... the rest, totally identical ... } </code></pre> <p>My calling code is like this:-</p> <pre><code>AnsiString s1, s2; s1 = working("Hello %s", "World"); s2 = broken("Hello %s", "World"); </code></pre> <p>But, s1 contains "Hello World", while s2 has "Hello (null)". I think this is due to the way va_start works, but I'm not exactly sure what's going on.</p>
<p>If you look at what va_start expands out to, you'll see what's happening:</p> <pre><code>va_start(argptr, format); </code></pre> <p>becomes (roughly)</p> <pre><code>argptr = (va_list) (&amp;format+1); </code></pre> <p>If format is a value-type, it gets placed on the stack right before all the variadic arguments. If format is a reference type, only the address gets placed on the stack. When you take the address of the reference variable, you get the address or the original variable (in this case of a temporary AnsiString created before calling Broken), not the address of the argument.</p> <p>If you don't want to pass around full classes, your options are to either pass by pointer, or put in a dummy argument:</p> <pre><code>AnsiString working_ptr(const AnsiString *format,...) { ASSERT(format != NULL); va_list argptr; AnsiString buff; va_start(argptr, format); buff.vprintf(format-&gt;c_str(), argptr); va_end(argptr); return buff; } ... AnsiString format = "Hello %s"; s1 = working_ptr(&amp;format, "World"); </code></pre> <p>or</p> <pre><code>AnsiString working_dummy(const AnsiString &amp;format, int dummy, ...) { va_list argptr; AnsiString buff; va_start(argptr, dummy); buff.vprintf(format.c_str(), argptr); va_end(argptr); return buff; } ... s1 = working_dummy("Hello %s", 0, "World"); </code></pre>
<p>Side note:</p> <p>The behavior for class types as varargs arguments may be undefined, but it's consistent in my experience. The compiler pushes sizeof(class) of the class's memory onto the stack. Ie, in pseudo-code:</p> <pre><code>alloca(sizeof(class)); memcpy(stack, &amp;instance, sizeof(class); </code></pre> <p>For a really interesting example of this being utilized in a very creative way, notice that you <em>can</em> pass a CString instance in place of a LPCTSTR to a varargs function directly, and it works, and there's no casting involved. I leave it as an exercise to the reader to figure out how they made that work.</p>
27,409
<p>I'm creating a series of builders to clean up the syntax which creates domain classes for my mocks as part of improving our overall unit tests. My builders essentially populate a domain class (such as a <code>Schedule</code>) with some values determined by invoking the appropriate <code>WithXXX</code> and chaining them together.</p> <p>I've encountered some commonality amongst my builders and I want to abstract that away into a base class to increase code reuse. Unfortunately what I end up with looks like:</p> <pre><code>public abstract class BaseBuilder&lt;T,BLDR&gt; where BLDR : BaseBuilder&lt;T,BLDR&gt; where T : new() { public abstract T Build(); protected int Id { get; private set; } protected abstract BLDR This { get; } public BLDR WithId(int id) { Id = id; return This; } } </code></pre> <p>Take special note of the <code>protected abstract BLDR This { get; }</code>.</p> <p>A sample implementation of a domain class builder is:</p> <pre><code>public class ScheduleIntervalBuilder : BaseBuilder&lt;ScheduleInterval,ScheduleIntervalBuilder&gt; { private int _scheduleId; // ... // UG! here's the problem: protected override ScheduleIntervalBuilder This { get { return this; } } public override ScheduleInterval Build() { return new ScheduleInterval { Id = base.Id, ScheduleId = _scheduleId // ... }; } public ScheduleIntervalBuilder WithScheduleId(int scheduleId) { _scheduleId = scheduleId; return this; } // ... } </code></pre> <p>Because BLDR is not of type BaseBuilder I cannot use <code>return this</code> in the <code>WithId(int)</code> method of <code>BaseBuilder</code>.</p> <p>Is exposing the child type with the property <code>abstract BLDR This { get; }</code> my only option here, or am I missing some syntax trick?</p> <p>Update (since I can show why I'm doing this a bit more clearly):</p> <p>The end result is to have builders that build profiled domain classes that one would expect to retrieve from the database in a [programmer] readable format. There's nothing wrong with...</p> <pre><code>mock.Expect(m =&gt; m.Select(It.IsAny&lt;int&gt;())).Returns( new Schedule { ScheduleId = 1 // ... } ); </code></pre> <p>as that's pretty readable already. The alternative builder syntax is:</p> <pre><code>mock.Expect(m =&gt; m.Select(It.IsAny&lt;int&gt;())).Returns( new ScheduleBuilder() .WithId(1) // ... .Build() ); </code></pre> <p>the advantage I'm looking for out of using builders (and implementing all these <code>WithXXX</code> methods) is to abstract away complex property creation (automatically expand our database lookup values with the correct <code>Lookup.KnownValues</code> without hitting the database obviously) and having the builder provide commonly reusable test profiles for domain classes...</p> <pre><code>mock.Expect(m =&gt; m.Select(It.IsAny&lt;int&gt;())).Returns( new ScheduleBuilder() .AsOneDay() .Build() ); </code></pre>
<p>All I can say is that if there <em>is</em> a way of doing it, I want to know about it too - I use <em>exactly</em> this pattern in my <a href="http://github.com/jskeet/dotnet-protobufs/tree/master" rel="noreferrer">Protocol Buffers port</a>. In fact, I'm glad to see that someone else has resorted to it - it means we're at least somewhat likely to be right!</p>
<p>This is a good implementation strategy for C#.</p> <p>Some other languages (can't think of name of research language I've seen this in) have type systems that either support a covariant "self"/"this" directly, or have other clever ways to express this pattern, but with C#'s type system, this is a good (only?) solution.</p>
30,355
<p>Ok, so I just ran into the following problem that raised an eyebrow.</p> <p>For various reasons I have a testing setup where Testing classes in a TestingAssembly.dll depend on the TestingBase class in a BaseTestingAssembly.dll. One of the things the TestBase does in the meantime is look for a certain embedded resource in its own and the calling assembly</p> <p>So my BaseTestingAssembly contained the following lines...</p> <pre><code>public class TestBase { private static Assembly _assembly; private static Assembly _calling_assembly; static TestBase() { _assembly = Assembly.GetExecutingAssembly(); _calling_assembly = Assembly.GetCallingAssembly(); } } </code></pre> <p>Static since I figured, these assemblies would be the same over the application's lifetime so why bother recalculating them on every single test.</p> <p>When running this however I noticed that both _assembly and _calling_assembly were being set to BaseTestingAssembly rather than BaseTestingAssembly and TestingAssembly respectively.</p> <p>Setting the variables to non-static and having them initialized in a regular constructor fixed this but I am confused why this happened to begin this. I thought static constructors run the first time a static member gets referenced. This could only have been from my TestingAssembly which should then have been the caller. Does anyone know what might have happened?</p>
<p>The static constructor is called by the runtime and not directly by user code. You can see this by setting a breakpoint in the constructor and then running in the debugger. The function immediately above it in the call chain is native code.</p> <p><strong>Edit:</strong> There are a lot of ways in which static initializers run in a different environment than other user code. Some other ways are</p> <ol> <li>They're implicitly protected against race conditions resulting from multithreading</li> <li>You can't catch exceptions from outside the initializer</li> </ol> <p>In general, it's probably best not to use them for anything too sophisticated. You can implement single-init with the following pattern:</p> <pre><code>private static Assembly _assembly; private static Assembly Assembly { get { if (_assembly == null) _assembly = Assembly.GetExecutingAssembly(); return _assembly; } } private static Assembly _calling_assembly; private static Assembly CallingAssembly { get { if (_calling_assembly == null) _calling_assembly = Assembly.GetCallingAssembly(); return _calling_assembly; } } </code></pre> <p>Add locking if you expect multithreaded access.</p>
<p>I think the answer is here in the discussion of <a href="http://msdn.microsoft.com/en-us/library/k9x6w0hc(VS.80).aspx" rel="nofollow noreferrer">C# static constructors</a>. My best guess is that the static constructor is getting called from an unexpected context because:</p> <blockquote> <p>The user has no control on when the static constructor is executed in the program</p> </blockquote>
14,827
<p>I am currently trying to learn all new features of C#3.0. I have found a very nice collection of <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx" rel="nofollow noreferrer">sample to practice LINQ</a> but I can't find something similar for Lambda.</p> <p>Do you have a place that I could practice Lambda function?</p> <h2>Update</h2> <p>LINQpad is great to learn Linq (thx for the one who suggest) and use a little bit Lambda in some expression. But I would be interesting in more specific exercise for Lambda.</p>
<p><a href="http://linqpad.net/" rel="noreferrer">LINQPad</a> is a good tool for learning LINQ</p>
<p>The best that I have found is this <a href="http://www.albahari.com/nutshell/linqquiz.aspx" rel="nofollow noreferrer">link</a> for the moment. It's a quiz that let met practice, but I would like something more Lambda and less LINQ.</p>
30,286
<p>Can anyone explain the difference between <code>Server.MapPath(".")</code>, <code>Server.MapPath("~")</code>, <code>Server.MapPath(@"\")</code> and <code>Server.MapPath("/")</code>?</p>
<p><strong>Server.MapPath</strong> specifies the relative or virtual path to map <strong>to a physical directory</strong>.</p> <ul> <li><code>Server.MapPath(".")</code><sup>1</sup> returns the current physical directory of the file (e.g. aspx) being executed</li> <li><code>Server.MapPath("..")</code> returns the parent directory</li> <li><code>Server.MapPath("~")</code> returns the physical path to the root of the application</li> <li><code>Server.MapPath("/")</code> returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)</li> </ul> <p><em>An example:</em></p> <p>Let's say you pointed a web site application (<code>http://www.example.com/</code>) to</p> <pre><code>C:\Inetpub\wwwroot </code></pre> <p>and installed your shop application (sub web as virtual directory in IIS, marked as application) in </p> <pre><code>D:\WebApps\shop </code></pre> <p>For example, if you call <code>Server.MapPath()</code> in following request:</p> <pre><code>http://www.example.com/shop/products/GetProduct.aspx?id=2342 </code></pre> <p>then:</p> <ul> <li><code>Server.MapPath(".")</code><sup>1</sup> returns <code>D:\WebApps\shop\products</code></li> <li><code>Server.MapPath("..")</code> returns <code>D:\WebApps\shop</code></li> <li><code>Server.MapPath("~")</code> returns <code>D:\WebApps\shop</code></li> <li><code>Server.MapPath("/")</code> returns <code>C:\Inetpub\wwwroot</code></li> <li><code>Server.MapPath("/shop")</code> returns <code>D:\WebApps\shop</code></li> </ul> <p>If Path starts with either a forward slash (<code>/</code>) or backward slash (<code>\</code>), the <code>MapPath()</code> returns a path as if Path was a full, virtual path. </p> <p>If Path doesn't start with a slash, the <code>MapPath()</code> returns a path relative to the directory of the request being processed.</p> <p><em>Note: in C#, <code>@</code> is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.</em></p> <p><em>Footnotes</em></p> <ol> <li><code>Server.MapPath(null)</code> and <code>Server.MapPath("")</code> will <a href="https://stackoverflow.com/a/17616488/1185053">produce this effect too</a>.</li> </ol>
<p>1) <code>Server.MapPath(".")</code> -- Returns the "Current Physical Directory" of the file (e.g. <code>aspx</code>) being executed.</p> <p>Ex. Suppose <code>D:\WebApplications\Collage\Departments</code></p> <p>2) <code>Server.MapPath("..")</code> -- Returns the "Parent Directory"</p> <p>Ex. <code>D:\WebApplications\Collage</code></p> <p>3) <code>Server.MapPath("~")</code> -- Returns the "Physical Path to the Root of the Application"</p> <p>Ex. <code>D:\WebApplications\Collage</code></p> <p>4) <code>Server.MapPath("/")</code> -- Returns the physical path to the root of the Domain Name </p> <p>Ex. <code>C:\Inetpub\wwwroot</code></p>
34,762
<p>How would I achieve the pseudo-code below in JavaScript? I want to include the date check in the second code excerpt, where txtDate is for the BilledDate.</p> <pre><code>If ABS(billeddate – getdate) &gt; 31 then yesno “The date you have entered is more than a month from today, Are you sure the date is correct,”. if (txtDate &amp;&amp; txtDate.value == "") { txtDate.focus(); alert("Please enter a date in the 'Date' field.") return false; } </code></pre>
<p>Generally speaking you work with Date-objects in javascript, and these should be constructed with the following syntax:</p> <pre><code> var myDate = new Date(yearno, monthno-1, dayno); //you could put hour, minute, second and milliseconds in this too </code></pre> <p>Beware, the month-part is an index, so january is 0, february is 1 and december is 11 !-)</p> <p>Then you can pull out anything you want, the .getTime() thing returns number of milliseconds since start of Unix-age, 1/1 1970 00:00, så this value you could subtract and then look if that value is greater than what you want:</p> <pre><code>//today (right now !-) can be constructed by an empty constructor var today = new Date(); var olddate = new Date(2008,9,2); var diff = today.getTime() - olddate.getTime(); var diffInDays = diff/(1000*60*60*24);//24 hours of 60 minutes of 60 second of 1000 milliseconds alert(diffInDays); </code></pre> <p>This will return a decimal number, so probably you'll want to look at the integer-value:</p> <pre><code>alert(Math.floor(diffInDays)); </code></pre>
<p>Hello and good day for everyone</p> <p>You can try Refular Expressions to parse and validate a date format</p> <p>here is an URL yoy can watch some samples and how to use</p> <p><a href="http://www.javascriptkit.com/jsref/regexp.shtml" rel="nofollow noreferrer">http://www.javascriptkit.com/jsref/regexp.shtml</a></p> <p>A very very simple pattern would be: \d{2}/\d{2}/\d{4}</p> <p>for MM/dd/yyyy or dd/MM/yyyy</p> <p>With no more.... bye bye</p>
29,744
<p>Is it a best practice to use stored procedure for every single SQL call in .NET applications?</p> <p>Is it encouraged for performance reasons and to reduce surface area for SQL injection attacks (in web applications)?</p>
<p>Stored procedures have a few advantages over parameterized queries:</p> <ol> <li><p>When used <em>exclusively</em>, you can turn off CREATE, INSERT, SELECT, UPDATE, ALTER, DROP, DELETE, etc access for your application accounts, and this way add a small amount of security.</p></li> <li><p>They provide a consistent, manageable interface when you have multiple applications using the same database.</p></li> <li><p>Using procedures allows a DBA to manage and tune queries even after an application is deployed.</p></li> <li><p>Deploying small changes and bug fixes is much simpler.</p></li> </ol> <p>They also have a few disadvantages:</p> <ol> <li><p>The number of procedures can quickly grow to the point where maintaining them is difficult, and current tools don't provide a simple method for adequate documentation.</p></li> <li><p>Parameterized queries put the database code next to the place where it's used. Stored procedures keep it far separated, making finding related code more difficult.</p></li> <li><p>Stored procedures are harder to version.</p></li> </ol> <p>You'll need to weigh those costs/benefits for your system.</p>
<p>No. </p> <p>If you send your queries to SQL Server as parameterized queries, SQL Server will cache the execution plan AND will sanitize your parameter inputs properly to avoid SQL injection attacks.</p>
44,255
<p>I've written 2 reasonably large scale apps in .net so far, and both of them have needed an updating facility to automatically update the application when I roll out new code.</p> <p>I've found the 'Enterprise application block updater' a bit too complex for my needs, and I've found 'click once' frustrating when it comes to publishing.</p> <p>The most adequate updating code I've found is the <a href="http://windowsclient.net/articles/appupdater.aspx" rel="nofollow noreferrer">.net Application Updater Component</a>, which I've used for both projects. I've had to modify it recently because it uses web dav, which isn't always installed on our web servers (it still needs directory browsing, however).</p> <p>I'm surprised that there isn't more on the web about automatically updating applications, and was wondering whether people have had success with any other methods than the ones mentioned above?</p>
<p>See the answers to <a href="https://stackoverflow.com/questions/37030/how-to-best-implement-software-updates-on-windows">this similar question</a>: a few auto-update frameworks were recommended there which are designed for (or work with) .net apps:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms978574.aspx" rel="nofollow noreferrer">Application Updater Block</a> (which you mention)</li> <li><a href="http://msdn.microsoft.com/en-us/library/142dbbz4.aspx" rel="nofollow noreferrer">ClickOnce</a>, </li> <li><a href="http://wix.sourceforge.net/clickthrough.html" rel="nofollow noreferrer">ClickThrough</a></li> </ul>
<p>Try an off-the-shelf autoupdate product: <a href="http://www.AutoUpdatePlus.com" rel="nofollow noreferrer">http://www.AutoUpdatePlus.com</a></p>
7,236
<p>I was writing some Unit tests last week for a piece of code that generated some SQL statements.</p> <p>I was trying to figure out a regex to match <code>SELECT</code>, <code>INSERT</code> and <code>UPDATE</code> syntax so I could verify that my methods were generating valid SQL, and after 3-4 hours of searching and messing around with various regex editors I gave up.</p> <p>I managed to get partial matches but because a section in quotes can contain any characters it quickly expands to match the whole statement.</p> <p>Any help would be appreciated, I'm not very good with regular expressions but I'd like to learn more about them.</p> <p>By the way it's C# RegEx that I'm after.</p> <p><strong>Clarification</strong></p> <p>I don't want to need access to a database as this is part of a Unit test and I don't wan't to have to maintain a database to test my code. which may live longer than the project.</p>
<p>Regular expressions can match languages only a finite state automaton can parse, which is very limited, whereas SQL is a syntax. <strong>It can be demonstrated you can't validate SQL with a regex.</strong> So, you can stop trying.</p>
<p>I am assuming you did something like <code>.\*</code> try instead <code>[^"]*</code> that will keep you from eating the whole line. It still will give false positives on cases where you have <code>\</code> inside your strings.</p>
16,926
<p>I believe I already know the answer, but I am not 100% sure, so just a quick question: What does Red/Green Testing actually mean?</p> <p>I understand it as "Write your tests first, so that they all fail (= all red), then write your code and watch how each test turns green, and when all are green, you're fine".</p> <p>I heard this in <a href="http://sessions.visitmix.com/?selectedSearch=T22" rel="noreferrer">Scott's MVC Talk at Mix</a>, so I do not know if this is an "official" term or if he just made it up. (Edit: Scott actually also explains it starting at 55:00 Minutes, and he made a good remark why he beleives in it)</p>
<p>It does refer to TDD or Test Driven Development, but it would apply to each test. Write the test first, then write the code to pass the test. It would be wrong to write ALL the tests first. TDD is an incremental development approach.</p> <p>The basic idea is no code is written before there is failing test (RED). When you have a failing test, then you write the code to pass the test (GREEN). Now you are ready to write the next test -- i.e., no new tests until all are green. Or refactor, as @Brian points out.</p>
<p>When you run a TDD GUI, the display is red until all tests pass, then it switches to green.</p> <p>This is a summary of the rough outline of test-first development.</p> <ol> <li><p>Write some skeleton code that compiles, has enough API to be testable.</p></li> <li><p>Write tests which -- initially -- will be mostly failures. Red.</p></li> <li><p>Finish the code. The tests pass. Green.</p></li> </ol> <p>At this point, you at least have something that works. However, what you have is not very high quality. So you'll need to refactor to improve overall quality.</p>
34,914
<p>What column names cannot be used when creating an Excel spreadsheet with ADO.</p> <p>I have a statement that creates a page in a spreadsheet:</p> <pre><code>CREATE TABLE [TableName] (Column string, Column2 string); </code></pre> <p>I have found that using a column name of <code>Date</code> or <code>Container</code> will generate an error when the statement is executed.</p> <p>Does anyone have a complete (or partial) list of words that cannot be used as column names? This is for use in a user-driven environment and it would be better to "fix" the columns than to crash. </p> <p>My work-around for these is to replace any occurences of <code>Date</code> or <code>Container</code> with <code>Date_</code> and <code>Container_</code> respectively.</p>
<p>It may be possible to define a custom template for the DIP and deploy that to the site, setting the content type to link to that template.</p>
<p>I found a solution in a blog, but you have to use InfoPath... Here is the link: Using SharePoint Metadata in Word Documents – The Lookup Column </p> <p><a href="http://vspug.com/maartene/2009/03/13/using-sharepoint-metadata-in-word-documents-the-lookup-column-issue/" rel="nofollow noreferrer">http://vspug.com/maartene/2009/03/13/using-sharepoint-metadata-in-word-documents-the-lookup-column-issue/</a></p>
11,310
<p>I am looking for guidance regarding the best practice around the use of the Profile feature in ASP.NET.</p> <p>How do you decide what should be kept in the built-in user Profile, or if you should create your own database table and add a column for the desired fields? For example, a user has a zip code, should I save the zip code in my own table, or should I add it to the web.config xml profile and access it via the user profile ASP.NET mechanism? </p> <p>The pros/cons I can think of right now are that since I don't know the profile very well (it is a bit of a <em>Matrix</em> right now), I probably can do whatever I want if I go the table route (e.g., SQL to get all the users in the same zip code as the current user). I don't know if I can do the same if I use the ASP.NET profile.</p>
<p>Ive only built 2 applications that used the profile provider. Since then I have stayed away from using it. For both of the apps I used it to store information about the user such as their company name, address and phone number. </p> <p>This worked fine until our client wanted to be able to find a user by one of these fields. Searching involved looping through <strong>every</strong> users profile and comparing the information to the search criteria. As the user base grew the search time became unacceptable to our client. The only solution was to create a table to store the users information. Search speed was increased immensely.</p> <p>I would recommend storing this type of information in its own table.</p>
<p>In my experience its best to keep an the info in the profile to a bare minimum, only put the essentials in there that are directly needed for authentication. Other information such as addresses should be saved in your own database by your own application logic, this approach is more extensible and maintainable.</p>
2,401
<p>Are people still writing <a href="http://zeroc.com/blogs/michi/" rel="noreferrer">SOAP services</a> or is it a technology that has passed its <a href="http://www.addsimplicity.com/" rel="noreferrer">architectural shelf life</a>? Are people returning to binary formats?</p>
<p>The alternative to SOAP is not binary formats.</p> <p>I think you're seeing a surge in the desire to leave the complexities of WS-* behind in favor of REST and JSON, because they're much simpler to use and don't require frameworks to be used successfully. The problems that WS-* ostensibly tries to solve aren't problems for most users, but they have to pay for the complexity any way.</p>
<p>Yes, some people <strong>still</strong> are (and now it's 2011!). I think the main reason is that MS WCF automatically generates SOAP bindings. The horror. </p>
5,938
<p>While porting an application from SQL 2005 to SQL Server Compact Edition, I found that I need to port this command:</p> <pre><code>SELECT TOP 1 Id FROM tblJob WHERE Holder_Id IS NULL </code></pre> <p>But SQL Server Compact Edition doesn't support the <code>TOP</code> keyword. How can I port this command?</p>
<pre><code>SELECT TOP(1) Id FROM tblJob WHERE Holder_Id IS NULL </code></pre> <p>Need the brackets as far as I know.</p> <p>reference: <a href="http://technet.microsoft.com/en-us/library/bb686896.aspx" rel="noreferrer">http://technet.microsoft.com/en-us/library/bb686896.aspx</a></p> <p>addition: likewise, only for version 3.5 onwards</p>
<p>Looks like it can't be done in compact. You have to read all the jobs, or make a SqlReader, and just read the first one.</p>
16,759
<p>I work on relatively sensitive code that we wouldn't want falling into the wrong hands. Up until now, all the code has been keep in house so it hasn't been an issue. I am moving to working from home a day or two a week and we want to secure the code on my laptop.</p> <p>We have looked at a few alternatives, but Windows EFS and Bitlocker seem to be the most obvious. The laptop doesn't have TPM hardware, and I won't have access to Active Directory from home, so EFS looks to be the option.</p> <p>Basically, does anyone else have any alternatives, or issues with using EFS to encrypt source code? </p>
<p><a href="http://www.truecrypt.org/downloads.php" rel="nofollow noreferrer">Truecrypt</a>:</p> <blockquote> <p><strong>WARNING: Using TrueCrypt is not secure as it may contain unfixed security issues</strong></p> <p>This page exists only to help migrate existing data encrypted by TrueCrypt.</p> <p>The development of TrueCrypt was ended in 5/2014 after Microsoft terminated support of Windows XP. Windows 8/7/Vista and later offer integrated support for encrypted disks and virtual disk images. Such integrated support is also available on other platforms (click <a href="http://truecrypt.sourceforge.net/OtherPlatforms.html" rel="nofollow noreferrer">here</a> for more information). You should migrate any data encrypted by TrueCrypt to encrypted disks or virtual disk images supported on your platform...</p> </blockquote>
<p>The last time I did this was a few years ago, but we used PGPdisk. It did a good job.</p>
16,459
<p>It's kind of embarassing that I find it so difficult to learn JavaScript, but .. </p> <p>Let's say I have a really simple controller like this:</p> <pre><code>class front extends Controller { public function __construct() { parent::Controller(); } public function index() { //nothing! } public function test () { $someNumber = $this-&gt;input-&gt;post('someNumber'); if ($someNumber == 12) { return TRUE; } } } </code></pre> <p>Yes, that could probably be written better, haha. </p> <p>What I want to know is - how could I use JavaScript to submit a number in a form (I'll worry about validation and models later), how should I write my test() function so that it returns something readable by the JavaScript (I'm assuming return TRUE probably wouldn't work, perhaps XML or JSON or something like that?), and how do I access the data with the JavaScript? </p> <p>I know there are frameworks like jQuery that will help with this, but right now I'd just like to understand it at the simplest level and all the tutorials and guides I've found so far are way too in depth for me. An example in jQuery or whatever would be good too. </p> <p>Thanks a lot :)</p>
<p>you would just print it out basically, and re-capture that information via javascript:</p> <pre><code>public function test() { $somenumber = $this-&gt;input-&gt;post('someNumber'); if ($somenumber == 12) { print "Number is 12"; } else { print "Number is not 12"; } } </code></pre> <p>your javascript might look something like this:</p> <pre><code>var xhr; xhr = new XMLHTTPRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { // this is where the return information is alert('Status: '+xhr.status+' Response: '+xhr.responseText); } } xhr.open('POST', '/front/test'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send('someNumber=12'); </code></pre> <p>the code above doesn't take into account browser specific issues, but should run on firefox/ie7 at least i believe.</p> <p>here's a jQuery example of all the above:</p> <pre><code>var options = { 'someNumber' : 12 } $.post('/front/test', options, function(data) { alert(data); // should print "Number is 12" }); </code></pre>
<p>I've also found in CodeIgniter that 'XMLHTTPRequest' isn't returned in the response headers, when using the standard Javascript AJAX call as mentioned above. </p> <pre><code>$this-&gt;input-&gt;is_ajax_request(); </code></pre> <p>The input helper doesn't ever return true unless you use jQuery to handle the AJAX POST request.</p> <p>I also tried the method in this article which didn't work: <a href="http://developer.practicalecommerce.com/articles/1810-The-Benefit-of-Putting-AJAX-and-CodeIgniter-PHP-Together" rel="nofollow">http://developer.practicalecommerce.com/articles/1810-The-Benefit-of-Putting-AJAX-and-CodeIgniter-PHP-Together</a></p> <p>This is what I used in the end:</p> <pre><code> var query_params = $('#data-form').serialize(); $.ajax({ type: 'POST', url: 'process_this.php", data: queryParams, context: document.body, success: function(){ alert('complete'); // or whatever here } </code></pre> <p>Possibly caused by a config issue to do with my CI install, haven't had time to investigate yet.</p>
39,665
<p>How do I speed up prints for the Monoprice Select IIIP Plus printer?</p> <p>The manual shows [Cura] examples of:</p> <ul> <li>Print speed: 50mm/s</li> <li>Travel Speed: 80mm/s</li> <li>Bottom Layer Speed: 20mm/s</li> <li>Infill Speed: 50mm/s</li> <li>Outer shell speed: 15mm/s</li> <li>Inner shell speed: 30mm/s</li> </ul> <p>However, this doesn’t line up with their advertisements online of a 150mm/s printing speed.</p> <p>Are there better settings to use, especially ones which can speed up printing time? Or are there any other measures which I can take in order to reduce printing time in general? </p>
<p>In my experience a print speed of 50-70mm/s is ideal. Even if you set the speed to 150mm/s the print head still changes directions often and rarely will have enough time to accelerate from 0->150 before changing direction again. </p> <p>Some more effective ways of speeding up prints is to adjust</p> <ul> <li>Layer height</li> <li>Infill percentage (15-25% for regular prints, more if they need to be more sound)</li> <li>Supports</li> <li>Number of shells, etc</li> </ul>
<p>I was using Cura's default settings for a Prusa I3 on my MonoPrice Select V2 (model #13860), and got horrible results frequently. Then I used the settings you list, and got very nice results. Compare the below images for the bottom layer of 4 benchys, with adhesion brim.</p> <p>I'm using PLA, 0.4mm nozzle, 60C for bed, 200C for extruder, 1.75mm filament from Hatchbox.</p> <p><strong>Default Cura Settings</strong> <a href="https://i.stack.imgur.com/akAJu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/akAJu.jpg" alt="Using default Cura settings"></a></p> <p><strong>Listed Settings</strong> <a href="https://i.stack.imgur.com/Zg76A.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zg76A.jpg" alt="Using recommended settings"></a></p> <p><strong>Settings breakdown</strong></p> <pre><code>Setting Cura default Recommended Print Speed 60 50 Outer Wall Speed 30 15 Inner Wall Speed 60 30 Top/Bottom Speed 30 20 Travel Speed 120 80 </code></pre> <p><strong>Symptoms of my printer being told to print too fast:</strong></p> <p>Material would not adhere properly to the print bed, and would start making clumps. These would rest either on the bed, or on the nozzle itself. The ones on the bed would grow taller than layer height, making the next pass of the nozzle bump against it, further depositing material on it. The clumps on the nozzle would drop at other points, leaving stringing filament all over, and further compromising the next pass of the head.</p> <p>This might seem like a bed adhesion problem, but the prints were <em>very</em> well attached to the bed; I had to apply a lot of force to remove a 15*15cm square from the bed.</p> <p>Increasing the hot-end temperature seemed to help; at some point we were printing at 230C, well beyond Hatchbox' extrusion temperature range (range is listed as 180C-210C for this PLA batch).</p> <p>Ultimately, reducing print speed to the settings listed helped us increase print quality back to acceptable levels.</p>
654
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <hr> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
<p>Use a <a href="http://en.wikipedia.org/wiki/Trie" rel="noreferrer">trie</a>.</p> <p>Add your list of words to a trie. Each path from the root to a leaf is a valid word. A path from a root to an intermediate node represents a prefix, and the children of the intermediate node are valid completions for the prefix.</p>
<p>If your dictionary is really big, i'd suggest indexing with a python text index (PyLucene - note that i've never used the python extension for lucene) The search would be efficient and you could even return a search 'score'.</p> <p>Also, if your dictionary is relatively static you won't even have the overhead of re-indexing very often.</p>
13,760
<p>For my current project, I need to request XML data over a tcp/ip socket connection. For this, I am using the TcpClient class:</p> <pre><code>Dim client As New TcpClient() client.Connect(server, port) Dim stream As NetworkStream = client.GetStream() stream.Write(request) stream.Read(buffer, 0, buffer.length) // Output buffer and return results... </code></pre> <p>Now this works fine and dandy for small responses. However, when I start receiving larger blocks of data, it appears that the data gets pushed over the socket connection in bursts. When this happens, the stream.Read call only reads the first burst, and thus I miss out on the rest of the response. </p> <p>What's the best way to handle this issue? Initially I tried to just loop until I had a valid XML document, but I found that in between stream.Read calls the underlying stream would sometimes get shut down and I would miss out on the last portion of the data.</p>
<p>You create a loop for reading.</p> <p>Stream.Read returns int for the bytes it read so far, or 0 if the end of stream is reached.</p> <p>So, its like:</p> <pre><code>int bytes_read = 0; while (bytes_read &lt; buffer.Length) bytes_read += stream.Read(buffer, bytes_read, buffer.length - bytes_read); </code></pre> <p>EDIT: now, the question is how you determine the size of the buffer. If your server first sends the size, that's ok, you can use the above snippet. But if you have to read until the server closes the connection, then you have to use try/catch (which is good idea even if you know the size), and use bytes_read to determine what you received.</p> <pre><code>int bytes_read = 0; try { int i = 0; while ( 0 &lt; (i = stream.Read(buffer, bytes_read, buffer.Length - bytes_read) ) bytes_read += i; } catch (Exception e) { //recover } finally { if (stream != null) stream.Close(); } </code></pre>
<p>This is a possible way to do that and get in "response" the response string. If you need the byte array, just save ms.ToArray().</p> <pre><code>string response; TcpClient client = new TcpClient(); client.Connect(server, port); using (NetworkStream ns = c.GetStream()) using (MemoryStream ms = new MemoryStream()) { ns.Write(request); byte[] buffer = new byte[512]; int bytes = 0; while(ns.DataAvailable) { bytes = ns.Read(buffer,0, buffer.Length); ms.Write(buffer, 0, bytes); } response = Encoding.ASCII.GetString(ms.ToArray()); } </code></pre>
20,333
<p>I'm working on a game (C#) that uses a <a href="http://robocode.sourceforge.net/" rel="nofollow noreferrer">Robocode-like</a> programming model: participants inherit a base Class and add strategic behaviors. The game then loads instances of participants' Classes and the competition begins. Unfortunately, participants can "cheat" by sharing static variables between instances of their competitor Class.</p> <p>How do I prevent static variable sharing between Class instances in a .NET language? I know this is accomplished in Java by using a separate ClassLoader per instance. What's the .NET equivalent? </p> <p>Further, my testing shows that separate AppDomains only work when loading a Class that extends MarshalByRefObject. I guess this makes sense - if you simply load a Serializable Class, the Class is copied into the current AppDomain so a second object from a different AppDomain will share its static vars. MarshalByRefObject guarantees that only a proxy is loaded into the current AppDomain and the statics stay behind in the loading AppDomain. See also: <a href="http://blogs.msdn.com/ericlippert/archive/2004/05/27/143203.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/ericlippert/archive/2004/05/27/143203.aspx</a></p>
<p>Load each competitor into a different AppDomain.</p>
<p>I don't have a specific answer, but I would look at the .NET <a href="http://www.codeplex.com/terrarium2" rel="nofollow noreferrer">Terrarium</a> project. All participants are user loaded DLLs. They have done a lot of neat stuff to prevent unsafe and cheater code from loading/executing.</p> <p>Justin Rogers has <a href="http://weblogs.asp.net/justin_rogers/archive/tags/Terrarium/default.aspx" rel="nofollow noreferrer">written extensively</a> on Terrarium implementation details.</p>
10,969
<p>I dynamically create an element (div) in javascript, on which i register an event listener:</p> <pre><code>var tooltip = document.createElement('div'); tooltip.onclick = function() { alert('hello'); } </code></pre> <p>Now, if I attach this element to the document body:</p> <pre><code>document.body.appendChild(tooltip); </code></pre> <p>all is well and the event is captured. However (for positioning purposes) i want to attach this element to a (static) sub-element within my page, e.g:</p> <pre><code>document.getElementById('id').appendChild(tooltip); </code></pre> <p>and the element is generated and positioned correctly - but the onclick event now is no longer captured. Any thoughts? This is x-browser, so i must be missing something.</p> <p>Thanks, Don. </p>
<p>Maybe you need to register the event handler after appending?</p>
<p>Your code works fine for me on firefox 3.0.5 and IE7. Are you sure your example is correct?</p>
49,489
<p>I'm looking for a small and fast library implementing an HTTP server in .NET</p> <p>My general requirements are:</p> <ul> <li>Supports multiple simultaneous connections</li> <li>Only needs to support static content (no server side processing)</li> <li>HTTP only, HTTPS not needed</li> <li>Preferably be able to serve a page from an in memory source. I want to integrate it into another app to be able to make changing data available via a browser, but I don't want to have to write it to a file on disk first. For example, just pass it a C# string to use as the current page content.</li> <li>Preferably open source so I can modify it if needed</li> <li><em>Definitely</em> needs to be free... it's for a personal project with no budget other than my own time. I also want to be able to release the final product that would use this library freely (even if that means complying to the particular OSS license of that library.</li> </ul> <p>Edit: To clarify some more, what I need can be REALLY simple. I need to be able to serve essentially 2 documents, which I would like to be served directly from memory. And that's it. Yes, I could write my own, but I wanted to make sure I wasn't doing something that was already available.</p>
<p>Use <a href="http://www.asp.net/downloads/archived/cassini/" rel="nofollow noreferrer">Cassini</a>.</p> <p>Free, Open Source.</p> <p>It would take trivial hacking to serve from memory.</p>
<p><a href="https://github.com/javidsho/LightHTTP" rel="nofollow noreferrer">LightHTTP</a> is an open-source library I've created that does exactly what you need.</p> <ul> <li>It can be used in testing and mocking, or other scenarios where a lightweight HTTP server is preferred.</li> <li>It works asynchronously.</li> <li>Supports simultaneous connections.</li> <li>It can serve anyway you'd need, since it's based on <code>HttpListener</code>.</li> </ul>
34,421
<p>I've been trying for a while now to write a unit test for a UserViewControl in ASP.NET MVC. I'd like to get to code that looks something like this:</p> <pre><code>[TestMethod] public void HaveControlToDisplayThings() { var listControl = new ControlUnderTest(); var viewData = new ViewDataDictionary&lt;IList&lt;string&gt;&gt;(this.repo.GetMeSomeData()); // Set up a ViewContext using Moq. listControl.SetFakeViewContext(viewData); listControl.ViewData = viewData; listControl.RenderView(listControl.ViewContext); // Never got this far, no idea if this will work :) string s = listControl.ViewContext.HttpContext.Response.Output.ToString(); Assert.AreNotEqual(0, s.Length); foreach (var item in this.repo.GetMeSomeData()) { Assert.IsTrue(s.IndexOf(item) != -1); } } </code></pre> <p>Unfortunately, no matter what I try I get errors from deep inside RenderView. This is caused (as far as I can tell) by the static HttpContext.Current object being useless - I get <code>NullReferenceException</code>s from <code>System.Web.UI.Page.SetIntrinsics</code>.</p> <p>I tried using Phil Haack's <a href="http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx" rel="nofollow noreferrer">HttpSimulator</a> which gave me a HttpContext object but I found I also needed to specify a fake <code>HttpBrowserCapabilities</code> object to get slightly further:</p> <pre><code>Subtext.TestLibrary.HttpSimulator simulator = new HttpSimulator(); simulator.SimulateRequest(); var browserMock = new Mock&lt;HttpBrowserCapabilities&gt;(); browserMock.Expect(b =&gt; b.PreferredRenderingMime).Returns("text/html"); browserMock.Expect(b =&gt; b.PreferredResponseEncoding).Returns("UTF-8"); browserMock.Expect(b =&gt; b.PreferredRequestEncoding).Returns("UTF-8"); HttpContext.Current.Request.Browser = browserMock.Object; </code></pre> <p>Now I get exceptions on property accesses on that object. I mocked as many as I could, but seemed to be getting nowhere fast. </p> <p>Has anyone managed to make this work?</p>
<p>Unfortunately, the ASP.NET viewengine uses the VirtualPathProvider in the ASP.NET hosting environment. To make matters worse, I traced some of the other code using Reflector and found that there is other dependencies to some hardcode references to VirtualPath utilities. I hope they fix this in the release so we can truly test our Views and how they are rendered.</p>
<p>These are the values that need to be set in the HttpBrowserCapabilities object for a asp.net webforms site to run, I would try making sure these are set and see if that fixes your problem, I'm not sure if it would but hey it worth a shot right?</p> <ul> <li>Browser (aka name)</li> <li>useragent (passed in the request)</li> <li>tables (true/false)</li> <li>version (version of browser eg 1.0)</li> <li>w3cdomversion (eg 1.0)</li> <li>cookies (true/false)</li> <li>ecmascriptversion (eg 1.0)</li> </ul> <p>Hope this helps.</p>
28,368
<p>I want have to have a single imageList used by multiple forms in a project. That is to say, multiple controls use the same image list.</p> <p><em>Note: Ideally multiple projects in a single solution will use the same image list - but I don't want to ask too much of Microsoft at once.</em></p> <p>Some controls are listview, some are treeviews, some are custom controls, some are controls that do custom paint cycles.</p> <p>How can I point multiple ListViews and TreeViews to the same image list component?</p> <p>Some of the issues involved are:</p> <ul> <li>Where do I put the image list component? It has to sit on some sort of form</li> <li>How do I convince the IDE to show imagelist controls in the "SmallImageList" that are on different forms as the listview?</li> <li>If I instead construct the imagelist at runtime, how do I design the images that appear in the image list?</li> </ul> <p><strong>Note:</strong> This was easy in Delphi. You'd drop an ImageList component as you normally do, and it just appeared in the list of available image lists under the "SmallImageList" property in the Properties window.</p> <p><strong>Note:</strong> It's okay to say that it can't be done in Visual Studio. If the answer is that it cannot be done then that will be the accepted answer.</p>
<p>As for the principal question:</p> <blockquote> <p>.NET Windows Forms 2.0: How to have a shared imagelist?</p> </blockquote> <p>You can share the ImageList with a UserControl. Just add the UserControl in all your form and you will be able to access the ImageList.</p>
<p>I fired up Visual Studio and thought "lets make a enhanced ImageList control that inherits from the imagelist and fix this and post a solution on SO" and was let down with a bang, the ImageList control is sealed (noninheritable) so I got stuck before I even started. </p> <p>But I remembered that somwhere someone had done this allready and google did the trick after a bit of tweaking of the keywords.</p> <p>I found a solution on CodeProject, where <strong>Neal Andrews</strong> seems to have made exactly what you want, make a ImageLists to be inherited and shared globaly across multiple forms and controls, with full design time support.</p> <p><a href="http://www.codeproject.com/KB/cpp/SharedImageListsComponent.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cpp/SharedImageListsComponent.aspx</a></p> <p>Thanks Neal!</p>
43,048
<p>I need to specify a date value in a sybase where clause. For example:</p> <pre><code>select * from data where dateVal &lt; [THE DATE] </code></pre>
<p>Use the convert function, for example:</p> <pre><code>select * from data where dateVal &lt; convert(datetime, '01/01/2008', 103) </code></pre> <p>Where the convert style (103) determines the date format to use.</p>
<p>102 is the rule of thumb, convert (varchar, creat_tms, 102) > '2011'</p>
8,018
<p>I have an animation and I want it to play it just only once. From where can I set so when I export to SWF the default will be AUTO LOOPING disabled.</p> <p>Thanks</p>
<p>Insert a keyframe in the last frame and put a stop(); there? </p>
<p>Please following code</p> <pre><code>&lt;param name='loop' value='false' /&gt; &lt;object type='application/x-shockwave-flash' data='sourcefile' width='300' height='120' loop='false'&gt; </code></pre> <p>This works perfectly</p>
47,082
<p>I'm currently doing the following to use typed datasets in vs2008: </p> <p>Right click on "app_code" add new dataset, name it tableDS.</p> <p>Open tableDS, right click, add "table adapter"</p> <p>In the wizard, choose a pre defined connection string, "use SQL statements"</p> <p>select * from tablename and next + next to finish. (I generate one table adapter for each table in my DB)</p> <p>In my code I do the following to get a row of data when I only need one: </p> <p>cpcDS.tbl_cpcRow tr = (cpcDS.tbl_cpcRow)(new cpcDSTableAdapters.tbl_cpcTableAdapter()).GetData().Select("cpcID = " + cpcID)[0];</p> <p>I believe this will get the entire table from the database and to the filtering in dotnet (ie not optimal), is there any way I can get the tableadapter to filer the result set on the database instead (IE what I want to is send select * from tbl_cpc where cpcID = 1 to the database)</p> <p>And as a side note, I think this is a fairly ok design pattern for getting data from a database in vs2008. It's fairly easy to code with, read and mantain. But I would like to know it there are any other design patterns that is better out there? I use the datasets for read/update/insert and delete. </p>
<p>A bit of a shift, but you ask about different patterns - how about LINQ? Since you are using VS2008, it is possible (although not guaranteed) that you might also be able to use .NET 3.5.</p> <p>A LINQ-to-SQL data-context provides much more managed access to data (filtered, etc). Is this an option? I'm not sure I'd go "Entity Framework" at the moment, though (<a href="https://stackoverflow.com/questions/276433/do-you-think-its-advantageous-to-switch-to-entity-framework#276439">see here</a>).</p> <p>Edit per request:</p> <p>to get a row from the data-context, you simply need to specify the "predicate" - in this case, a primary key match:</p> <pre><code>int id = ... // the primary key we want to look for using(var ctx = new MydataContext()) { SomeType record = ctx.SomeTable.Single(x =&gt; x.SomeColumn == id); //... etc // ctx.SubmitChanges(); // to commit any updates } </code></pre> <p>The use of Single above is deliberate - this particular usage [Single(predicate)] allows the data-context to make full use of local in-memory data - i.e. if the predicate is just on the primary key columns, it might not have to touch the database at all if the data-context has already seen that record.</p> <p>However, LINQ is very flexible; you can also use "query syntax" - for example, a slightly different (list) query:</p> <pre><code> var myOrders = from row in ctx.Orders where row.CustomerID = id &amp;&amp; row.IsActive orderby row.OrderDate select row; </code></pre> <p>etc </p>
<p>You can add a query with a where clause to the tableadapter for the table you're interested in.</p> <p>LINQ is nice, but it's really just shortcut syntax for what the OP is already doing.</p> <p>Typed Datasets make perfect sense unless your data model is very complex. Then writing your own ORM would be the best choice. I'm a little confused as to why Andreas thinks typed datasets are hard to maintain. The only annoying thing about them is that the insert, update, and delete commands are removed whenever the select command is changed.</p> <p>Also, the speed advantage of creating a typed dataset versus your own ORM lets you focus on the app itself and not the data access code.</p>
37,731
<p>How can I insert ASCII special characters (e.g. with the ASCII value 0x01) into a string?</p> <p>I ask because I am using the following:</p> <pre><code>str.Replace( "&lt;TAG1&gt;", Convert.ToChar(0x01).ToString() ); </code></pre> <p>and I feel that there must be a better way than this. Any Ideas?</p> <p>Update:</p> <p>Also If I use this methodology, do I need to worry about unicode &amp; ASCII clashing?</p>
<p>I believe you can use <code>\uXXXX</code> to insert specified codes into your string.</p> <p>ETA: I just tested it and it works. :-)</p> <pre><code>using System; class Uxxxx { public static void Main() { Console.WriteLine("\u20AC"); } } </code></pre>
<blockquote> <p>Also If I use this methodology, do I need to worry about unicode &amp; ASCII clashing?</p> </blockquote> <p>Your first problem will be your tags clashing with ASCII. Once you get to TAG10, you will clash with 0x0A: line feed. If you ensure that you will never get more than nine tags, you should be safe. Unicode-encoding (or rather: UTF8) is identical to ASCII-encoding when the byte-values are between 0 and 127. They only differ when the top-bit is set. </p>
12,548
<p>Our customer would like to know <strong>who</strong> is online and currently using the custom application we wrote for them. I discussed it with them and this does not need to be <strong>exact</strong>, more of a guestimate will work. </p> <p>So my thought is a 15 minute time interval to determine user activity. Some ideas I have for doing this are as follows:</p> <ol> <li><p>Stamp their user record with a date and time of their last activity every time they do something that hits the database, or requests a web page ... this though could be quite database intensive.</p></li> <li><p>Send out a "who is online request" from our software, looking for responses, this could be done at a scheduled interval, and then stamp the user record with the current date and time for each response I received.</p></li> </ol> <p>What are your thoughts? And how would you handle this situation?</p> <p><strong>Clarification</strong></p> <p>I would like to use the same architecture for both Windows or the Web if possible. I have a single business logic layer that multiple user interfaces interact with, could be Windows or the Web.</p> <p>By Windows I would mean client-server.</p> <p><strong>Clarification</strong></p> <p>I am using an n-tier architecture so my business objects handle all the interaction with the presentation layer. That presentation layer could be feeding a client-server Windows application, Web application, Web Service and so on. </p> <p>It is not a high traffic application, as it was developed for a customer of ours, maybe 100 users at most.</p>
<p>Our solution is to maintain a "Transaction" table (which follows what was done), in addition to our "Session" table (which follows who was here). UPDATE, INSERT and DELETE instructions are all managed through a "Transaction" object and each of these SQL instruction is stored in the "Transaction" table once it has been successfully executed on the database (depending on tables updated: we have the possibility to specifically follow some tables and ignore others). This "Transaction" table has other fields such as transactiontType (I for INSERT, D for DELETE, U for UPDATE), transactionDateTime, etc, and a foreign key "sessionId", telling us finally who sent the instruction. It is even possible, through some code, to identify who did what and when (Gus created the record on monday, Tim changed the Unit Price on tuesday, Liz added an extra discount on thursday, etc).</p> <p>Pros for this solution are:</p> <ol> <li>you're able to tell "what who and when", and to show it to your users! (you'll need some code to analyse SQL statements)</li> <li>if your data is replicated, and replication fails, you can rebuild your database through this table</li> </ol> <p>Cons are</p> <ol> <li>100 000 data updates per month mean 100 000 records in Tbl_Transaction</li> <li>Finally, this table tends to be 99% of your database volume</li> </ol> <p>Our choice: all records older than 90 days are automatically deleted every morning</p>
<p>I'd just drop a log record table in the db. </p> <p>UserId int FK<br> Action char(3) ('in' or 'out')<br> Time DateTime </p> <p>You can drop a new record in the table when somebody logs in or out or alternatively update the last record for the user.</p>
20,995
<p>Does anyone know of a whirlwind tour of Eclipse that would help a (former) Visual Studio user get up to speed with it?</p> <p>I just want something that tells me where all the basic features are and what all the cool stuff I've heard so much about is?</p> <p>So far I've been using it mostly as a text editor and have had some luck compiling and running programs in it. But... I'm a bit confused, for instance sometimes I can't seem to get out of debug mode.</p> <p>I'me sure I'm just looking in the wrong places for everything as I'm used to a different interface.</p> <p>Are there plugins for Eclipse that make it look and feel more like Visual Studio?</p> <p>I'm using Europa at the moment because thats what the rest of my team use, howver I'm more than happy to migrate to Ganemede...</p>
<p>Is the problem in an executable or a DLL?</p> <p>If it's a DLL what is its preferred load address? If this clashes with any other DLL then it will be rebased by the loader, and this can lead to what you're seeing. </p> <p>As part of your build process, you should ensure that all your DLLs are rebased (there's a tool to do this) so that their address spaces don't clash (this frees up some page file space as well as improving load time).</p>
<p>When you are in the debugger and stepping into the code, can you check if the code address is within the range that you see in the "Modules" window? Sometimes the same piece of code may exist in several modules of same / different names.</p> <p>Once you identify the "Module" which contains the code, use the base address from the Modules window to arrive at (by subtracting) the DLL entry point address.</p> <p>Finally, there is also the effect of entry jump tables (trampoline), which is a kind of function call indirection that can be added at compile time or at runtime. Thus, the "entry point" address may be a smoke screen and doesn't match the address for the function body.</p> <p>(My understanding of DLL structure is limited, so there may be inaccuracies in my answer.)</p>
21,985
<p>Ever wanted to have an HTML drag and drop sortable table in which you could sort both rows and columns? I know it's something I'd die for. There's a lot of sortable lists going around but finding a sortable table seems to be impossible to find. </p> <p>I know that you can get pretty close with the tools that script.aculo.us provides but I ran into some cross-browser issues with them. </p>
<p>I've used jQuery UI's sortable plugin with good results. Markup similar to this:</p> <pre><code>&lt;table id="myTable"&gt; &lt;thead&gt; &lt;tr&gt;&lt;th&gt;ID&lt;/th&gt;&lt;th&gt;Name&lt;/th&gt;&lt;th&gt;Details&lt;/th&gt;&lt;/tr&gt; &lt;/thead&gt; &lt;tbody class="sort"&gt; &lt;tr id="1"&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;Name1&lt;/td&gt;&lt;td&gt;Details1&lt;/td&gt;&lt;/tr&gt; &lt;tr id="2"&gt;&lt;td&gt;2&lt;/td&gt;&lt;td&gt;Name1&lt;/td&gt;&lt;td&gt;Details2&lt;/td&gt;&lt;/tr&gt; &lt;tr id="3"&gt;&lt;td&gt;3&lt;/td&gt;&lt;td&gt;Name1&lt;/td&gt;&lt;td&gt;Details3&lt;/td&gt;&lt;/tr&gt; &lt;tr id="4"&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;Name1&lt;/td&gt;&lt;td&gt;Details4&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>and then in the javascript</p> <pre><code>$('.sort').sortable({ cursor: 'move', axis: 'y', update: function(e, ui) { href = '/myReorderFunctionURL/'; $(this).sortable("refresh"); sorted = $(this).sortable("serialize", 'id'); $.ajax({ type: 'POST', url: href, data: sorted, success: function(msg) { //do something with the sorted data } }); } }); </code></pre> <p>This POSTs a serialized version of the items' IDs to the URL given. This function (PHP in my case) then updates the items' orders in the database.</p>
<p>How about <a href="http://www.kryogenix.org/code/browser/sorttable/" rel="nofollow noreferrer">sorttable</a>? That would seem to fit your requirements nicely.</p> <p>It's rather easy to use - load the sorttable Javascript file, then, for each table you want it to make sortable, apply class="sortable" to the &lt;table&gt; tag.</p> <p>It will immediately understand how to sort most types of data, but if there's something it doesn't, you can add a custom sort key to tell it how to sort. The documentation explains it all pretty well.</p>
10,794
<p>I am trying to log a method's parameters by using reflection. I read the <a href="https://stackoverflow.com/questions/168396/capturing-method-state-using-reflection">earlier question</a> posted about this issue on StackOverflow as well which pointed me to CLR API's. </p> <p>Is it possible, someone can point me to the right direction, as to how will I get the values of parameters passed using API? </p>
<p>Basically you can't in "vanilla" .NET code. Parameters are just local variables, and their values can't be fetched without delving into the debugger API mentioned in the other thread.</p> <p>What you <em>may</em> be able to do is use <a href="http://www.sharpcrafters.com/solutions/logging" rel="nofollow noreferrer">PostSharp</a> to insert the logging code. I'd suggest going that route before looking at the debugging API!</p>
<p>@ Sean: This seems promising, Is it possible to intercept and get values like that in WCF? I know the service log already contains that information but it is difficult to dig through it which makes me look for alternative ways to log methods and their parameters. </p>
22,782
<p>I have an algorithm that generates strings based on a list of input words. How do I separate only the strings that sounds like English words? ie. discard <strong>RDLO</strong> while keeping <strong>LORD</strong>.</p> <p><strong>EDIT:</strong> To clarify, they do not need to be actual words in the dictionary. They just need to sound like English. For example <strong>KEAL</strong> would be accepted.</p>
<p>You can build a markov-chain of a huge english text.</p> <p>Afterwards you can feed words into the markov chain and check how high the probability is that the word is english.</p> <p>See here: <a href="http://en.wikipedia.org/wiki/Markov_chain" rel="noreferrer">http://en.wikipedia.org/wiki/Markov_chain</a> </p> <p>At the bottom of the page you can see the markov text generator. What you want is exactly the reverse of it. </p> <p>In a nutshell: The markov-chain stores for each character the probabilities of which next character will follow. You can extend this idea to two or three characters if you have enough memory.</p>
<p>I'd suggest a few simple rules and standard pairs and triplets would be good.</p> <p>For example, english sounding words tend to follow the pattern of vowel-consonant-vowel, apart from some dipthongs and standard consonant pairs (e.g. th, ie and ei, oo, tr). With a system like that you should strip out almost all words that don't sound like they could be english. You'd find on closer inspection that you will probably strip out a lot of words that do sound like english as well, but you can then start adding rules that allow for a wider range of words and 'train' your algorithm manually.</p> <p>You won't remove all false negatives (e.g. I don't think you could manage to come up with a rule to include 'rythm' without explicitly coding in that rythm is a word) but it will provide a method of filtering.</p> <p>I'm also assuming that you want strings that could be english words (they sound reasonable when pronounced) rather than strings that are definitely words with an english meaning.</p>
11,749
<p>I've got an NSColor, and I really want the 32-bit RGBA value that it represents. Is there any easy way to get this, besides extracting the float components, then multiplying and ORing and generally doing gross, endian-dependent things?</p> <p>Edit: Thanks for the help. Really, what I was hoping for was a Cocoa function that already did this, but I'm cool with doing it myself.</p>
<p>Another more brute force approach would be to create a temporary CGBitmapContext and fill with the color. </p> <pre><code>NSColor *someColor = {whatever}; uint8_t data[4]; CGContextRef ctx = CGBitmapContextCreate((void*)data, 1, 1, 8, 4, colorSpace, kCGImageAlphaFirst | kCGBitmapByteOrder32Big); CGContextSetRGBFillColor(ctx, [someColor redComponent], [someColor greenComponent], [someColor blueComponent], [someColor alphaComponent]); CGContextFillRect(ctx, CGRectMake(0,0,1,1)); CGContextRelease(ctx); </code></pre> <p>FWIW, there are no endian issues with an 8 bit per component color value. Endianness is only with 16 bit or greater integers. You can lay out the memory any way you want, but the 8 bit integer values are the same whether a big endian or little endian machine. (ARGB is the default 8 bit format for Core Graphics and Core Image I believe).</p> <p>Why not just this?:</p> <pre><code>uint32_t r = (uint32_t)(MIN(1.0f, MAX(0.0f, [someColor redComponent])) * 255.0f); uint32_t g = (uint32_t)(MIN(1.0f, MAX(0.0f, [someColor greenComponent])) * 255.0f); uint32_t b = (uint32_t)(MIN(1.0f, MAX(0.0f, [someColor blueComponent])) * 255.0f); uint32_t a = (uint32_t)(MIN(1.0f, MAX(0.0f, [someColor alphaComponent])) * 255.0f); uint32_t value = (r &lt;&lt; 24) | (g &lt;&lt; 16) | (b &lt;&lt; 8) | a; </code></pre> <p>Then you know exactly how it is laid out in memory.</p> <p>Or this, if its more clear to you:</p> <pre><code>uint8_t r = (uint8_t)(MIN(1.0f, MAX(0.0f, [someColor redComponent])) * 255.0f); uint8_t g = (uint8_t)(MIN(1.0f, MAX(0.0f, [someColor greenComponent])) * 255.0f); uint8_t b = (uint8_t)(MIN(1.0f, MAX(0.0f, [someColor blueComponent])) * 255.0f); uint8_t a = (uint8_t)(MIN(1.0f, MAX(0.0f, [someColor alphaComponent])) * 255.0f); uint8_t data[4]; data[0] = r; data[1] = g; data[2] = b; data[3] = a; </code></pre>
<p>Converting the 4 floats to their integer representation, however you want to accomplish that, is the only way.</p>
41,726
<p>What are all the valid self-closing elements (e.g. &lt;br/&gt;) in XHTML (as implemented by the major browsers)?</p> <p>I know that XHTML technically allows any element to be self-closed, but I'm looking for a list of those elements supported by all major browsers. See <a href="http://dusan.fora.si/blog/self-closing-tags" rel="noreferrer">http://dusan.fora.si/blog/self-closing-tags</a> for examples of some problems caused by self-closing elements such as &lt;div /&gt;.</p>
<p>Every browser that supports XHTML (Firefox, Opera, Safari, <a href="https://learn.microsoft.com/en-us/archive/blogs/ie/xhtml-in-ie9" rel="noreferrer">IE9</a>) supports self-closing syntax on <strong>every element</strong>.</p> <p><code>&lt;div/&gt;</code>, <code>&lt;script/&gt;</code>, <code>&lt;br&gt;&lt;/br&gt;</code> all should work just fine. If they don't, then you have <em>HTML</em> with inappropriately added XHTML DOCTYPE.</p> <p><strong>DOCTYPE does not change how document is interpreted. <a href="http://www.webdevout.net/articles/beware-of-xhtml#content_type" rel="noreferrer">Only MIME type does</a></strong>.</p> <p><a href="https://lists.w3.org/Archives/Public/www-html/2000Sep/0024.html" rel="noreferrer">W3C decision about ignoring DOCTYPE</a>:</p> <blockquote> <p>The HTML WG has discussed this issue: the intention was to allow old (HTML-only) browsers to accept XHTML 1.0 documents by following the guidelines, and serving them as text/html. Therefore, documents served as text/html should be treated as HTML and not as XHTML.</p> </blockquote> <p>It's a very common pitfall, because W3C Validator largely ignores that rule, but browsers follow it religiously. Read <a href="https://webkit.org/blog/68/understanding-html-xml-and-xhtml/" rel="noreferrer">Understanding HTML, XML and XHTML</a> from WebKit blog:</p> <blockquote> <p>In fact, the vast majority of supposedly XHTML documents on the internet are served as <code>text/html</code>. Which means they are not XHTML at all, but actually invalid HTML that’s getting by on the error handling of HTML parsers. All those “Valid XHTML 1.0!” links on the web are really saying “Invalid HTML 4.01!”.</p> </blockquote> <hr /> <p>To test whether you have real XHTML or invalid HTML with XHTML's DOCTYPE, put this in your document:</p> <pre><code>&lt;span style=&quot;color:green&quot;&gt;&lt;span style=&quot;color:red&quot;/&gt; If it's red, it's HTML. Green is XHTML. &lt;/span&gt; </code></pre> <p>It validates, and in real XHTML it works perfectly (see: <a href="https://kornel.ski/1" rel="noreferrer">1</a> vs <a href="https://kornel.ski/2" rel="noreferrer">2</a>). If you can't believe your eyes (or don't know how to set MIME types), open your page via <a href="https://schneegans.de/xp/" rel="noreferrer">XHTML proxy</a>.</p> <p>Another way to check is view source in Firefox. It will highlight slashes in red when they're invalid.</p> <p>In HTML5/XHTML5 this hasn't changed, and the distinction is even clearer, because you don't even have additional <code>DOCTYPE</code>. <code>Content-Type</code> is the king.</p> <hr /> <p>For the record, the XHTML spec allows any element to be self-closing by making XHTML an <a href="https://www.w3.org/TR/REC-xml/#sec-starttags" rel="noreferrer">XML application</a>: [emphasis mine]</p> <blockquote> <p>Empty-element tags may be used for <strong>any element which has no content</strong>, whether or not it is declared using the keyword EMPTY.</p> </blockquote> <p>It's also explicitly shown in the <a href="https://www.w3.org/TR/xhtml1/#h-4.6" rel="noreferrer">XHTML spec</a>:</p> <blockquote> <p>Empty elements must <strong>either</strong> have an end tag or the start tag must end with <code>/&gt;</code>. For instance, <code>&lt;br/&gt;</code> or <code>&lt;hr&gt;&lt;/hr&gt;</code></p> </blockquote>
<p>&lt;hr /&gt; is another</p>
12,303
<p>In my Silverlight app I want a multi-line text box to expand every time the user hits Enter.</p> <p>The difficult part is how to calculate the correct height based on the number of text lines.</p> <p>I have tried the following but the textbox becomes too small:</p> <pre><code>box.Height = box.FontSize*lineCount + box.Padding.Top + box.Padding.Bottom + box.BorderThickness.Top + box.BorderThickness.Bottom; </code></pre> <p>What am I missing here? Or maybe it can be done automatically somehow?</p> <p>Thanks, Jacob</p> <p><strong>Edit:</strong> I suspect the problem to be in the FontSize property (does it use another size unit?)</p>
<p>This seems to be how the textbox works out of the box. Just make sure you set the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.acceptsreturn(VS.95).aspx" rel="nofollow noreferrer">AcceptsReturn</a>="True" on the textbox. Also make sure you don't set the height of the Textbox so that it is calculated for you.</p>
<p>The <code>TextBox</code> will fire a <code>SizeChanged</code> event, and it will also set the <code>ActualHeight</code> property. </p> <p>I don't think this was the case in Silverlight 2, when I had to use a <code>TextBlock</code> with the same font, set the padding to 4, and set the same text, and get the <code>ActualHeight</code> off that.</p>
33,739
<p>I'm evaluating Visual Studio productivity addons for my development team, which includes some folks who are very new to C# and some folks who are very experienced. We don't use VB.NET. I personally like ReSharper, but before I suggest something that I personally like, I would like some opinions for and reasoning behind using a different addon.</p> <p>Given the choice between ReSharper, CodeRush, and Visual Assist, which one did you choose and why? </p> <p>For discussion, do you run more than one addon at a time? Or one not on this list? What are your thoughts on these addons?</p>
<p>I downloaded both resharper and coderush trials. Initially I liked coderush a bit better. It seems a bit more polished and a bit more stable. But eventually I did go with resharper. Mainly because of the unit testing integration.</p> <p>I don't really see why you have to choose for your development team though. In my last company everyone used the tools they liked. We all used VS 2005 and 2008(depending on the project) and svn for versioning as long as everyone used the same coding standards we didn't have much problems. Standardizing is good up to a point but it might be a good idea to give your developers some choice in what tools they want to use.</p>
<p>I recommend ReSharper 4.0 with VS 2008. It really offers the best refactoring commands.</p> <p>ReSharper 4.0 has really been improved since it's beta. However, I heard that CodeRush had a better templating model. Personally, I rather have a powerful refactoring tool rather than a templating tool.</p> <p>I suggest ReSharper 4.0</p>
20,161
<p>What are the best practices when managing a software project involving a non-English-speaking client?</p> <p>What communication issues are relevant? Would you maintain documentation in both languages (especially updating the specifications regularly)?</p>
<p>My native language is not English, so I'm on the other side. There were times when we had to write project documents in 4-6 languages.</p> <p>Try to find somebody who understand English (like a key person). I try to avoid the communication in different languages on a project. Of course you can talk and write on different languages with project members, but if you talk or write to all members of the project at once, it should be one language.</p> <p>Documentation should be maintained in as many languages as many involved. All documents should be updated on a regular basis and try to avoid the situation when you have to tell them that "the English is the current one". Find someone who is native in the target language and translate from English for you. It will be far more better, understandable, and more native than if you try the other way around.</p>
<p>Always follow up with a written confirmation of any verbal discussion. Most people can read foreign languages better then they can speak them. It also helps to pick one language as the standard for all documents and code. </p>
25,034
<p>What are some suggestions for easy to use C++ compilers for a beginner? Free or open-source ones would be preferred.</p>
<p>GCC is a good choice for simple things.</p> <p>Visual Studio Express edition is the free version of the major windows C++ compiler.</p> <p>If you are on Windows I would use VS. If you are on linux you should use GCC.</p> <p>*I say GCC for simple things because for a more complicated project the build process isn't so easy</p>
<p>Visual Studio in command line behaves just like GCC. Just open the Visual Studio command line window and:</p> <p><code><pre> c:\temp> cl /nologo /EHsc /W4 foo.cpp c:\temp> dir /b foo.* foo.cpp &lt;-- your source file foo.obj &lt;-- result of compiling the cpp file foo.pdb &lt;-- debugging symbols (friendly names for debugging) foo.exe &lt;-- result of linking the obj with libraries </pre></code></p>
10,271
<p>We have, now, assertained that <em>inlined videos</em> (for want of a better description) are currently turned off (disabled) for SE 3D Printing, but can be turned on at any time, and there is no need to wait for the site to exit Beta, see <a href="https://3dprinting.meta.stackexchange.com/questions/226/is-the-inlining-videos-capability-turned-off-on-this-site">Is the &quot;inlining videos&quot; capability turned off on this site?</a></p> <p>The question now is, should we enable it?</p> <p>I have seen a few (2?) cases where the OP has linked to a video in order to succinctly describe their issue. As Ecnerwal points out in <a href="https://3dprinting.stackexchange.com/questions/4153/help-understanding-bridge-settings#answer-4157">their answer</a> to <a href="https://3dprinting.stackexchange.com/questions/4153/help-understanding-bridge-settings">Help understanding bridge settings</a>, watching videos, and in particular having to click on a link to watch them, can be somewhat onerous. Having the video inlined, <em>might</em> make it less so.</p> <p>BTW, I don't know what [backend or UX] disadvantages there would be to switching it on, although there are these <a href="http://3dprinting.meta.stackexchange.com/questions/226/is-the-inlining-videos-capability-turned-off-on-this-site#answer-400">cautionary tales</a>.</p>
<p>Per answer to <a href="https://meta.stackexchange.com/questions/296832/what-are-the-limitations-in-beta">What are the limitations in Beta</a></p> <p>"Inline videos is a feature that is off by default on all sites and only turned on if the community thinks it's necessary to improve the quality of a good portion of their question base." </p>
<p>A note of caution, <a href="https://stackoverflow.com/c/moderators/questions/257#answer-261">this post</a> on the Stack Moderators site, Pᴀᴜʟsᴛᴇʀ2's post, <a href="https://stackoverflow.com/c/moderators/questions/257">How do you request embedded video for your site?</a> - As mods can only follow these links I've included the content below:</p> <blockquote> <p>I don't know how exactly to request it, but I do want to point at one pretty big downside.</p> <p><strong>The player is pretty darn big.</strong> Plus, my experience is that it has a tendency to eat CPU cycles for breakfast.</p> <p>I looked at the numbers <a href="https://space.meta.stackexchange.com/questions/883/are-there-ways-to-make-posts-with-images-better-for-low-connect-speed-users-doe/885#comment3547_885">about a year ago over on Space Exploration Meta</a>. What I found was:</p> <blockquote> <p>Loading <a href="https://space.stackexchange.com/q/21891/415">https://space.stackexchange.com/q/21891/415</a> without using the browser cache downloads 7642 KB for me just now. Of that, <code>www.youtube.com</code> is responsible for 3182 KB and <code>i.stack.imgur.com</code> another 2729 KB. Excluding just the embedded images and the video-related downloads leaves about 1.7 MB to be downloaded. That's still a sizable chunk of data for what basically amounts to a few pages of text, but not quite as extreme as 7.6 MB.</p> </blockquote> <p>So one video embed adds about 3 MB download for everyone viewing the post, regardless of whether or not they are in any way interested in the video. (I think the video itself is downloaded on demand, so if someone actually watches the video, that adds even more data, but at that point at least they have some interest in it.) In situations where connections are metered by the megabyte, this can add up quickly, and is something that should be kept in mind before turning on this feature. Not everyone is on a fast, no-extra-charge-per-megabyte connection.</p> <p>(Yes, I'm big on keeping text as mostly text. I'm old-fashioned in that regard.)</p> </blockquote> <p>Also <a href="https://stackoverflow.com/c/moderators/questions/257#answer-260">this post</a>:</p> <blockquote> <blockquote> <p>Are there any downsides to having embedded video (performance or otherwise)?</p> </blockquote> <p>Yep, <a href="https://meta.stackexchange.com/a/279637/295232">performance could be an issue</a>. Also, malicious users could post links to videos with ... questionable ... content (though this could be alleviated by requiring some reputation to post embedded videos, just as some sites do with pictures).</p> </blockquote>
42
<p>In a C# .NET 3.5 app (a mix of WinForms and WPF) I want to let the user select a folder to import a load of data from. At the moment, it's using <code>System.Windows.Forms.FolderBrowserDialog</code> but that's a bit lame. Mainly because you can't type the path into it (so you need to map a network drive, instead of typing a UNC path).</p> <p>I'd like something more like the <code>System.Windows.Forms.OpenFileDialog</code>, but for folders instead of files. </p> <p>What can I use instead? A WinForms or WPF solution is fine, but I'd prefer not to PInvoke into the Windows API if I can avoid it.</p>
<p>Don't create it yourself! It's been done. You can use <a href="http://dotnetzip.codeplex.com/SourceControl/changeset/view/29832#432677" rel="nofollow noreferrer">FolderBrowserDialogEx</a> - a re-usable derivative of the built-in FolderBrowserDialog. This one allows you to type in a path, even a UNC path. You can also browse for computers or printers with it. Works just like the built-in FBD, but ... better. </p> <p>Full Source code. Free. MS-Public license.</p> <p><img src="https://i.stack.imgur.com/V1caf.png" alt="FolderBrowserDialogEx"></p> <p>Code to use it: </p> <pre><code>var dlg1 = new Ionic.Utils.FolderBrowserDialogEx(); dlg1.Description = "Select a folder to extract to:"; dlg1.ShowNewFolderButton = true; dlg1.ShowEditBox = true; //dlg1.NewStyle = false; dlg1.SelectedPath = txtExtractDirectory.Text; dlg1.ShowFullPathInEditBox = true; dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer; // Show the FolderBrowserDialog. DialogResult result = dlg1.ShowDialog(); if (result == DialogResult.OK) { txtExtractDirectory.Text = dlg1.SelectedPath; } </code></pre>
<p>So far, based on the lack of responses to <a href="https://stackoverflow.com/questions/31059/how-do-you-configure-an-openfiledialog-to-select-folders">my identical question</a>, I'd assume the answer is to roll your own dialog from scratch.</p> <p>I've seen things here and there about subclassing the common dialogs from VB6 and I think this might be part of the solution, but I've never seen anything about modifying what the dialog thinks it's selecting. It'd be possible through .NET via PInvoke and some other tricks, but I have yet to see code that does it.</p> <p>I <em>know</em> it's possible and it's not Vista-specific because Visual Studio has done it since VS 2003.</p> <p>Here's hoping someone answers either yours or mine!</p>
6,801
<p>For some reason, new projects set the version number of the assembly to 1.0.*, which then assigns what appears to be a random number once compiled.</p> <p>Why is this not set to 1.0.0.0 like all other projects.</p> <p>Thanks.</p>
<p>The numbers aren't random, though they can appear that way if you don't know how they're generated. I came across it a while ago:</p> <p>When a version is 1.0.d.s, "d" is the number of days since February 1, 2000 and "s" is the number of seconds since midnight/2.</p>
<p>I have noticed that some templates have different behaviors in regards to this. My guess is they want to make sure it increments by default.</p> <p>You can modify the template if you don't like the default setup.</p>
28,978
<p>I want to log in to Stack Overflow with Techorati OpenID hosted at my site.</p> <p><a href="https://stackoverflow.com/users/login">https://stackoverflow.com/users/login</a> has some basic information.</p> <p>I understood that I should change</p> <pre><code>&lt;link rel="openid.delegate" href="http://yourname.x.com" /&gt; </code></pre> <p>to</p> <pre><code>&lt;link rel="openid.delegate" href="http://technorati.com/people/technorati/USERNAME/" /&gt; </code></pre> <p>but if I change</p> <pre><code>&lt;link rel="openid.server" href="http://x.com/server" /&gt; </code></pre> <p>to</p> <pre><code>&lt;link rel="openid.server" href="http://technorati.com/server" /&gt; </code></pre> <p>or</p> <pre><code>&lt;link rel="openid.server" href="http://technorati.com/" /&gt; </code></pre> <p>it does not work.</p>
<p>when reimporting your keys from the old keyring, you need to specify the command:</p> <pre><code>gpg --allow-secret-key-import --import &lt;keyring&gt; </code></pre> <p>otherwise it will only import the public keys, not the private keys.</p>
<p>The resolution to this problem for me, was to notify the sender that he did use the Public key that I sent them but rather someone elses. You should see the key that they used. Tell them to use the correct one.</p>
11,677
<p>I'm looking for an open source search indexing library. It will be used for embedded web application so it should have a small code size. Preferably, written in C, C++ or PHP and does not require any database to be installed for storing indexes. Indexes should be stored on a file instead (e.g., xml, txt). I tried to look on some famous search libraries such as xapian and clucene, they're good but have a relatively large code size for an embedded system. </p> <p>This will be run on a Linux platform and will be used to index HTML files.</p> <p>Any thoughts on what would be a good search library/API to use?</p> <p>Thanks.</p>
<p><a href="http://hyperestraier.sourceforge.net/" rel="nofollow noreferrer">Hyper Estraier</a>.</p>
<p>First: you have to store indexes somewhere. So a data file will be needed unless you want memory only indexes.</p> <p>To index generic items, I can recommend you sqlite: <a href="http://www.sqlite.org/" rel="nofollow noreferrer">http://www.sqlite.org/</a>. I even use it in memory only mode when I have a bunch of data and I need to handle it with multiple indexes.</p>
11,595
<p>I have a Viewbox with <code>Stretch=Uniform</code> in order to not distort the content. However, when the frame window is wider or taller than the content, the Viewbox content is always centered.</p> <p>I cannot seem to find any content alignment options on the Viewbox. Is there a way to do this?</p>
<p>Try <code>VerticalAlignment="Top"</code> and <code>HorizontalAlignment="Left"</code> on your viewbox. It will cause it to be anchored to the top and left side.</p> <pre><code>&lt;Grid&gt; &lt;Viewbox VerticalAlignment="Top" HorizontalAlignment="Left"&gt; ... &lt;/Viewbox&gt; &lt;/Grid&gt; </code></pre> <p>If you want it to completely fill (but keep it uniform) you can use <code>Stretch="UniformToFill"</code></p>
<p>According to <a href="http://msdn.microsoft.com/en-us/library/ms741838.aspx" rel="nofollow noreferrer">MSDN</a> the Viewbox is used to stretch the child elements. Since the child elements would be stretched, you would have to set the content alignment of the children.</p> <p>You may want to look at this for more information on the Viewbox: <a href="https://stackoverflow.com/questions/288954/how-do-i-keep-aspect-ratio-on-scalable-scrollable-content-in-wpf">How do I keep aspect ratio on scalable, scrollable content in WPF?</a></p>
44,469
<p>Does PHP have a method of having auto-generated class variables? I <em>think</em> I've seen something like this before but I'm not certain.</p> <pre><code>public class TestClass { private $data = array(); public function TestClass() { $this-&gt;data['firstValue'] = "cheese"; } } </code></pre> <p>The <code>$this-&gt;data</code> array is always an associative array but they keys change from class to class. Is there any viable way to access <code>$this-&gt;data['firstValue']</code> from <code>$this-&gt;firstValue</code> without having to define the link?</p> <p>And if it is, are there any downsides to it?</p> <p>Or is there a static method of defining the link in a way which won't explode if the <code>$this-&gt;data</code> array doesn't contain that key?</p>
<p>See here: <a href="http://www.php.net/manual/en/language.oop5.overloading.php" rel="noreferrer">http://www.php.net/manual/en/language.oop5.overloading.php</a></p> <p>What you want is the "__get" method. There is an example for what you need on the link.</p>
<p>Use the PHP5 "magic" <code>__get()</code> method. It would work like so:</p> <pre><code>public class TestClass { private $data = array(); // Since you're using PHP5, you should be using PHP5 style constructors. public function __construct() { $this-&gt;data['firstValue'] = "cheese"; } /** * This is the magic get function. Any class variable you try to access from * outside the class that is not public will go through this method. The variable * name will be passed in to the $param parameter. For this example, all * will be retrieved from the private $data array. If the variable doesn't exist * in the array, then the method will return null. * * @param string $param Class variable name * * @return mixed */ public function __get($param) { if (isset($this-&gt;data[$param])) { return $this-&gt;data[$param]; } else { return null; } } /** * This is the "magic" isset method. It is very important to implement this * method when using __get to change or retrieve data members from private or * protected members. If it is not implemented, code that checks to see if a * particular variable has been set will fail even though you'll be able to * retrieve a value for that variable. * * @param string $param Variable name to check * * @return boolean */ public function __isset($param) { return isset($this-&gt;data[$param]); } /** * This method is required if you want to be able to set variables from outside * your class without providing explicit setter options. Similar to accessing * a variable using $foo = $object-&gt;firstValue, this method allows you to set * the value of a variable (any variable in this case, but it can be limited * by modifying this method) by doing something like: * $this-&gt;secondValue = 'foo'; * * @param string $param Class variable name to set * @param mixed $value Value to set * * @return null */ public function __set($param, $value) { $this-&gt;data[$param] = $value; } } </code></pre> <p>Using the magic <code>__get</code>, <code>__set</code>, and <code>__isset</code> constructors will allow you to control how you want variables to be set on a class while still storing all the values in a single array.</p> <p>Hope this helps :)</p>
12,685
<p>What is the best, preferably free/open source tool for auto-generating Java unit-tests? I know, the unit-tests cannot really serve the same purpose as normal TDD Unit-Tests which document and drive the design of the system. However auto-generated unit-tests can be useful if you have a huge legacy codebase and want to know whether the changes you are required to make will have unwanted, obscure side-effects.</p>
<p>Not free. Not opensource. But I have found AgitarOne Agitator (<a href="http://www.agitar.com/solutions/products/agitarone.html" rel="nofollow noreferrer">http://www.agitar.com/solutions/products/agitarone.html</a>) to be REALLY good for automatically generating unit tests AND looking for unwanted obscure side effects</p>
<p>To be honest, I probably wouldn't do this. Unit tests are isolated and you won't actually know if you have "unwanted, obscure side-effects" because everything is walled off from the other things that cause the side effects. As a result, you need integration or system testing and <em>that</em> is not something you can automate.</p> <p>Build a few high-level, end-to-end system tests which give you a degree of confidence and then use coverage testing to find out what you've missed, The downside is that when bugs crop up, it will be harder to point to their exact cause, but the upside is that you'll be far more likely to see the bugs.</p> <p>Once you find bugs, write unit tests just for them. As you move forward, you can use TDD for the bits you want to refactor.</p> <p>I know this probably wasn't the answer you want to hear, but I've been testing for many, many years and this is a solid approach (though I would hardly call it the only approach :)</p>
10,673
<p>Is there an easy method to store a person's user settings in a sql 2000 database. Ideally all settings in one field so I don't keep having to edit the table every time I add a setting. I am thinking along the lines of serialize a settings class if anyone has an example.</p> <p>The reason I don't want to use the built in .NET user settings stored in persistent storage is work uses super mandatory profiles so upon a users log off the settings are cleared which is a pain. I posted asking for any solutions to this previously but didn't get much of a response.</p>
<p>The VS designer keeps property settings in the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.aspx" rel="nofollow noreferrer">ApplicationSettingsBase</a> class. By default, these properties are serialized/deserialized into a per user XML file. You can override this behavior by using a custom <a href="http://msdn.microsoft.com/en-us/library/system.configuration.settingsprovider.aspx" rel="nofollow noreferrer">SettingsProvider</a> which is where you can add your database functionality. Just add the <code>SettingsProvider</code> attribute to the VS generated <code>Settings</code> class:</p> <pre><code>[SettingsProvider(typeof(CustomSettingsProvider))] internal sealed partial class Settings { ... } </code></pre> <p>A good example of this is the <a href="http://msdn.microsoft.com/en-us/library/ms181001.aspx" rel="nofollow noreferrer">RegistrySettingsProvider</a>.</p> <p>I answered another similar question the same way <a href="https://stackoverflow.com/questions/170825/how-to-serialize-systemconfigurationsettingsproperty#170932">here</a>.</p>
<p>First you need your table.</p> <pre><code>create table user_settings ( user_id nvarchar(256) not null, keyword nvarchar(64) not null, constraint PK_user_settings primary key (user_id, keyword), value nvarchar(max) not null ) </code></pre> <p>Then you can build your API:</p> <pre><code>public string GetUserSetting(string keyword, string defaultValue); public void SetUserSetting(string keyword, string value); </code></pre> <p>If you're already doing CRUD development (which I assume from the existence and availability of a database), then this should be trivially easy to implement.</p>
20,660
<p>I am trying to implement a custom "broken image" icon to appear if I cannot load an image. To accomplish this, I used the brokenImageSkin parameter, but it renders the image at its true resolution, which ends up cutting off the image if the size of the control is constrained.</p> <pre><code> &lt;mx:Image brokenImageSkin="@Embed('/assets/placeholder.png')" source="http://www.example.com/bad_url.png"/&gt; </code></pre> <p>How can I scale the brokenImageSkin to a custom width and height?</p>
<p>I see that in this example, <a href="http://blog.flexexamples.com/2008/03/02/setting-a-custom-broken-image-skin-for-the-image-control-in-flex/#more-538" rel="nofollow noreferrer">http://blog.flexexamples.com/2008/03/02/setting-a-custom-broken-image-skin-for-the-image-control-in-flex/#more-538</a>, there is an IO error event where you could set the width and height of the image.</p>
<ol> <li><p>Make a new class that extends ProgrammaticSkin. Embed your image using the [Embed] meta keyword and associate it with a variable of type Class (see the documentation for this)</p></li> <li><p>Override updateDisplaylist.</p></li> <li><p>Call graphics.clear() in this function.</p></li> <li><p>Call graphics.beginBitmapFill and then apply the appropriate dimensions and scaling based on the unscaledWidth and unscaledHeight passed in.</p></li> </ol> <p>This is way more complicated but it's the only way I know of to get more control out of a custom skinning operation like that.</p>
18,745
<p>Do not waste your time with this question. Follow up to: <a href="https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons">What is so bad about singletons?</a></p> <hr> <p><strike>Please feel free to bitch on <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">Singleton</a>.</strike></p> <p>Inappropriate usage of <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">Singleton</a> may cause lot of paint. What kind of problem do you experienced with singleton? What is common misuse of this pattern?</p> <hr> <p>After some digging into Corey's answer I discovered some greate articles on this topic.</p> <ul> <li><a href="http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial" rel="nofollow noreferrer">Why Singletons Are Controversial</a></li> <li><a href="http://scientificninja.com/advice/performant-singletons" rel="nofollow noreferrer">Performant Singletons</a></li> <li><a href="http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-join-new-project.html" rel="nofollow noreferrer">Singletons are Pathological Liars</a></li> <li><a href="http://googletesting.blogspot.com/2008/08/where-have-all-singletons-gone.html" rel="nofollow noreferrer">Where Have All the Singletons Gone?</a></li> <li><a href="http://googletesting.blogspot.com/2008/08/root-cause-of-singletons.html" rel="nofollow noreferrer">Root Cause of Singletons</a></li> </ul>
<p>There's nothing inherently wrong with the Singleton pattern. It is a tool and sometimes it should be used.</p>
<p>Most of the singleton patterns that I see written aren't written in a thread safe manner. If written correctly, they can be useful.</p>
11,219
<p>I am having a very strange problem. I have a very large regular expression searching for certain words in some text (RegEx looks something like this: <code>(?i)\b(a|b|c|d...)\b;</code> and so on where a, b, c, d, represent words). Anyway, I put it in a pre compiled assembly to speed things up a bit, however the problem is that pre compiled regex does not work the same way as a non compiled version of the same regex... o_0</p> <p>For example if the regex is: <code>(?i)\b(he|desk)\b</code> and I pass "helpdesk" through it the pre compiled version returns "lp" so the words he and desk gets striped out as if the boundary condition is not working at all, however if I do use exactly the same regular expression a non pre compiled version it works just fine... Does anyone know if I may be missing anything?</p> <p>Thanks</p> <p>(Sorry using VB.Net and C#)</p>
<p>Since you are searching for whole words, how about searching for <code>\w+</code>, and checking if the word is in a collection. A hash-based set or a hash-map would work well here. This approach would make it easier to update the list if the need should arise.</p>
<p>You've given two different languages there. So maybe there's some interaction.</p> <p>In any case I think some short but complete test programs might be in order - try and reproduce the problem in some independent test code to make it easier to reason about.</p> <p>Maybe it would be more efficient to do the search without regular expressions?</p>
47,279
<p>Sample code that shows how to create threads using MFC declares the thread function as both static and <code>__cdecl</code>. Why is the latter required? Boost threads don't bother with this convention, so is it just an anachronism?</p> <p>For example (MFC):</p> <pre><code>static __cdecl UINT MyFunc(LPVOID pParam) { ... } CWinThread* pThread = AfxBeginThread(MyFunc, ...); </code></pre> <p>Whereas Boost:</p> <pre><code>static void func() { ... } boost::thread t; t.create(&amp;func); </code></pre> <p>(the code samples might not be 100% correct as I am nowhere near an IDE).</p> <p>What is the point of __cdecl? How does it help when creating threads?</p>
<p>__cdecl tells the compiler to use the C calling convention (as opposed to the stdcall, fastcall or whatever other calling convention your compiler supports). I believe, VC++ uses stdcall by default.</p> <p>The calling convention affects things such as how arguments are pushed onto the stack (or registers, in the case of fastcall) and who pops arguments off the stack (caller or callee).</p> <p>In the case of Boost. I believe it uses template specialization to figure out the appropriate function type and calling convention.</p>
<p>Because your thread is going to be called by a runtime function that manages this for you, and that function expects it to be that way. Boost designed it a different way.</p> <p>Put a breakpoint at the start of your thread function and look at the stack when it gets called, you'll see the runtime function that calls you.</p>
20,557
<p>I need to load some fonts temporarily in my program. Preferably from a dll resource file.</p>
<p>And here a Delphi version:</p> <pre><code>procedure LoadFontFromDll(const DllName, FontName: PWideChar); var DllHandle: HMODULE; ResHandle: HRSRC; ResSize, NbFontAdded: Cardinal; ResAddr: HGLOBAL; begin DllHandle := LoadLibrary(DllName); if DllHandle = 0 then RaiseLastOSError; ResHandle := FindResource(DllHandle, FontName, RT_FONT); if ResHandle = 0 then RaiseLastOSError; ResAddr := LoadResource(DllHandle, ResHandle); if ResAddr = 0 then RaiseLastOSError; ResSize := SizeOfResource(DllHandle, ResHandle); if ResSize = 0 then RaiseLastOSError; if 0 = AddFontMemResourceEx(Pointer(ResAddr), ResSize, nil, @NbFontAdded) then RaiseLastOSError; end; </code></pre> <p>to be used like:</p> <pre><code>var FontName: PChar; FontHandle: THandle; ... FontName := 'DEJAVUSANS'; LoadFontFromDll('Project1.dll' , FontName); FontHandle := CreateFont(0, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, FontName); if FontHandle = 0 then RaiseLastOSError; </code></pre>
<p>Here's some code that will load/make available the font from inside your executable (ie, the font was embedded as a resource, rather than something you had to install into Windows generally). </p> <p>Note that the font is available to <em>any</em> application until your program gets rid of it. I don't know how useful you'll find this, but I have used it a few times. I've never put the font into a dll (I prefer this 'embed into the exe' approach) but don't imagine it changes things too much.</p> <pre>procedure TForm1.FormCreate(Sender: TObject); var ResStream : TResourceStream; sFileName : string; begin sFileName:=ExtractFilePath(Application.ExeName)+'SWISFONT.TTF'; ResStream:=nil; try ResStream:=TResourceStream.Create(hInstance, 'Swisfont', RT_RCDATA); try ResStream.SaveToFile(sFileName); except on E:EFCreateError Do ShowMessage(E.Message); end; finally ResStream.Free; end; AddFontResource(PChar(sFileName)); SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0); end; procedure TForm1.FormDestroy(Sender: TObject); var sFile:string; begin sFile:=ExtractFilePath(Application.ExeName)+'SWISFONT.TTF'; if FileExists(sFile) then begin RemoveFontResource(PChar(sFile)); SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0); DeleteFile(sFile); end; end; </pre>
13,305
<p>I'm fairly new to WPF and I've come across a problem that seems a bit tricky to solve. Basically I want a 4x4 grid thats scalable but keeps a square (or any other arbitrary) aspect ratio. This actually seems quite tricky to do, which surprises me because I would imagine its a reasonably common requirement.</p> <p>I start with a Grid definition like this:</p> <pre><code>&lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinition&gt; ... &lt;/Grid&gt; </code></pre> <p>Now if you set that to stretch, it can fill the Window or whatever container you put it in. The rows and column are uniform but the aspect ratio isn't fixed.</p> <p>Then I tried putting it in a StackPanel to use the available space. Didn't help. What did get me most of the way there was when I remembered Viewboxes.</p> <pre><code>&lt;StackPanel Orientation="Horizontal"&gt; &lt;Viewbox&gt; &lt;Grid Height="1000" Width="1000"&gt; &lt;!-- this locks aspect ratio --&gt; &lt;Grid.RowDefinitions&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinition&gt; ... &lt;/Grid&gt; &lt;/viewbox&gt; &lt;Label HorizontalAlignment="Stretch"&gt;Extra Space&lt;/Label&gt; &lt;/StackPanel&gt; </code></pre> <p>Now my content scales and keeps aspect ratio. The problem is that if the window isn't wide enough some of my grid is off the screen. I'd like to be able to scroll to it if that were the case. Likewise, I might need a minimum size, which might lead to vertical scrolling too.</p> <p>Now I've tried putting my StackPanel and Grid (separately) in an appropriate ScrollViewer container but then the content no longer scales to fit the window. It goes to full size, which is no good.</p> <p>So how do I go about doing this? Am I barking up the wrong tree? Is there a better/easier way of doing this?</p>
<p>You need to put the content (the grid) inside a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.viewbox.aspx" rel="noreferrer">Viewbox</a> and set the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.viewbox.stretch.aspx" rel="noreferrer">Viewbox.Stretch Property</a> to <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.stretch.aspx" rel="noreferrer">Stretch.Uniform</a></p> <p>The Viewbox control is used to stretch or scale a child element and lets you control the way the child is stretched. Check the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.stretch.aspx" rel="noreferrer">examples</a> here.</p> <p><a href="https://i.stack.imgur.com/5sBYY.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/5sBYY.jpg" alt="alt text" /></a><br /> <sub>(source: <a href="http://i.msdn.microsoft.com/ms635549.img_mmgraphics_stretchenum(en-us,VS.90).jpg" rel="noreferrer">microsoft.com</a>)</sub></p>
<p>put 0.25* instead of * for each Column and RowWidth</p>
36,785
<p>In my model I have:</p> <pre><code>validate :my_custom_validation def my_custom_validation errors.add_to_base("error message") if condition.exists? end </code></pre> <p>I would like to add some parameters to mycustomer vaildation like so:</p> <pre><code>validate :my_custom_validation, :parameter1 =&gt; x, :parameter2 =&gt; y </code></pre> <p>How do I write the mycustomvalidation function to account for parameters? </p>
<p>Validators usualy have an array parameter indicating, first, the fields to validate and lastly (if it exists) a hash with the options. In your example:</p> <pre><code>:my_custom_validation, parameter1: x, parameter2: y </code></pre> <p>:my_custom_validation would be a field name, while parameter1: x, parameter2: y would be a hash:</p> <pre><code>{ parameter1: x, parameter2: y} </code></pre> <p>Therefore, you'd do something like:</p> <pre><code>def my_custom_validation(*attr) options = attr.pop if attr.last.is_a? Hash # do something with options errors.add_to_base("error message") if condition.exists? end </code></pre>
<p>You should also be able to use a <a href="https://www.geeksforgeeks.org/lambda-function-ruby/" rel="nofollow noreferrer">Ruby lambda</a> to help with method based validation of your model attributes (x, y) like below:</p> <pre><code>validate -&gt; { my_custom_validation(parameter1: x, parameter2: y) } </code></pre>
13,172
<p>I'm familiar with the issue behind ORA-01775: looping chain of synonyms, but is there any trick to debugging it, or do I just have to "create or replace" my way out of it? </p> <p>Is there a way to query the schema or whatever to find out what the current definition of a public synonym is? </p> <p>Even more awesome would be a graphical tool, but at this point, anything would be helpful.</p>
<p>As it turns out, the problem wasn't actually a looping chain of synonyms, but the fact that the synonym was pointing to a view that did not exist.</p> <p>Oracle apparently errors out as a looping chain in this condition.</p>
<p><a href="http://ora-01775.ora-code.com/" rel="nofollow noreferrer">http://ora-01775.ora-code.com/</a> suggests:</p> <p><strong>ORA-01775</strong>: looping chain of synonyms<br> <em>Cause</em>: Through a series of CREATE synonym statements, a synonym was defined that referred to itself. For example, the following definitions are circular:<br> <code>CREATE SYNONYM s1 for s2 CREATE SYNONYM s2 for s3 CREATE SYNONYM s3 for s1</code><br> <em>Action</em>: Change one synonym definition so that it applies to a base table or view and retry the operation.</p>
30,683
<p>I have exceptions created for every condition that my application does not expect. <code>UserNameNotValidException</code>, <code>PasswordNotCorrectException</code> etc.</p> <p>However I was told I should not create exceptions for those conditions. In my UML those ARE exceptions to the main flow, so why should it not be an exception?</p> <p>Any guidance or best practices for creating exceptions?</p>
<p>My personal guideline is: an exception is thrown when a fundamental assumption of the current code block is found to be false.</p> <p>Example 1: say I have a function which is supposed to examine an arbitrary class and return true if that class inherits from List&lt;>. This function asks the question, "Is this object a descendant of List?" This function should never throw an exception, because there are no gray areas in its operation - every single class either does or does not inherit from List&lt;>, so the answer is always "yes" or "no".</p> <p>Example 2: say I have another function which examines a List&lt;> and returns true if its length is more than 50, and false if the length is less. This function asks the question, "Does this list have more than 50 items?" But this question makes an assumption - it assumes that the object it is given is a list. If I hand it a NULL, then that assumption is false. In that case, if the function returns <i>either</i> true <i>or</i> false, then it is breaking its own rules. The function cannot return <i>anything</i> and claim that it answered the question correctly. So it doesn't return - it throws an exception.</p> <p>This is comparable to the <a href="http://en.wikipedia.org/wiki/Fallacy_of_many_questions" rel="noreferrer">"loaded question"</a> logical fallacy. Every function asks a question. If the input it is given makes that question a fallacy, then throw an exception. This line is harder to draw with functions that return void, but the bottom line is: if the function's assumptions about its inputs are violated, it should throw an exception instead of returning normally.</p> <p>The other side of this equation is: if you find your functions throwing exceptions frequently, then you probably need to refine their assumptions.</p>
<p>The exceptions versus returning error code argument should be about flow control not philosophy (how "exceptional" an error is):</p> <pre><code>void f1() throws ExceptionType1, ExceptionType2 {} void catchFunction() { try{ while(someCondition){ try{ f1(); }catch(ExceptionType2 e2){ //do something, don't break the loop } } }catch(ExceptionType1 e1){ //break the loop, do something else } </code></pre> <p>}</p>
10,272
<p>We have a solution where we are picking the messages using Windows Service. </p> <p>The Windows Service fires every after 2 minutes and retrieves the MSMQ message to pass it to a Web Service.</p> <ol> <li>Can I create a WCF service which will automatically picks up the messages from MSMQ Queue?</li> <li>Can I avoid Windows Service by using WCF Service if it support auto invocation?</li> </ol>
<p>Q1: you can automatically pick up messages from MSMQ, you will need to look into the netmsmqbinding, there are some design considerations that you have to think about though, if you are used to the native MSMQ, you know that you have the ability to peek at the messages. But when you use WCF, you loose that ability to peek. WCF will intercept the messages in MSMQ and you are responsible for keeping your WCF service and the peeking app in synch. You will also need to look into whether you need transactional or non-transactional queues and you will have to modify your binding based on that.</p> <p>Q2: You will need to host the WCF service in windows service or in IIS7. if you host in IIS7 look into enabling MSMQ WAS listener</p> <p>Here is a nice article: <a href="http://blogs.msdn.com/tomholl/archive/2008/07/12/msmq-wcf-and-iis-getting-them-to-play-nice-part-1.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/tomholl/archive/2008/07/12/msmq-wcf-and-iis-getting-them-to-play-nice-part-1.aspx</a></p>
<p>One way to transfer messages from an MSMQ to a web service call is to use a netMsmqBinding service endpoint and a basicHttpBinding client endpoint that support the same contract. The netMsmq service will automatically grab messages from the queue and deserialize them into an object. In your implementation of your netMsmq service, just instantiate your basicHttp client proxy and just call the same method. Basically a pass-through or proxy pattern from the web-service to the MSMQ and vice-versa. In Juval Lowy's "Programming WCF" he calls this pattern the "HTTP Bridge" for queues.</p>
48,760
<p>I have only just set up my Anet A6 today. I am trying to print a calibration box, but the print is moving around the bed while trying to print. Any ideas how to fix this? The documentation is very vague.</p> <p>Basically I am very new to 3D printing. I purchased an Anet A6 and have set it up stock. I am trying to just print the box directly from the demo models on the SD card. I'm using the standard filament that comes with the printer. I'm not sure what type it is.</p> <p>All settings are default.</p>
<p>If the printed material moves with the nozzle, you might have several problems at hand, e.g.:</p> <ul> <li>adhesion, </li> <li>nozzle to bed distance and </li> <li>overall level.</li> </ul> <p>Nozzle to bed distance needs to be the thickness of a plain A4 or Letter paper. This needs to be at the same distance (when pulling the sheet of paper you need to feel a little drag) at the complete area of the bed. This is sometimes difficult as not all beds are perfectly flat from itself. Finally, you need to pull some tricks out of your sleeve to get the filament to adhere to the bed. Many example can be found, popular ones are using blue tape, glass bed, glue stick, PVA based spray (e.g. strong hairspray or dedicated spray cans like 3DLAC or Dimafix, etc.), or a combination of these. You just need to experiment some more what works best for you, but it is good to start with a correctly levelled bed with the proper nozzle gap. Sometimes, increasing the bed and filament temperature with 5&nbsp;&deg;C for the first layer also helps.</p>
<p>Chances are, you're not levelled close enough. try levelling your bed when it's heated around 60C (or as high as you can get if your machine's FW won't let it go that high) with a piece of standard printer paper. you should get a bit of resistance, and play around with the paper for a bit, find a happy medium. Try spreading glue stick on your bed, or spray it with hairspray. If you have BuildTak or some form of PEI, wipe it with some 99% rubbing alcohol. Lastly, find a fairly simple model on thingiverse.com or myminifactory.com, and slice it using either Raft or Skirt as build plate adhesion. I prefer a skirt because you can actively be checking how your bed levelling is, and adjust it. And make sure your first layer flow or extrusion multiplier is slightly higher is about 110-120%. This can get you good sticking almost every time.</p>
1,231
<p>I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:</p> <pre><code>/browse/&lt;name1&gt;/&lt;value1&gt;/&lt;name2&gt;/&lt;value2&gt;/ .... etc .... </code></pre> <p>where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match.</p> <p>Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs.</p> <p>Ideally each name/value pair will be passed to the view function as a parameter named <code>name1</code>, <code>name2</code>, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there?</p> <p>So, it seems I need to do something like this:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>... and got the same problem, but this time <code>*args</code> only includes the last matched pattern.</p> <p>Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.*) pattern?</p>
<p>A possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view. As an example:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?P&lt;match&gt;.+)/$', 'app.views.view', name='model_browse'), ) def view(request, match): pieces = match.split('/') # even indexed pieces are the names, odd are values ... </code></pre> <p>No promises about the regexp I used, but I think you understand what I mean.</p> <p>(Edited to try and fix the regexp.)</p>
<p>Same answer came to me while reading the question.</p> <p>I believe model_browse view is the best way to sort the query parameters and use it as a generic router.</p>
30,964
<p>I created a single page (with code behind .vb) and created Public intFileID As Integer</p> <p>in the Page load I check for the querystring and assign it if available or set intFileID = 0.</p> <pre><code>Public intFileID As Integer = 0 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then If Not Request.QueryString("fileid") Is Nothing Then intFileID = CInt(Request.QueryString("fileid")) End If If intFileID &gt; 0 Then GetFile(intFileID) End If End If End Sub Private Sub GetFile() 'uses intFileID to retrieve the specific record from database and set's the various textbox.text End Sub </code></pre> <p>There is a click event for the Submit button that inserts or updates a record based on the value of the intFileID variable. I need to be able to persist that value on postback for it all to work.</p> <p>The page simply inserts or updates a record in a SQL database. I'm not using a gridview,formview,detailsview, or any other rad type object which persists the key value by itself and I don't want to use any of them.</p> <p>How can I persist the value set in intFileID without creating something in the HTML which could possibly be changed.</p> <p><strong>[EDIT] Changed Page_Load to use ViewState to persist the intFileID value</strong></p> <pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then If Not Request.QueryString("fileid") Is Nothing Then intFileID = CInt(Request.QueryString("fileid")) End If If intFileID &gt; 0 Then GetFile(intFileID) End If ViewState("intFileID") = intFileID Else intFileID = ViewState("intFileID") End If End Sub </code></pre>
<p>As others have pointed out, you can store it in the Session or the ViewState. If it's page specific, I like to store it in the ViewState as opposed to the Session, but I don't know if one method is generally preferred over the other.</p> <p>In VB, you would store an item in the ViewState like:</p> <pre><code>ViewState(key) = value </code></pre> <p>And retrieve it like:</p> <pre><code>value = ViewState(key) </code></pre>
<p>I'll use Session as <a href="https://stackoverflow.com/questions/222999/how-to-persist-variable-on-postback/223006#223006">suggested by tvanfosson.</a> ViewState and HiddenField might be too heavy if you want to keep large data like a dataset for comments in a forum's topic pages..</p>
27,521
<p>I am using the WebBrowser control to add a WebInterface to C# app. My desire is to verify that only such app is able to connect to our Web server using SSL client certificates.</p> <p>My idea was to embed the client certificate in the app and just use when connecting via my app. Anybody have a sugestion on how to do this? Or the only way to make it work is to load the key in the X509Store.</p> <p>If I put it in X509Store, will it make my key available for general Internet Explorer Usage?</p>
<p>Are you sure this is what you want to do? If you embed the private key in your application (as your approach entails), an attacker can extract it and use it to authenticate their rogue software.</p> <p>A server cannot authenticate client software. It can only test whether a client possesses some secret. When you embed a private key in your client and distribute it, it will not be a secret anymore.</p> <p>I'd recommend authenticating <em>users</em> of your software, rather than the software itself. You need to let users generate their own secret, whether it is a password or a private key, and give them an incentive to protect it.</p>
<p>The intent of using the key is not so much to validate the users as to restrict access to users of the app instead of using any WebBrowser. This is sort of an intranet behavior over the public internet.</p> <p>This is a poor man's DRM. The losses due to people extracting the key are not that important. I think the risk of this happening is low and what we could loose is minimal. </p> <p>Nevertheless if there is any other idea to restrict access to the WebServer to only users of the App I am open for any suggestions. Basically my desire is now to have a public WebServer wide open to be read by anyone, but access over the public network from diverse places is necessary so setting up a intranet infrastructure is not possible either.</p>
12,188
<p>I would like to compare two dates in javascript. I have been doing some research, but all I can find is how to return the current date. I want to compare 2 separate dates, not related to today. How do I do that. </p> <pre><code>var startDate = Date(document.form1.Textbox2); </code></pre>
<pre><code>if (date1.getTime() &gt; date2.getTime()) { alert("The first date is after the second date!"); } </code></pre> <p><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date" rel="noreferrer">Reference to Date object</a></p>
<p>You could try adding the following script code to implement this:</p> <pre><code>if(CompareDates(smallDate,largeDate,'-') == 0) { alert('Selected date must be current date or previous date!'); return false; } function CompareDates(smallDate,largeDate,separator) { var smallDateArr = Array(); var largeDateArr = Array(); smallDateArr = smallDate.split(separator); largeDateArr = largeDate.split(separator); var smallDt = smallDateArr[0]; var smallMt = smallDateArr[1]; var smallYr = smallDateArr[2]; var largeDt = largeDateArr[0]; var largeMt = largeDateArr[1]; var largeYr = largeDateArr[2]; if(smallYr&gt;largeYr) return 0; else if(smallYr&lt;=largeYr &amp;&amp; smallMt&gt;largeMt) return 0; else if(smallYr&lt;=largeYr &amp;&amp; smallMt==largeMt &amp;&amp; smallDt&gt;largeDt) return 0; else return 1; } </code></pre>
43,934
<p>I would like to have two applications in my STM32 flash, one is basically a boot and the other the 'main' application. I have figured out how to load each of them into different areas of flash, and after taking a memory dump everything looks like it is in the right place.</p> <p>So when I do a reset it loads the boot, all the boot does at the moment is jump to the application. Debugging the boot, this all appears to work correctly. However the problems arrives after i've made the jump to the application, it just executes one instruction (assembly) and then jumps back to the boot. It should stay in the application indefinitely.</p> <p>My question is then, where should I 'jump' to in the app? </p> <p>It seems that there are a few potential spots, such as the interrupt vectors, the reset handler, the main function of the app. Actually I've tried all of those with no success.</p> <p>Hopefully that makes sense, i'll update the question if not.</p> <p>thanks for your help! Richard</p> <h2>Updates:</h2> <ul> <li>I had a play around in the debugger and manually changed the program counter to the main of the application, and well that worked a charm, so it makes me think there is something wrong with my jump, why doesn't the program counter keep going after the jump?</li> <li>Actually it seems to be the PSR, the 'T' gets reset on the jump, if I set that again after the jump it continues on with the app as I desire</li> <li>Ok found a solution, seems that you need to have the PC LSB set to 1 when you do a branch or it falls into the 'ARM' mode (32 bit instruction instead of 16 bit instructions like in the 'thumb' mode. Quite an obscure little problem, thanks for letting me share it with you! </li> </ul>
<p>Make sure you jump to an address where the LSB is 1. See this site for an explanation: <a href="https://www.embedded.com/introduction-to-arm-thumb/" rel="nofollow noreferrer">https://www.embedded.com/introduction-to-arm-thumb/</a></p>
<p>Richard,</p> <p>I was trying to do the same thing you succeeded at, but was having problems. I was using the IAR IDE and updated the *.icf file (in the "proj" directory) to put my application at 0x08002000 and loaded a separate project at 0x08000000 that just does a jump to the address at the reset vector at 0x08002004. The boot code started up and does seem to jump to the application start, but the application failed sometime during the IAR initialization, ending up at an ILLEGAL INSTRUCTION trap.</p> <p>After single-stepping through the application code, I found that I forgot to set the interrupt vector base address to that of the application's. It was still pointing to 0x08000000 and thus the code went insane. Adding a call to set the vector address before enabling any interrupts solved my problem and is required if you wish to have an application shifted in flash.</p> <p>Ira.</p>
26,586
<p>I'm currently working on a project which needs to persist any kind of object (of which implementation we don't have any control) so these objects could be recovered afterwards. </p> <p>We can't implement an ORM because we can't restrict the users of our library at development time.</p> <p>Our first alternative was to serialize it with the Java default serialization but we had a lot of trouble recovering the objects when the users started to pass different versions of the same object (attributes changed types, names, ...).</p> <p>We have tried with the XMLEncoder class (transforms an object into a XML), but we have found that there is a lack of functionality (doesn't support Enums for example). </p> <p>Finally, we also tried JAXB but this impose our users to annotate their classes.</p> <p>Any good alternative?</p>
<p>It's 2011, and in a commercial grade REST web services project we use the following serializers to offer clients a variety of media types:</p> <ul> <li><a href="http://x-stream.github.io/" rel="noreferrer">XStream</a> (for XML but not for JSON)</li> <li><a href="https://github.com/FasterXML/jackson" rel="noreferrer">Jackson</a> (for JSON)</li> <li><a href="https://github.com/EsotericSoftware/kryo" rel="noreferrer">Kryo</a> (a fast, compact binary serialization format)</li> <li><a href="https://github.com/FasterXML/jackson-dataformat-smile" rel="noreferrer">Smile</a> (a binary format that comes with Jackson 1.6 and later).</li> <li>Java Object Serialization.</li> </ul> <p>We experimented with other serializers recently:</p> <ul> <li><a href="http://simple.sourceforge.net/" rel="noreferrer">SimpleXML</a> seems solid, runs at 2x the speed of XStream, but requires a bit too much configuration for our situation.</li> <li><a href="http://code.google.com/p/yamlbeans/" rel="noreferrer">YamlBeans</a> had a couple of bugs.</li> <li><a href="http://code.google.com/p/snakeyaml/" rel="noreferrer">SnakeYAML</a> had a minor bug relating to dates.</li> </ul> <p>Jackson JSON, Kryo, and Jackson Smile were all significantly faster than good old Java Object Serialization, by about 3x to 4.5x. XStream is on the slow side. But these are all solid choices at this point. We'll keep monitoring the other three.</p>
<p>Another idea: Use cache. Caches provide much better control, scalability and robustness to the application. Still need to serialize, though, but the management becomes much easier with within a caching service framework. Cache can be persisted in memory, disk, database or array - or all of the options - with one being overflow, stand by, fail-over for the other . Commons JCS and Ehcache are two java implementations, the latter is an enterprise solution free up to 32 GB of storage (disclaimer: I don't work for ehcache ;-)). </p>
29,605
<p>Is it possible to disable the browsers vertical and horizontal scrollbars using jQuery or javascript?</p>
<p>In case you need possibility to hide and show scrollbars dynamically you could use</p> <pre><code>$("body").css("overflow", "hidden"); </code></pre> <p>and</p> <pre><code>$("body").css("overflow", "auto"); </code></pre> <p>somewhere in your code.</p>
<p>Because Firefox has an arrow key short cut, you probably want to put a <code>&lt;div&gt;</code> around it with CSS style: <code>overflow:hidden;</code>.</p>
30,034
<p>I would like to be able to define and use a custom type in some of my PowerShell scripts. For example, let's pretend I had a need for an object that had the following structure:</p> <pre><code>Contact { string First string Last string Phone } </code></pre> <p>How would I go about creating this so that I could use it in function like the following:</p> <pre><code>function PrintContact { param( [Contact]$contact ) "Customer Name is " + $contact.First + " " + $contact.Last "Customer Phone is " + $contact.Phone } </code></pre> <p>Is something like this possible, or even recommended in PowerShell?</p>
<h2>Prior to PowerShell 3</h2> <p>PowerShell's Extensible Type System didn't originally let you create concrete types you can test against the way you did in your parameter. If you don't need that test, you're fine with any of the other methods mentioned above. </p> <p>If you want an actual type that you can cast to or type-check with, as in your example script ... it <strong>cannot</strong> be done without writing it in C# or VB.net and compiling. In PowerShell 2, you can use the "Add-Type" command to do it quite simmple:</p> <pre><code>add-type @" public struct contact { public string First; public string Last; public string Phone; } "@ </code></pre> <p><strong><em>Historical Note</em></strong>: In PowerShell 1 it was even harder. You had to manually use CodeDom, there is a very old function <a href="http://poshcode.org/scripts/190" rel="noreferrer">new-struct</a> script on PoshCode.org which will help. Your example becomes:</p> <pre><code>New-Struct Contact @{ First=[string]; Last=[string]; Phone=[string]; } </code></pre> <p>Using <code>Add-Type</code> or <code>New-Struct</code> will let you actually test the class in your <code>param([Contact]$contact)</code> and make new ones using <code>$contact = new-object Contact</code> and so on...</p> <h1>In PowerShell 3</h1> <p>If you don't need a "real" class that you can cast to, you don't have to use the Add-Member way that <a href="https://stackoverflow.com/a/59980/8718">Steven and others have demonstrated</a> above.</p> <p>Since PowerShell 2 you could use the -Property parameter for New-Object:</p> <pre><code>$Contact = New-Object PSObject -Property @{ First=""; Last=""; Phone="" } </code></pre> <p>And in PowerShell 3, we got the ability to use the <code>PSCustomObject</code> accelerator to add a TypeName:</p> <pre><code>[PSCustomObject]@{ PSTypeName = "Contact" First = $First Last = $Last Phone = $Phone } </code></pre> <p>You're still only getting a single object, so you should make a <code>New-Contact</code> function to make sure that every object comes out the same, but you can now easily verify a parameter "is" one of those type by decorating a parameter with the <code>PSTypeName</code> attribute:</p> <pre><code>function PrintContact { param( [PSTypeName("Contact")]$contact ) "Customer Name is " + $contact.First + " " + $contact.Last "Customer Phone is " + $contact.Phone } </code></pre> <h1>In PowerShell 5</h1> <p>In PowerShell 5 everything changes, and we finally got <code>class</code> and <code>enum</code> as language keywords for defining types (there's no <code>struct</code> but that's ok):</p> <pre><code>class Contact { # Optionally, add attributes to prevent invalid values [ValidateNotNullOrEmpty()][string]$First [ValidateNotNullOrEmpty()][string]$Last [ValidateNotNullOrEmpty()][string]$Phone # optionally, have a constructor to # force properties to be set: Contact($First, $Last, $Phone) { $this.First = $First $this.Last = $Last $this.Phone = $Phone } } </code></pre> <p>We also got a new way to create objects without using <code>New-Object</code>: <code>[Contact]::new()</code> -- in fact, if you kept your class simple and don't define a constructor, you can create objects by casting a hashtable (although without a constructor, there would be no way to enforce that all properties must be set):</p> <pre><code>class Contact { # Optionally, add attributes to prevent invalid values [ValidateNotNullOrEmpty()][string]$First [ValidateNotNullOrEmpty()][string]$Last [ValidateNotNullOrEmpty()][string]$Phone } $C = [Contact]@{ First = "Joel" Last = "Bennett" } </code></pre>
<p>Here's one more option, which uses a similar idea to the PSTypeName solution mentioned by <a href="https://stackoverflow.com/a/66693/361842">Jaykul</a> (and thus also requires PSv3 or above).</p> <h1>Example</h1> <ol> <li>Create a <strong><em>TypeName</em>.Types.ps1xml</strong> file defining your type. E.g. <code>Person.Types.ps1xml</code>:</li> </ol> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;Types&gt; &lt;Type&gt; &lt;Name&gt;StackOverflow.Example.Person&lt;/Name&gt; &lt;Members&gt; &lt;ScriptMethod&gt; &lt;Name&gt;Initialize&lt;/Name&gt; &lt;Script&gt; Param ( [Parameter(Mandatory = $true)] [string]$GivenName , [Parameter(Mandatory = $true)] [string]$Surname ) $this | Add-Member -MemberType 'NoteProperty' -Name 'GivenName' -Value $GivenName $this | Add-Member -MemberType 'NoteProperty' -Name 'Surname' -Value $Surname &lt;/Script&gt; &lt;/ScriptMethod&gt; &lt;ScriptMethod&gt; &lt;Name&gt;SetGivenName&lt;/Name&gt; &lt;Script&gt; Param ( [Parameter(Mandatory = $true)] [string]$GivenName ) $this | Add-Member -MemberType 'NoteProperty' -Name 'GivenName' -Value $GivenName -Force &lt;/Script&gt; &lt;/ScriptMethod&gt; &lt;ScriptProperty&gt; &lt;Name&gt;FullName&lt;/Name&gt; &lt;GetScriptBlock&gt;'{0} {1}' -f $this.GivenName, $this.Surname&lt;/GetScriptBlock&gt; &lt;/ScriptProperty&gt; &lt;!-- include properties under here if we don't want them to be visible by default &lt;MemberSet&gt; &lt;Name&gt;PSStandardMembers&lt;/Name&gt; &lt;Members&gt; &lt;/Members&gt; &lt;/MemberSet&gt; --&gt; &lt;/Members&gt; &lt;/Type&gt; &lt;/Types&gt; </code></pre> <ol start="2"> <li>Import your type: <code>Update-TypeData -AppendPath .\Person.Types.ps1xml</code></li> <li>Create an object of your custom type: <code>$p = [PSCustomType]@{PSTypeName='StackOverflow.Example.Person'}</code></li> <li>Initialise your type using the script method you defined in the XML: <code>$p.Initialize('Anne', 'Droid')</code></li> <li>Look at it; you'll see all properties defined: <code>$p | Format-Table -AutoSize</code></li> <li>Type calling a mutator to update a property's value: <code>$p.SetGivenName('Dan')</code></li> <li>Look at it again to see the updated value: <code>$p | Format-Table -AutoSize</code></li> </ol> <h1>Explanation</h1> <ul> <li>The PS1XML file allows you to define custom properties on types.</li> <li>It is not restricted to .net types as the documentation implies; so you can put what you like in '/Types/Type/Name' any object created with a matching 'PSTypeName' will inherit the members defined for this type.</li> <li>Members added through <code>PS1XML</code> or <code>Add-Member</code> are restricted to <code>NoteProperty</code>, <code>AliasProperty</code>, <code>ScriptProperty</code>, <code>CodeProperty</code>, <code>ScriptMethod</code>, and <code>CodeMethod</code> (or <code>PropertySet</code>/<code>MemberSet</code>; though those are subject to the same restrictions). All of these properties are read only.</li> <li>By defining a <code>ScriptMethod</code> we can cheat the above restriction. E.g. We can define a method (e.g. <code>Initialize</code>) which creates new properties, setting their values for us; thus ensuring our object has all the properties we need for our other scripts to work.</li> <li>We can use this same trick to allow the properties to be updatable (albeit via method rather than direct assignment), as shown in the example's <code>SetGivenName</code>.</li> </ul> <p>This approach isn't ideal for all scenarios; but is useful for adding class-like behaviors to custom types / can be used in conjunction with other methods mentioned in the other answers. E.g. in the real world I'd probably only define the <code>FullName</code> property in the PS1XML, then use a function to create the object with the required values, like so:</p> <h1>More Info</h1> <p>Take a look at the <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_types.ps1xml?view=powershell-6" rel="nofollow noreferrer">documentation</a>, or the OOTB type file <code>Get-Content $PSHome\types.ps1xml</code> for inspiration.</p> <pre><code># have something like this defined in my script so we only try to import the definition once. # the surrounding if statement may be useful if we're dot sourcing the script in an existing # session / running in ISE / something like that if (!(Get-TypeData 'StackOverflow.Example.Person')) { Update-TypeData '.\Person.Types.ps1xml' } # have a function to create my objects with all required parameters # creating them from the hash table means they're PROPERties; i.e. updatable without calling a # setter method (note: recall I said above that in this scenario I'd remove their definition # from the PS1XML) function New-SOPerson { [CmdletBinding()] [OutputType('StackOverflow.Example.Person')] Param ( [Parameter(Mandatory)] [string]$GivenName , [Parameter(Mandatory)] [string]$Surname ) ([PSCustomObject][Ordered]@{ PSTypeName = 'StackOverflow.Example.Person' GivenName = $GivenName Surname = $Surname }) } # then use my new function to generate the new object $p = New-SOPerson -GivenName 'Simon' -Surname 'Borg' # and thanks to the type magic... FullName exists :) Write-Information "$($p.FullName) was created successfully!" -InformationAction Continue </code></pre>
8,454
<p>I worked on an embedded system this summer written in straight C. It was an existing project that the company I work for had taken over. I have become quite accustomed to writing unit tests in Java using JUnit but was at a loss as to the best way to write unit tests for existing code (which needed refactoring) as well as new code added to the system.</p> <p>Are there any projects out there that make unit testing plain C code as easy as unit testing Java code with JUnit? Any insight that would apply specifically to embedded development (cross-compiling to arm-linux platform) would be greatly appreciated.</p>
<p>One unit testing framework in C is <a href="https://libcheck.github.io/check/" rel="noreferrer">Check</a>; a list of unit testing frameworks in C can be found <a href="http://check.sourceforge.net/doc/check_html/check_2.html#SEC3" rel="noreferrer">here</a> and is reproduced below. Depending on how many standard library functions your runtime has, you may or not be able to use one of those.</p> <blockquote> <h3>AceUnit</h3> <p>AceUnit (Advanced C and Embedded Unit) bills itself as a comfortable C code unit test framework. It tries to mimick JUnit 4.x and includes reflection-like capabilities. AceUnit can be used in resource constraint environments, e.g. embedded software development, and importantly it runs fine in environments where you cannot include a single standard header file and cannot invoke a single standard C function from the ANSI / ISO C libraries. It also has a Windows port. It does not use forks to trap signals, although the authors have expressed interest in adding such a feature. See the <a href="http://aceunit.sourceforge.net/" rel="noreferrer">AceUnit homepage</a>.</p> <h3>GNU Autounit</h3> <p>Much along the same lines as Check, including forking to run unit tests in a separate address space (in fact, the original author of Check borrowed the idea from GNU Autounit). GNU Autounit uses GLib extensively, which means that linking and such need special options, but this may not be a big problem to you, especially if you are already using GTK or GLib. See the <a href="http://autounit.tigris.org/" rel="noreferrer">GNU Autounit homepage</a>.</p> <h3>cUnit</h3> <p>Also uses GLib, but does not fork to protect the address space of unit tests.</p> <h3>CUnit</h3> <p>Standard C, with plans for a Win32 GUI implementation. Does not currently fork or otherwise protect the address space of unit tests. In early development. See the <a href="http://cunit.sourceforge.net/" rel="noreferrer">CUnit homepage</a>.</p> <h3>CuTest</h3> <p>A simple framework with just one .c and one .h file that you drop into your source tree. See the <a href="http://cutest.sourceforge.net/" rel="noreferrer">CuTest homepage</a>.</p> <h3>CppUnit</h3> <p>The premier unit testing framework for C++; you can also use it to test C code. It is stable, actively developed, and has a GUI interface. The primary reasons not to use CppUnit for C are first that it is quite big, and second you have to write your tests in C++, which means you need a C++ compiler. If these don’t sound like concerns, it is definitely worth considering, along with other C++ unit testing frameworks. See the <a href="http://cppunit.sourceforge.net/doc/cvs/index.html" rel="noreferrer">CppUnit homepage</a>.</p> <h3>embUnit</h3> <p>embUnit (Embedded Unit) is another unit test framework for embedded systems. This one appears to be superseded by AceUnit. <a href="http://sourceforge.net/projects/embunit/" rel="noreferrer">Embedded Unit homepage</a>.</p> <h3>MinUnit</h3> <p>A minimal set of macros and that’s it! The point is to show how easy it is to unit test your code. See the <a href="http://www.jera.com/techinfo/jtns/jtn002.html" rel="noreferrer">MinUnit homepage</a>.</p> <h3>CUnit for Mr. Ando</h3> <p>A CUnit implementation that is fairly new, and apparently still in early development. See the <a href="http://park.ruru.ne.jp/ando/work/CUnitForAndo/html/" rel="noreferrer">CUnit for Mr. Ando homepage</a>.</p> <p><em>This list was last updated in March 2008.</em></p> </blockquote> <h2>More frameworks:</h2> <h3>CMocka</h3> <p>CMocka is a test framework for C with support for mock objects. It's easy to use and setup.</p> <p>See <a href="https://cmocka.org/" rel="noreferrer">the CMocka homepage</a>.</p> <h3>Criterion</h3> <p>Criterion is a cross-platform C unit testing framework supporting automatic test registration, parameterized tests, theories, and that can output to multiple formats, including TAP and JUnit XML. Each test is run in its own process, so signals and crashes can be reported or tested if needed.</p> <p>See the <a href="https://github.com/Snaipe/Criterion" rel="noreferrer">Criterion homepage</a> for more information.</p> <h3>HWUT</h3> <p>HWUT is a general Unit Test tool with great support for C. It can help to create Makefiles, generate massive test cases coded in minimal 'iteration tables', walk along state machines, generate C-stubs and more. The general approach is pretty unique: Verdicts are based on 'good stdout/bad stdout'. The comparison function, though, is flexible. Thus, any type of script may be used for checking. It may be applied to any language that can produce standard output.</p> <p>See <a href="http://hwut.sourceforge.net/" rel="noreferrer">the HWUT homepage</a>.</p> <h3>CGreen</h3> <p>A modern, portable, cross-language unit testing and mocking framework for C and C++. It offers an optional BDD notation, a mocking library, the ability to run it in a single process (to make debugging easier). A test runner which discover automatically the test functions is available. But you can create your own programmatically.</p> <p>All those features (and more) are explained in <a href="https://cgreen-devs.github.io/" rel="noreferrer">the CGreen manual</a>.</p> <p>Wikipedia gives a detailed list of C unit testing frameworks under <a href="https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C" rel="noreferrer">List of unit testing frameworks: C</a></p>
<p>In case you are targeting Win32 platforms or NT kernel mode, you should have a look at <a href="http://cfix.sf.net/" rel="nofollow noreferrer">cfix</a>.</p>
9,149
<p>I'm making a simple IRC Bot in C. And I finally got the bot connecting and receiving information. My code is supposed to be sending as well, but the server is acting as if it is not sending anything. When The bot connects, I receive this:</p> <blockquote> <p>Recieved: :roc.esper.net NOTICE AUTH :*** Looking up your hostname...</p> <p>Recieved: :roc.esper.net NOTICE AUTH :*** Found your hostname</p> </blockquote> <p>at which point my code sends this:</p> <p>Sent: NICK Goo</p> <p>Sent: USER Goo * * :Goo</p> <p>I determined from using wireshark that this is the registration you should send after the initial connect. However, I'm not sure the data is actually sending or maybe it is invalid somehow? Because after about 30 seconds of nothing i also receive this:</p> <blockquote> <p>Recieved: ERROR :Closing Link: c-68-33-143-182.hsd1.md.comcast.net (Registration timed out)</p> </blockquote> <p>And then my program closes.</p> <p>Does anyone else know anything about the programatic auth/registration processes in irc? Or does anyone else have any helpful ideas at all?</p> <p>Thanks</p> <p>** EDIT ** Fixed. I needed to be sending line terminators at the end of each line. \r\n</p>
<p>Try sending the USER command before the NICK command. What IRC network are you trying to connect to?</p> <pre><code>" &gt; telnet irc.freenode.net 6667 NOTICE AUTH :*** Looking up your hostname... NOTICE AUTH :*** Checking ident NOTICE AUTH :*** No identd (auth) response NOTICE AUTH :*** Couldn't look up your hostname USER x x x x NICK hwjrh :kubrick.freenode.net 001 hwjrh :Welcome to the freenode IRC Network hwjrh :kubrick.freenode.net 002 hwjrh :Your host is kubrick.freenode.net[kubrick.freenode.net/6667], running version hyperion-1.0.2b " </code></pre> <p>Works for me; I telnet to Freenode, Undernet and Dalnet all the time...</p>
<p>From the tutorials I looked at (like <a href="http://www.haskell.org/haskellwiki/Roll_your_own_IRC_bot" rel="nofollow noreferrer">this one</a>), it seems that you are doing it right, except that this</p> <pre><code>USER Goo * * :Goo </code></pre> <p>is</p> <pre><code>USER Goo 0 * :Goo </code></pre> <p>in all the tutorials I saw. Also, don't forget the PING-PONG later on, but this should not be needed for registration (EDIT: It seems that this is wrong and PONG is needed right after you send NICK).</p> <p>I guess you know about <a href="http://www.mirc.com/help/rfc1459.txt" rel="nofollow noreferrer">RFC 1459</a>, which will also help you a lot with this.</p>
41,826
<p>We've been using Scrum on a few projects now with varying success and I now have a query relating to documentation.</p> <p>In Scrum, you obviously have the product backlog ("The application begins by bringing up the last document the user was working with.") and the sprint task backlog ("Implement forgot password screen"). However, in all the examples I have seen, these two items are fairly high level in terms of detail (being designed on fit on a post-it note).</p> <p>So, where does the detail sit? Let's say the client has some very specific requirements for a stock management screen, or has a complex API that needs to be integrated with on the back end, where is this documented, how and who captures this information? Is it seperate to the backlog but populated on a just-in-time basis or some other way?</p>
<p><a href="http://en.wikipedia.org/wiki/Scrum_(development)#Sprint_backlog" rel="noreferrer">Sprint backlog</a></p> <blockquote> <p>The sprint backlog is a greatly detailed document containing information about how the team is going to implement the requirements for the upcoming sprint. Tasks are broken down into hours with no task being more than 16 hours. If a task is greater than 16 hours, it should be broken down further. Tasks on the sprint backlog are never assigned, rather tasks are signed-up for by the team members as they like.</p> </blockquote>
<p>My understanding is that specific requirements such as this are handled by the product owner. They will liase with the client during Sprint Planning 2 and update the tasks with specfic requirements as needed - hence why the Product Owner is a optional attendee of the Sprint Planning 2 meeting. This gives you a hybrid of Just-in-Time and Sprint Planning 2 population of the specifics. Anything that isn't satisfied by the time you come to work on the task will be an impediment and should be dealt with a the daily scrum, by the product owner.</p> <p>As the development is Agile when using Scrum you shouldn't find too much of an issues getting requirements just in time.</p>
15,372
<p>I have a gridview that is within an updatepanel for a modal popup I have on a page.<br> The issue is that the entire page refreshes every time I click an imagebutton that is within my gridview. This causes my entire page to load and since I have grayed out the rest of the page so that the user cannot click on it this is very annoying.</p> <p>Does any one know what I am missing. </p> <p><strong>Edit:</strong> I entered a better solution at the bottom</p>
<p>do you have ChildrenAsTriggers="false" on the UpdatePanel?</p> <p>Are there any javascript errors on the page?</p>
<p>Is the Modal Window popped up using the IE Modal window? Or is it a DIV that you are showing?</p> <p>If it is an IE Modal Pop up you need to ensure you have </p> <pre><code> &lt;base target="_self" /&gt; </code></pre> <p>To make sure the post back are to the modal page.</p> <p>If it is a DIV make sure you have your XHTML correct or it might not know what to update.</p>
5,516
<p>Due to a lack of response to my original <a href="https://stackoverflow.com/questions/124258/how-would-you-allow-users-to-edit-attachments-in-a-web-application">question</a>, probably due to poor wording on my part. Since then, I have thought about my original question and decided to reword it, hopefully for the better! :)</p> <p>We create custom business software for our customers, and quite often they want attachments to be added to certain business entities. For example, they want to attach a Word document to a customer, or an image to a job. I'm curious as to how other are handling the following:</p> <ul> <li>How the user attaches documents? Single attachment? Batch attachment?</li> <li>How you display the attached documents? Simple list? Detailed list?</li> <li>And the killer question, how the user then edits attached documents? Is this even possible in a web environment? Granted the user can just view the attachment.</li> <li>Is there a good control library to help manage this process?</li> </ul> <p>Our current development environment is ASP.NET and C#, but I don't think this is a pretty agnostic question when it comes to development tools, save for the fact I need to work in a web environment.</p> <p>It seems we always run into problems with the customer and working with attachments in a web environment so I am looking for some <strong>successes</strong> that other programmers have had with their user base on how best to interact with attachments.</p>
<ul> <li>Start with one file upload control ("Browse button"), and use JavaScript to dynamically add more upload controls if they want to attach multiple files in a single batch.</li> <li>Display them in a simple list format (Filename, type, size, date), but provide full details somewhere else if they want them.</li> <li>If they want to edit the files, they have to download them, then re-upload them. Hence, you need a way that they can say "this attachment overrides that old attachment".</li> <li>I'm not familiar with C# and ASP.NET, so I can't recommend any libraries that will help.</li> </ul>
<p><a href="http://developer.yahoo.com/yui/uploader/" rel="nofollow noreferrer">http://developer.yahoo.com/yui/uploader/</a></p>
15,724
<p>I have a requirement to read and display the owner of a file (for audit purposes), and potentially changing it as well (this is secondary requirement). Are there any nice C# wrappers?</p> <p>After a quick google, I found only <a href="http://web.archive.org/web/20061116233324/http://www.softinsight.com/bnoyes/PermaLink.aspx?guid=8edc9d4c-0f2c-4006-8186-a3697ebc7476" rel="noreferrer">the WMI solution</a> and a suggestion to PInvoke GetSecurityInfo</p>
<p>No need to P/Invoke. <a href="http://msdn.microsoft.com/en-us/library/system.io.file.getaccesscontrol.aspx" rel="noreferrer">System.IO.File.GetAccessControl</a> will return a <a href="http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesecurity_members.aspx" rel="noreferrer">FileSecurity</a> object, which has a <a href="http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.objectsecurity.getowner.aspx" rel="noreferrer">GetOwner</a> method.</p> <p>Edit: Reading the owner is pretty simple, though it's a bit of a cumbersome API:</p> <pre><code>const string FILE = @"C:\test.txt"; var fs = File.GetAccessControl(FILE); var sid = fs.GetOwner(typeof(SecurityIdentifier)); Console.WriteLine(sid); // SID var ntAccount = sid.Translate(typeof(NTAccount)); Console.WriteLine(ntAccount); // DOMAIN\username </code></pre> <p>Setting the owner requires a call to SetAccessControl to save the changes. Also, you're still bound by the Windows rules of ownership - you can't assign ownership to another account. You can give take ownership perms, and they have to take ownership.</p> <pre><code>var ntAccount = new NTAccount("DOMAIN", "username"); fs.SetOwner(ntAccount); try { File.SetAccessControl(FILE, fs); } catch (InvalidOperationException ex) { Console.WriteLine("You cannot assign ownership to that user." + "Either you don't have TakeOwnership permissions, or it is not your user account." ); throw; } </code></pre>
<pre><code>FileInfo fi = new FileInfo(@"C:\test.txt"); string user = fi.GetAccessControl().GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(); </code></pre>
18,477
<p>I have a database with <code>account numbers</code> and <code>card numbers</code>. I match these to a file to <code>update</code> any card numbers to the account number so that I am only working with account numbers.</p> <p>I created a view linking the table to the account/card database to return the <code>Table ID</code> and the related account number, and now I need to update those records where the ID matches the Account Number.</p> <p>This is the <code>Sales_Import</code> table, where the <code>account number</code> field needs to be updated:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>LeadID</th> <th>AccountNumber</th> </tr> </thead> <tbody> <tr> <td>147</td> <td>5807811235</td> </tr> <tr> <td>150</td> <td>5807811326</td> </tr> <tr> <td>185</td> <td>7006100100007267039</td> </tr> </tbody> </table> </div> <p>And this is the <code>RetrieveAccountNumber</code> table, where I need to update from:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>LeadID</th> <th>AccountNumber</th> </tr> </thead> <tbody> <tr> <td>147</td> <td>7006100100007266957</td> </tr> <tr> <td>150</td> <td>7006100100007267039</td> </tr> </tbody> </table> </div> <p>I tried the below, but no luck so far:</p> <pre><code>UPDATE [Sales_Lead].[dbo].[Sales_Import] SET [AccountNumber] = (SELECT RetrieveAccountNumber.AccountNumber FROM RetrieveAccountNumber WHERE [Sales_Lead].[dbo].[Sales_Import]. LeadID = RetrieveAccountNumber.LeadID) </code></pre> <p>It updates the card numbers to account numbers, but the account numbers get replaced by <code>NULL</code></p>
<p>I believe an <code>UPDATE FROM</code> with a <code>JOIN</code> will help:</p> <h2>MS SQL</h2> <pre><code>UPDATE Sales_Import SET Sales_Import.AccountNumber = RAN.AccountNumber FROM Sales_Import SI INNER JOIN RetrieveAccountNumber RAN ON SI.LeadID = RAN.LeadID; </code></pre> <h2>MySQL and MariaDB</h2> <pre><code>UPDATE Sales_Import SI, RetrieveAccountNumber RAN SET SI.AccountNumber = RAN.AccountNumber WHERE SI.LeadID = RAN.LeadID; </code></pre>
<p>If above answers not working for you try this </p> <pre><code>Update Sales_Import A left join RetrieveAccountNumber B on A.LeadID = B.LeadID Set A.AccountNumber = B.AccountNumber where A.LeadID = B.LeadID </code></pre>
27,776
<p>What is the easiest way to manage the authorized_keys file for openssh across a large number of hosts? If I need to add or revoke a new key to an account on 10 hosts say, I must login and add the public key manually, or through a clumsy shell script, which is time consuming. </p> <p>Ideally there would be a central database linking keys to accounts@machines with some sort of grouping support (IE, add this key to username X on all servers in the web category). There's fork of SSH with ldap support, but I'd rather use the mainline SSH packages.</p>
<p>I'd checkout the <a href="http://web.monkeysphere.info/" rel="noreferrer">Monkeysphere</a> project. It uses OpenPGP's web of trust concepts to manage ssh's authorized_keys and known_hosts files, without requiring changes to the ssh client or server.</p>
<p>I've always done this by maintaining a "master" tree of the different servers' keys, and using rsync to update the remote machines. This lets you edit things in one location, push the changes out efficiently, and keeps things "up to date" -- everyone edits the master files, no one edits the files on random hosts.</p> <p>You may want to look at projects which are made for running commands across groups of machines, such as Func at <a href="https://fedorahosted.org/func" rel="nofollow noreferrer">https://fedorahosted.org/func</a> or other server configuration management packages. </p>
10,008
<p>I came across the Adobe Flex framework one day. After watching http://www.adobe.com/products/flex/media/flexapp/'> the demo of Flex, it looks to me it is a bundle of different Ajax controls. I have no working knowledge of Flex at all and know very little about Flex. Therefore, I would like to hear from the developers here with some Flex experience to explain a bit more pros and cons of this Framework. In particular:</p> <ul> <li> How productive it is to program in Flex compared to the .Net + Silverlight? </li> <li> Any technical advantages over other frameworks? </li> <li> Any disadvantages ? <li> Does it have any known scaling issues? </li> <li> What kind of web servers can it be hosted on? </li> <li> Any other things I should be aware of about Flex? </ul>
<ul> <li>How productive it is to program in Flex compared to the .Net + Silverlight?</li> </ul> <p>Way more productive than Silverlight as it has a much richer and capable control library. Silverlight is rapidly gaining ground here though. I think by the time SL 4 comes out they will reach feature parity, maybe even SL 3.</p> <ul> <li>Any technical advantages over other frameworks?</li> </ul> <p>If you can create it in Photoshop, you can pretty much do it in Flex with the help of the Flash drawing API. If you want to build very interesting data visualizations (tree/node diagrams, such as an org chart) you can do this Flex without a ton of work.</p> <ul> <li>Any disadvantages ?</li> </ul> <p>There is no server-side component to ActionScript so you need to find a way to pass data between Flex and your backend, be it Java, .NET, PHP, etc. There are libraries out there to AMF remoting with just about any backend which makes it easy. But as far as the objects you pass between the two, you need to maintain both or use a code generation tool to create AS3 classes from your backend classes.</p> <ul> <li>Does it have any known scaling issues?</li> </ul> <p>Flex is simply a presentation technology so this question doesn't really apply.</p> <ul> <li>What kind of web servers can it be hosted on?</li> </ul> <p>Again, only a presentation technology. It compiles out to a SWF file that is loaded by the browser over HTTP and then executes inside of the Flash Player plugin.</p>
<p>Well ~~ .. it's more that Silverlight is similar to Flex. It's not Ajax so much as a kind of 'walled-garden' inside of which you have a rich programming environment. Somewhat like Java apps say.</p> <p>The usual criticism derives from just that. Flex/Flash applications tend to be ignorant of the browser (more or less) so that stuff like back-button usually gives unexpected results.</p> <p>It'll run on all the current browsers on all platforms. You don't <em>need</em> to "host" flex as you build a SWF file that gets loaded into the browser and is executed by the Flash Player which your users are expected to have already downloaded/installed .. (95+%) penetration helps.</p> <p>I've been using Flex for the last year or so and it's served my purposes well. It can be integrated nicely with javascript stuff on your web pages and provides a very rich set of capabilities for doing all sorta things like web-services and XML processing and of course all your video/audio/music rich media.</p>
42,555
<p><strong>Is there anything built into the core C# libraries that can give me an immutable Dictionary?</strong> </p> <p>Something along the lines of <em>Java's</em>:</p> <pre><code>Collections.unmodifiableMap(myMap); </code></pre> <p>And just to clarify, I am not looking to stop the keys / values themselves from being changed, just the structure of the Dictionary. I want something that fails fast and loud if any of IDictionary's mutator methods are called (<code>Add, Remove, Clear</code>).</p>
<p>No, but a wrapper is rather trivial:</p> <pre><code>public class ReadOnlyDictionary&lt;TKey, TValue&gt; : IDictionary&lt;TKey, TValue&gt; { IDictionary&lt;TKey, TValue&gt; _dict; public ReadOnlyDictionary(IDictionary&lt;TKey, TValue&gt; backingDict) { _dict = backingDict; } public void Add(TKey key, TValue value) { throw new InvalidOperationException(); } public bool ContainsKey(TKey key) { return _dict.ContainsKey(key); } public ICollection&lt;TKey&gt; Keys { get { return _dict.Keys; } } public bool Remove(TKey key) { throw new InvalidOperationException(); } public bool TryGetValue(TKey key, out TValue value) { return _dict.TryGetValue(key, out value); } public ICollection&lt;TValue&gt; Values { get { return _dict.Values; } } public TValue this[TKey key] { get { return _dict[key]; } set { throw new InvalidOperationException(); } } public void Add(KeyValuePair&lt;TKey, TValue&gt; item) { throw new InvalidOperationException(); } public void Clear() { throw new InvalidOperationException(); } public bool Contains(KeyValuePair&lt;TKey, TValue&gt; item) { return _dict.Contains(item); } public void CopyTo(KeyValuePair&lt;TKey, TValue&gt;[] array, int arrayIndex) { _dict.CopyTo(array, arrayIndex); } public int Count { get { return _dict.Count; } } public bool IsReadOnly { get { return true; } } public bool Remove(KeyValuePair&lt;TKey, TValue&gt; item) { throw new InvalidOperationException(); } public IEnumerator&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; GetEnumerator() { return _dict.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((System.Collections.IEnumerable)_dict).GetEnumerator(); } } </code></pre> <p>Obviously, you can change the this[] setter above if you want to allow modifying values. </p>
<p>There's also another alternative as I have described at:</p> <p><a href="http://www.softwarerockstar.com/2010/10/readonlydictionary-tkey-tvalue/" rel="nofollow">http://www.softwarerockstar.com/2010/10/readonlydictionary-tkey-tvalue/</a></p> <p>Essentially it's a subclass of ReadOnlyCollection>, which gets the work done in a more elegant manner. Elegant in the sense that it has compile-time support for making the Dictionary read-only rather than throwing exceptions from methods that modify the items within it.</p>
5,542
<p>I was asked implement a licensing schema for our product. They are very expensive products with few customers sparsely distributed around the world and basically every one of them has a design environment (a windows application installed on single windows machines, from 1 to 150 client machines per customer) and a web server that hosts production environment (1 to 8 machines per customer). Our product is licensed for server usage so customers can use any number of clients; we've decided not to license the server part (because it's subject to SLA agreements) but only the client, because, after some time without capability to use the client the system becomes basically useless.</p> <p>Our basic assumption is that the customer is "honest enough" and only thing we would like to cover is stopping the client design environment if not properly licensed with a time expiration license.</p> <p>I've evaluated different licensing product and they are or too expensive or too difficult to manage, so I've come up with this simple solution:</p> <ul> <li>The license will be a simple signed XML file, signed using the standard XML Signature feature of w3c, using a private key that will be given to the admin department on a USB key; if they lose of copy it then the licensing schema will fail but it will be their fault</li> <li>The client will open the license file on startup and check its validity using a public key embedded in the binaries</li> <li>If license XML is valid and the data in it (expiration date and product name) are correct than the designer work; if not, an appropriate message will be shown</li> </ul> <p>Any ideas about possible problems or how to improve the scenario?</p>
<p>I have yet to see a licensing scheme that wasn't broken in a few weeks provided there was sufficient interest. Your scheme looks very good (though be certain that if someone really wants to, they'll break it). </p> <p>Whatever you do, you should follow Eric Sink's <a href="http://www.ericsink.com/bos/Transparency.html" rel="nofollow noreferrer">advice</a>:</p> <blockquote> <p>The goal should simply be to "keep honest people honest". If we go further than this, only two things happen:</p> <ol> <li>We fight a battle we cannot win. Those who want to cheat will succeed.</li> <li>We hurt the honest users of our product by making it more difficult to use.</li> </ol> </blockquote> <p>Since you're implementing a license scheme for a program designed for corporate use, you can go even simpler and just keep some kind of id and expiration date along with a simple signature on the client and refuse to start if the license expired or signature failed. It's not that hard to break it, but no licensing scheme is and if you consider your customers honest, this will be more than enough.</p>
<p>It's not completely clear from your question how your scheme works. Does every instance of the client software have a different key? How long does the license last? Do you have a different key per customer? How is the license paid for? How is a license renewed?</p> <p>If you are trying to control numbers of usages of the client code then only the first one above will do it.</p> <p>At the end of the day, in the world you appear to inhabit, I suspect that you are going to have to live in trust that there are no blatant infringements of your license. Most decent sized organisations (which it sounds like your customers would be) have a responsibility not to infringe which can lead them to serious consequences if they break the license agreements. They will be audited on it periodically too and you probably have some statutory rights to go and check their usage (if not you should write it into your license agreement).</p> <p>Where it becomes very dangerous for you is if the contents of the USB keys find their way onto the web. In that regard any scheme which uses a published key is vulnerable to a wilful disclosure of the secrets.</p> <p>I'm certain there is a lot of literature on this subject, so it is probably worth you continuing your research.</p> <p>BTW I'm not sure about your reference to SLAs in the middle part about your server licensing. Licensing and SLAs are very different. A license is the clients obligation an SLA is yours. </p>
20,519
<p>Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory?</p> <p>What I want to do is the copy a file if it's on a different, but move it if it's the same. For example:</p> <pre><code>target_directory = "/Volumes/externalDrive/something/" input_foldername, input_filename = os.path.split(input_file) if same_partition(input_foldername, target_directory): copy(input_file, target_directory) else: move(input_file, target_directory) </code></pre>
<p>In C, you would use <code>stat()</code> and compare the <code>st_dev</code> field. In python, <code>os.stat</code> should do the same.</p> <pre><code>import os def same_partition(f1, f2): return os.stat(f1).st_dev == os.stat(f2).st_dev </code></pre>
<p>Another way is the “better to ask forgiveness than permission” approach—just try to rename it, and if that fails, catch the appropriate <code>OSError</code> and try the copy approach. ie:</p> <pre><code>import errno try: os.rename(source, dest): except IOError, ex: if ex.errno == errno.EXDEV: # perform the copy instead. </code></pre> <p>This has the advantage that it will also work on Windows, where st_dev is always 0 for all partitions.</p> <p>Note that if you actually want to copy and then delete the source file (ie. perform a move), rather than just copy, then shutil.move will already do what you want:</p> <pre> Help on function move in module shutil: move(src, dst) Recursively move a file or directory to another location. If the destination is on our current filesystem, then simply use rename. Otherwise, copy src to the dst and then remove src. </pre>
31,061
<p>Why do I get compiler errors with this Java code?</p> <pre><code>1 public List&lt;? extends Foo&gt; getFoos() 2 { 3 List&lt;? extends Foo&gt; foos = new ArrayList&lt;? extends Foo&gt;(); 4 foos.add(new SubFoo()); 5 return foos; 6 }</code></pre> <p>Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface.</p> <p>Errors I get with this code:</p> <ul> <li>On Line 3: "Cannot instantiate ArrayList&lt;? extends Foo&gt;"</li> <li>On Line 4: "The method add(capture#1-of ? extends Foo) in the type List&lt;capture#1-of ? extends Foo&gt; is not applicable for the arguments (SubFoo)"</li> </ul> <p><b>Update:</b> Thanks to Jeff C, I can change Line 3 to say "new ArrayList&lt;Foo&gt;();". But I'm still having the issue with Line 4.</p>
<p>Use this instead:</p> <pre><code>1 public List&lt;? extends Foo&gt; getFoos() 2 { 3 List&lt;Foo&gt; foos = new ArrayList&lt;Foo&gt;(); /* Or List&lt;SubFoo&gt; */ 4 foos.add(new SubFoo()); 5 return foos; 6 } </code></pre> <p>Once you declare foos as <code>List&lt;? extends Foo&gt;</code>, the compiler doesn't know that it's safe to add a SubFoo. What if an <code>ArrayList&lt;AltFoo&gt;</code> had been assigned to <code>foos</code>? That would be a valid assignment, but adding a SubFoo would pollute the collection.</p>
<p>The following will work fine:</p> <pre><code>public List&lt;? extends Foo&gt; getFoos() { List&lt;Foo&gt; foos = new ArrayList&lt;Foo&gt;(); foos.add(new SubFoo()); return foos; } </code></pre>
21,254
<p>The scenario</p> <ul> <li>You have developed a webapp using EJBs version 3.</li> <li>The system is deployed, delivered and is used by the customer.</li> </ul> <p>If you would have to rewrite the system from scratch, would you use EJBs again?</p> <p><strong>No</strong>: Don't answer this question, answer <a href="https://stackoverflow.com/questions/161349/top-reason-not-to-use-ejb-30-again">this one</a> instead.</p> <p><strong>Yes</strong>: Provide one important, real problem that EJBs solved, based on your personal experience.</p> <p>Let the answer contain just <strong>one</strong> problem. This will let other readers vote up the best feature of EJBs.</p>
<p>I think it depends on what version of EJBs you're talking about. Let's discuss the only two relevant (IMO) versions.</p> <p>EJB 2.1 might still be used by some people in a legacy system. They really have the most use as an RPC abstraction. They also provided a rudimentary ORM (Object-Relational Mapping) system as well. And as you mentioned, transaction support is provided. So if you were building a system where you wanted to communicate with a remote system, transfer object-oriented data and do it transactionally, you might find EJBs to be worth the effort. Otherwise, I'd say stay away.</p> <p>EJB 3.0, however, has been greatly improved. It has all the features of the previous version, but does it in a more straightforward way. It also provides a fairly simple Inversion-Of-Control framework not unlike Spring, and a pretty decent ORM in the form of the JPA (Java Persistence API.) I have used EJB 3.0 and actually enjoyed it. You could argue for the use of EJB 3.0 the same way you would for Spring, plus it has a few more advanced, or enterprise-y, features available.</p>
<p>One thing that has bitten many when using EJBs, or J2EE in general, is the dependency on the application server you're running your EJBs on. The appserver tends to be supported for a particular set of operating system releases and JVM versions. Not having the source code to a significant part of your runtime environment could also turn into a challenge.</p> <p>While migrating from one vendor to another in principle is possible, you need to be very aware of small differences in how they implement the specification, and to stay away from vendor-specific extensions.</p> <p>That being said, the appservers I've been exposed to can handle very much abuse from the code running in it and perform very well.</p>
13,099
<p>I am trying to read a custom (non-standard) CSS property, set in a stylesheet (not the inline style attribute) and get its value. Take this CSS for example:</p> <pre><code>#someElement { foo: 'bar'; } </code></pre> <p>I have managed to get its value with the currentStyle property in IE7:</p> <pre><code>var element = document.getElementById('someElement'); var val = element.currentStyle.foo; </code></pre> <p>But currentStyle is MS-specific. So I tried getComputedStyle() in Firefox 3 and Safari 3:</p> <pre><code>var val = getComputedStyle(element,null).foo; </code></pre> <p>...and it returns undefined. <strong>Does anyone know a cross-browser way of retreiving a custom CSS property value?</strong></p> <p><em>(As you might have noticed, this isn't valid CSS. But it should work as long as the value follows the correct syntax. A better property name would be "-myNameSpace-foo" or something.)</em></p>
<p>Firefox does not carry over tags, attributes or CSS styles it does not understand from the code to the DOM. That is by design. Javascript only has access to the DOM, not the code. So no, there is no way to access a property from javascript that the browser itself does not support.</p>
<p>Maybe you can try with <a href="http://lesscss.org/" rel="nofollow">LESS</a>. It's The Dynamic Stylesheet language and you can create non-standard css attributes, commands that will compile later.</p>
31,097
<p>This is in reference to a <a href="https://stackoverflow.com/questions/331073/speed-up-nhibernate-calls-to-oracle">question</a> I asked earlier. Aside from viewing the SQL generated by NHibernate on calls to the database, what is the best way to find bottlenecks between NHibernate and the DB? In particular, I have queries that return very quickly when run directly against the database, but very slow (over 3-4x) return times when running the code in unit tests and on the web page. I am relatively sure this has something to do with the way I have mapped my tables and the primary keys. How can I dig in further to see where my slow areas are occurring? Are there other tools available? I know this is an extremely broad question, but I have not had the need to explore these problems yet. Any help would be greatly appreciated.</p>
<p>AFAIK there is no single tool to profile NHibernate, yet. This is about to change with <a href="http://ayende.com/Blog/archive/2008/11/04/nh-prof-a-guided-tour.aspx" rel="nofollow noreferrer">Ayende's NHIbernate Profiler</a>. In the meantime, you can use a combination of code profilers (e.g. <a href="http://www.jetbrains.com/profiler/" rel="nofollow noreferrer">dotTrace</a>), SQL Server Profiler, the NHibernate logger, and static analysis, i.e. if you know about the SELECT N+1 problem, most of the time you can spot it just by looking at the code.</p> <p><strong>EDIT</strong>: <a href="http://www.nhprof.com/" rel="nofollow noreferrer">NHProf</a> is now available!</p>
<p>I use JProbe for analyzing my code. It can show the amount of time spent in any particular location in my code, and where the bottlenecks are. I'm sure there are other tools available though, some of which may be cheaper.</p>
43,053
<p>I'm looking for shell scripts files installed on my system, but <strong>find</strong> doesn't work:</p> <pre><code>$ find /usr -name *.sh </code></pre> <p>But I know there are a ton of scripts out there. For instance:</p> <pre><code>$ ls /usr/local/lib/*.sh /usr/local/lib/tclConfig.sh /usr/local/lib/tkConfig.sh </code></pre> <p>Why doesn't <strong>find</strong> work?</p>
<p>Try quoting the wildcard:</p> <pre><code>$ find /usr -name \*.sh </code></pre> <p>or:</p> <pre><code>$ find /usr -name '*.sh' </code></pre> <p>If you happen to have a file that matches <strong>*.sh</strong> in the current working directory, the wildcard will be expanded before find sees it. If you happen to have a file named tkConfig.sh in your working directory, the <strong>find</strong> command would expand to:</p> <pre><code>$ find /usr -name tkConfig.sh </code></pre> <p>which would only find files named tkConfig.sh. If you had more than one file that matches <strong>*.sh</strong>, you'd get a syntax error from <strong>find</strong>:</p> <pre><code>$ cd /usr/local/lib $ find /usr -name *.sh find: bad option tkConfig.sh find: path-list predicate-list </code></pre> <p>Again, the reason is that the wildcard expands to both files:</p> <pre><code>$ find /usr -name tclConfig.sh tkConfig.sh </code></pre> <p>Quoting the wildcard prevents it from being prematurely expanded.</p> <p>Another possibility is that /usr or one of its subdirectories is a symlink. <strong>find</strong> doesn't normally follow links, so you might need the <strong>-follow</strong> option:</p> <pre><code>$ find /usr -follow -name '*.sh' </code></pre>
<p>For finding files on your disks, lean to use "locate" instead that is instantaneous (looks into a daily built index) you example would be:</p> <pre><code>locate '/usr*.sh' </code></pre>
3,936
<p>What software is recommended for working with and editing large XML schemas? I'm looking for both Windows and Linux software (doesn't have to be cross platform, just want suggestions for both) that help with dealing with huge XML files.</p>
<p>I may be old fashioned, but I prefer my text editor. </p> <p>I use emacs, and it has a fairly decent xml mode. </p> <p>Most good text editors will have decent syntax hi-lighting and tag matching facilities. Your IDE might already do it (IntelliJ idea does, and I believe Eclipse does as well). Good text editors will be able to deal with <em>huge</em> files, but some text editors may not be able to handle them. How big are we talking about?</p>
<p><strong>XML Copy Editor</strong> - Windows and Linux</p> <p>Fast, free, and supports XML schema validation.</p> <p>Official Website <a href="http://xml-copy-editor.sourceforge.net/" rel="nofollow">http://xml-copy-editor.sourceforge.net/</a></p> <p>How to install in Ubuntu <a href="http://ubuntuforums.org/showthread.php?t=1640003" rel="nofollow">http://ubuntuforums.org/showthread.php?t=1640003</a></p>
2,397
<p>I need to compare large count of PDF files for it optical content. Because the PDF files was created on different platforms and with different versions of the software there are structural differences. For example:</p> <ul> <li>the chunking of text can be different</li> <li>the write order can be different</li> <li>the position can be differ some pixels</li> </ul> <p>It should compare the content like a human people and not the internal structure. I want test for regressions between different versions of the PDF generator that we used. </p>
<p>Because there is no such tool available that we have written one. You can download the <a href="http://www.inetsoftware.de/products/pdf-content-comparer" rel="noreferrer">i-net PDF content comparer</a> and use it. I hope that help other with the same problem. If you have problems with it or you have feedback for us then you can contact our support.</p> <p><img src="https://i.stack.imgur.com/CvV5W.png" alt="enter image description here"></p>
<p>blubeam pdf software will do this for you</p>
17,560
<p><strong>Background:</strong> I have an HTML page which lets you expand certain content. As only small portions of the page need to be loaded for such an expansion, it's done via JavaScript, and not by directing to a new URL/ HTML page. However, as a bonus the user is able to permalink to such expanded sections, i.e. send someone else a URL like</p> <p><em><a href="http://example.com/#foobar" rel="noreferrer">http://example.com/#foobar</a></em></p> <p>and have the "foobar" category be opened immediately for that other user. This works using parent.location.hash = 'foobar', so that part is fine.</p> <p><strong>Now the question:</strong> When the user closes such a category on the page, I want to empty the URL fragment again, i.e. turn <a href="http://example.com/#foobar" rel="noreferrer">http://example.com/#foobar</a> into <a href="http://example.com/" rel="noreferrer">http://example.com/</a> to update the permalink display. However, doing so using <code>parent.location.hash = ''</code> causes a reload of the whole page (in Firefox 3, for instance), which I'd like to avoid. Using <code>window.location.href = '/#'</code> won't trigger a page reload, but leaves the somewhat unpretty-looking "#" sign in the URL. So is there a way in popular browsers to JavaScript-remove a URL anchor including the "#" sign without triggering a page refresh?</p>
<p>As others have mentioned, <a href="https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history#The_replaceState%28%29.C2.A0method" rel="noreferrer">replaceState</a> in HTML5 can be used to remove the URL fragment.</p> <p>Here is an example:</p> <pre><code>// remove fragment as much as it can go without adding an entry in browser history: window.location.replace("#"); // slice off the remaining '#' in HTML5: if (typeof window.history.replaceState == 'function') { history.replaceState({}, '', window.location.href.slice(0, -1)); } </code></pre>
<pre><code>$(document).ready(function() { $(".lnk").click(function(e) { e.preventDefault(); $(this).attr("href", "stripped_url_via_desired_regex"); }); }); </code></pre>
33,778
<p>I'm trying to reduce the form spam on our website. (It's actually pretty recent).</p> <p>I seem to remember reading somewhere that the spammers aren't executing the Javascript on the site.</p> <p>Is that true? And if so, then could you simply check for javascript being disabled and then figure it's <em>likely</em> that it's spam?</p>
<p>There are still a large number of people that run with Javascript turned off.</p> <p>Alternatively, I have had decent success with stopping form spam using CSS. Basically, include an input field and label that is hidden using CSS (<code>display: none;</code>) and once submitted, check if anything has been entered in the field. </p> <p>I generally label the field as a spam filter with an instruction to <em>not</em> put anything in the field, but all newer browsers will properly hide the block.</p> <ul> <li>More: <a href="http://www.modernblue.com/web-design-blog/fighting-spam-with-css/" rel="nofollow noreferrer">Fighting Spam with CSS</a></li> </ul> <p><a href="http://recaptcha.net/" rel="nofollow noreferrer">reCAPTCHA</a> is also surprisingly easy to implement.</p>
<p>I can't remember where I've seen this method but spam bots like to fill out forms. Have you considered putting a form field that is hidden with javascript (and says don't fill this field if the user doesn't have JavaScript). This way if something fills in this field you can ignore it as spam.</p>
7,563
<p>I have a fairly good feel for what MySQL replication can do. I'm wondering what other databases support replication, and how they compare to MySQL and others?</p> <p>Some questions I would have are:</p> <ol> <li>Is replication built in, or an add-on/plugin?</li> <li>How does the replication work (high-level)? MySQL provides statement-based replication (and row-based replication in 5.1). I'm interested in how other databases compare. What gets shipped over the wire? How do changes get applied to the replicas?</li> <li>Is it easy to check consistency between master and slaves?</li> <li>How easy is it to get a failed replica back in sync with the master?</li> <li>Performance? One thing I hate about MySQL replication is that it's single-threaded, and replicas often have trouble keeping up, since the master can be running many updates in parallel, but the replicas have to run them serially. Are there any gotchas like this in other databases?</li> <li>Any other interesting features...</li> </ol>
<p>MySQL's replication is weak inasmuch as one needs to sacrifice other functionality to get full master/master support (due to the restriction on supported backends).</p> <p>PostgreSQL's replication is weak inasmuch as only master/standby is supported built-in (using log shipping); more powerful solutions (such as Slony or Londiste) require add-on functionality. Archive log segments are shipped over the wire, which are the same records used to make sure that a standalone database is in working, consistent state on unclean startup. This is what I'm using presently, and we have resynchronization (and setup, and other functionality) fully automated. None of these approaches are fully synchronous. More complete support will be built in as of PostgreSQL 8.5. Log shipping does not allow databases to come out of synchronization, so there is no need for processes to test the synchronized status; bringing the two databases back into sync involves setting the backup flag on the master, rsyncing to the slave (with the database still runnning; this is safe), and unsetting the backup flag (and restarting the slave process) with the archive logs generated during the backup process available; my shop has this process (like all other administration tasks) automated. Performance is a nonissue, since the master has to replay the log segments internally anyhow in addition to doing other work; thus, the slaves will always be under less load than the master.</p> <p>Oracle's RAC (which isn't properly replication, as there's only one storage backend -- but you have multiple frontends sharing the load, and can build redundancy into that shared storage backend itself, so it's worthy of mention here) is a multi-master approach far more comprehensive than other solutions, but is <I><B>extremely</B></I> expensive. Database contents aren't "shipped over the wire"; instead, they're stored to the shared backend, which all the systems involved can access. Because there is only one backend, the systems cannot come out of sync.</p> <p>Continuent offers a third-party solution which does fully synchronous statement-level replication with support for all three of the above databases; however, the commercially supported version of their product isn't particularly cheap (though vastly less expensive. Last time I administered it, Continuent's solution required manual intervention for bringing a cluster back into sync.</p>
<p>Another way to go is to run in a virtualized environment. I thought the data in this blog article was interesting</p> <p><a href="http://chucksblog.typepad.com/chucks_blog/2008/09/enterprise-apps.html" rel="nofollow noreferrer">http://chucksblog.typepad.com/chucks_blog/2008/09/enterprise-apps.html</a></p> <p>It's from an EMC executive, so obviously, it's not independent, but the experiment should be reproducible</p> <p>Here's the data specific for Oracle</p> <p><a href="http://oraclestorageguy.typepad.com/oraclestorageguy/2008/09/to-rac-or-not-to-rac-reprise.html" rel="nofollow noreferrer">http://oraclestorageguy.typepad.com/oraclestorageguy/2008/09/to-rac-or-not-to-rac-reprise.html</a></p> <p>Edit: If you run virtualized, then there are ways to make anything replicate</p> <p><a href="http://chucksblog.typepad.com/chucks_blog/2008/05/vmwares-srm-cha.html" rel="nofollow noreferrer">http://chucksblog.typepad.com/chucks_blog/2008/05/vmwares-srm-cha.html</a></p>
17,175
<p>I want to be able to generate a highly graphical (with lots of text content as well) PDF file from data that I might have in a database or xml or any other structured form.</p> <p>Currently our graphic designer creates these PDF files in Photoshop manually after getting the content as a MS Word Document. But usually, there are more than 20 revisions of the content; small changes here and there, spelling corrections, etc.</p> <p>The 2 disadvantages are: 1) The graphic designer's time is unnecessarily occupied. The first version is the only one he/she should have to work on. 2) The PDF file becomes the document which now has the final revised content, and the initial content is out of sync with it. So if the initial content needs to be somewhere else (like on a website), we need to recreate it from the PDF file.</p> <p>Generating the PDF file will help me solve both these problems. Perhaps some way in which the graphic designer creates a "Template" and then puts in tags/holders and maps these tags/holders to the relevant data.</p> <p>Thanks :-)</p>
<p>There are some tools out there for doing this. XSL-FO is useful. <a href="http://cocoon.apache.org/2.1/howto/howto-html-pdf-publishing.html" rel="nofollow noreferrer">Here</a> is a tutorial for creating a pdf from xml (or xhtml) with cocoon. Also see <a href="http://xmlgraphics.apache.org/fop/" rel="nofollow noreferrer">Apache FOP</a>.</p> <p>You could format your SQL data as XML and still use the same templates this way.</p>
<p>You could look at doing the workflow in PostScript which is plain text that you can easily compose from fragments. Then you can use any <a href="http://www.cutepdf.com/Products/CutePDF/writer.asp" rel="nofollow noreferrer">free tool</a> to convert to PDF.</p>
14,138
<p>Why does the following have the effect it does - it prints a terminal full of random characters and then exits leaving a command prompt that produces garbage when you type in it. (I tried it because I thought it would produce a seg fault).</p> <p><img src="https://i.stack.imgur.com/kGkf4.png" alt="http://oi38.tinypic.com/r9qxbt.jpg"></p> <pre><code>#include &lt;stdio.h&gt; int main(){ char* s = "lololololololol"; while(1){ printf("%c", *s); s++; } } </code></pre> <p>it was compiled with:</p> <pre>gcc -std=c99 hello.c</pre>
<p>It will eventually seg fault, but before that it'll print out whatever bytes are in the same page. That's why you see random chars on the screen.</p> <p>Those may well include escape sequences to change (say) the character encoding of the console. That's why you end up with gibberish when you type on the console after it's exited, too.</p>
<p>Also, you can usually get back to your command prompt by using the 'reset' command, typing blindly of course. (type Enter, reset, Enter)</p>
36,591