instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>In a SQL-database I make some selects, that get an duration (as result of a subtraction between two dates) in seconds as an int. But I want to format this result in a human-readable form like 'hh:mm' or 'dd:hh'. Is that possible in SQL and how can I realize this?</p>
<p>In SQL 2005, You can use the following:</p> <pre><code> select convert(varchar(8), dateadd(second, [SecondsColumn], 0), 108) </code></pre> <p>Which first converts the seconds into a date after 1900-01-01, and then gets the hh:mm:ss part. </p> <p>If the column is more than 24 hours, this will roll over, if you want days and then hours in that case just do something like:</p> <pre><code>case when SecondsColumn&gt; (24*60*60) then cast(datepart(day,datediff(dd, 0, dateadd(second, SecondsColumn, 0))) as varchar(4)) + 'd' + convert(varchar(2), dateadd(second, SecondsColumn, 0), 108) else convert(varchar(8), dateadd(second, SecondsColumn, 0), 108) end </code></pre>
<p>There is no standard, though many DBMSs have their own custom syntax.</p> <p>In general it is better to be doing formatting-for-human-readability work in your application's presentation layer rather than anywhere near the database.</p>
23,962
<p>Looking at the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array" rel="noreferrer">mozilla documentation</a>, looking at the regular expression example (headed &quot;Creating an array using the result of a match&quot;), we have statements like:</p> <blockquote> <p>input: A read-only property that reflects the original string against which the regular expression was matched.</p> <p>index: A read-only property that is the zero-based index of the match in the string.</p> </blockquote> <p>etc... is it possible to create your own object in JavaScript which will have read-only properties, or is this a privilege reserved to built-in types implemented by particular browsers?</p>
<p><strong>Edit:</strong> Since this answer was written, a new, better way using <code>Object.defineProperty</code> has been standardized in EcmaScript 5, with support in newer browsers. See <a href="https://stackoverflow.com/questions/366047/can-read-only-properties-be-implemented-in-pure-javascript/2964881#2964881">Aidamina's answer</a>. If you need to support "older" browsers, you could use one of the methods in this answer as a fallback.</p> <hr> <p>In Firefox, Opera 9.5+, and Safari 3+, Chrome and IE (tested with v11) you can define getter and setter properties. If you only define a getter, it effectively creates a read-only property. You can define them in an object literal or by calling a method on an object.</p> <pre><code>var myObject = { get readOnlyProperty() { return 42; } }; alert(myObject.readOnlyProperty); // 42 myObject.readOnlyProperty = 5; // Assignment is allowed, but doesn't do anything alert(myObject.readOnlyProperty); // 42 </code></pre> <p>If you already have an object, you can call <code>__defineGetter__</code> and <code>__defineSetter__</code>:</p> <pre><code>var myObject = {}; myObject.__defineGetter__("readOnlyProperty", function() { return 42; }); </code></pre> <p>Of course, this isn't really useful on the web because it doesn't work in Internet Explorer.</p> <p>You can read more about it from <a href="http://ejohn.org/blog/javascript-getters-and-setters/" rel="noreferrer">John Resig's blog</a> or the <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Getters_and_Setters" rel="noreferrer">Mozilla Developer Center</a>.</p>
<p><a href="http://www.bobjs.com" rel="nofollow">bob.js framework</a> provides a way to declare read-only properties. Under the hood, it declares a private field and exposes the getter/setter functions for it. bob.js provides multiple ways of doing this same thing, depending on the convenience and specific goals. Here's one approach that uses object-oriented instance of the <code>Property</code> (other approaches allow defining setters/getters on the object itself):</p> <pre><code>var Person = function(name, age) { this.name = new bob.prop.Property(name, true); var setName = this.name.get_setter(); this.age = new bob.prop.Property(age, true); var setAge = this.age.get_setter(); this.parent = new bob.prop.Property(null, false, true); }; var p = new Person('Bob', 20); p.parent.set_value(new Person('Martin', 50)); console.log('name: ' + p.name.get_value()); console.log('age: ' + p.age.get_value()); console.log('parent: ' + (p.parent.get_value ? p.parent.get_value().name.get_value() : 'N/A')); // Output: // name: Bob // age: 20 // parent: N/A </code></pre> <p>At the end, <code>p.name.set_value</code> is not defined because that's a read-only property.</p>
47,781
<p>I'm using <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29#Releases" rel="noreferrer">Eclipse Ganymede</a>. Everything works fine, but I have an anal-retentive yearning for a warning-free Problems tab. Right now it (correctly) complains about my <a href="http://en.wikipedia.org/wiki/Apache_Ant" rel="noreferrer">Ant</a> scripts: "No grammar constraints (DTD or XML schema) detected for the document." Is there any way to turn that off for just those files? Ideally I'd like it to still warn me if my other schema-constrained files were missing the schema declarations.</p>
<p>The simplest is to supply a minimal DTD to shut it up.</p> <pre><code>&lt;!DOCTYPE project&gt; </code></pre> <p>for ant files</p>
<p>right click on the warning to delete it, then clean</p>
47,486
<p>So the chain of events is:</p> <ol> <li>The user submits a form.</li> <li>During the processing of the submission, there is a message generated, such as "Your record was saved."</li> <li>The user is redirected to a new page, say the search results.</li> <li>The new page needs to display the message.</li> </ol> <p>So, the question is how to get the message from step 2 to step 3? This is only one simple example...there are many other much more complicated examples.</p> <p>I am using PHP.</p> <p>Needs:</p> <ul> <li>supports multiple messages and need to be formatted on the receiving machine as required</li> <li>messages can be added on the same page (such as within step 4)</li> <li>messages added from inside any function or object</li> </ul> <p>Some options I have come up with:</p> <ul> <li>store in a session variable as an array and emptied after each display</li> <li>pass as a get or query parameter; can get annoying as you are constantly processing this and have to remember to get it; as it can get long, it could easily go over the max length of the query string</li> <li>store in the database on a per session basis (may not always be for a logged in user); this would require an extra insert on each page where they are added, possibly multiple, and an extra select on every page</li> </ul> <p>Currently I have been storing the messages in the session in an array, but I'm wondering if there is a better way. I don't think the other 2 options above are very good.</p> <p><strong>Edit:</strong> I use 2 functions for the session method: AddStatusMsg() (adds an element to the array) and DisplayStatusMsg() (returns an HTML formatted message and empties the array).</p>
<p>I would recommend AGAINST storing these messages either in the database or in the session, for one simple reason: tabs. (Well, really, the stateless nature of HTTP.)</p> <p>Think of a person who's got multiple tabs open of different sections of your website. This person performs some action and while that loads, switches to another tab and clicks on a link. If you're storing the messages in the session/database and the switched-to tab is a page that can display these messages too, the user has now entered a race condition where depending on which request the server responds to first, the messages may display where they were not intended.</p> <p>Now, there are some situations where this legitimately might not matter, but it could also be extremely confusing in some cases.</p> <p>Putting the messages in the request doesn't have to be as bad as it initially seems. Perhaps you could store all the messages you want to display in the database with a numeric (or, for bonus obfuscation, hash) ID, and pass a list of IDs in the query string. This keeps the query string short, and all you have to do is keep track of what ID corresponds to what message in your code.</p>
<p>Store it in the database as well as the session. This way the user can get to his history if he needs it, and you have easy access through the session data.</p> <p>Don't use a query parameter, it'll only confuse the user at some point when the message is displayed when it shouldn't be.</p> <p>Displaying the messages should be a part of your main template (in other words; done once).</p>
39,077
<p>I have a Button style and can't seem to property databind the border's CornerRadius property to the template. This is a dependency property, so it should be data bindable. I wonder if I'm missing the right XAML syntax to use?</p> <pre><code>&lt;Style TargetType="{x:Type Button}" BasedOn="{x:Null}"&gt; &lt;Setter Property="FocusVisualStyle" Value="{DynamicResource MyButtonFocusVisual}"/&gt; &lt;Setter Property="Background" Value="{DynamicResource MyButtonBackgroundBrush}"/&gt; &lt;Setter Property="Foreground" Value="{DynamicResource MyButtonForegroundBrush}"/&gt; &lt;Setter Property="BorderBrush" Value="{DynamicResource MyButtonBorderBrush}"/&gt; &lt;Setter Property="BorderThickness" Value="3"/&gt; &lt;Setter Property="FontFamily" Value="Segoe UI"/&gt; &lt;Setter Property="FontSize" Value="14" /&gt; &lt;Setter Property="CornerRadius" Value="2" /&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type Button}"&gt; &lt;!-- We use Grid as a root because it is easy to add more elements to customize the button --&gt; &lt;Grid x:Name="Grid"&gt; &lt;Border x:Name="Border" CornerRadius="{TemplateBinding CornerRadius}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"/&gt; &lt;/Grid&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>Both and CornerRadius="{TemplateBinding CornerRadius}" give me the error "CornerRadius is not recognized or is not accessible". </p>
<p>You're trying to set/bind a <code>CornerRadius</code> property on class <code>Button</code>, but there is no such property. So the error is expected.</p>
<p>Kent is right. A way around this is to create your own custom control that inherits from the button class. Then inside this derived class, create a dependency property and register it to the window for the CornerRadius property. Then you may use the above code, but instead of setting the style property on a Button control, set the style property on the derived class.</p>
42,496
<p>I need some help regarding algorithm for randomness. So Problem is.</p> <p>There are 50 events going to happen in 8 hours duration. Events can happen at random times. Now it means in each second there is a chance of event happening is 50/(8*60*60)= .001736. How can I do this with random generation algorithm?</p> <p>I can get random number </p> <pre><code>int r = rand(); double chance = r/RAND_MAX; if(chance &lt; 0.001736) then event happens else no event </code></pre> <p>But most of times rand() returns 0 and 0&lt;0.001736 and I am getting more events than required.</p> <p>Any suggestions?</p> <hr> <p>sorry I forget to mention I calculated chance as double chance = (static_cast )(r) / (static_cast)(RAND_MAX);</p> <hr> <p>It removed double from static_cast</p> <p>double chance = (double)r/(double)(RAND_MAX);</p>
<p>Both <code>r</code> and <code>RAND_MAX</code> are integers, so the expression</p> <pre><code>double chance = r / RAND_MAX; </code></pre> <p>is computed with integer arithmetic. Try:</p> <pre><code>double chance = 1.0 * r / RAND_MAX; </code></pre> <p>which will cause the division to be a floating point division.</p> <p>However, a better solution would be to use a random function that returns a floating point value in the first place. If you use an integer random number generator, you will get some bias errors in your probability calculations.</p>
<p>Why not create a 28,800 element list and pull 50 elements from it to determine the time of the events? This does assume that 2 events can't occur at the same time and each event takes 1 second of time. You can use the random number generator to generate integer values between 0 and x so that it is possible to pick within the limits.</p>
36,651
<p>I'm writing opengl code in python using the library pyglet. When I draw to the screen using pyglet.graphics.vertex_list or pyglet.graphics.batch objects, they are very slow (~0.1 fps) compared to plain old pyglet.graphics.draw() or just glVertex() calls, which are about 40fps for the same geometry. In Linux the vertex_list is about the same speed as glVertex, which is disappointing, and batch methods are about twice as fast, which is a little better but not as much gain as I was hoping for.</p>
<p>Don't forget to invoke your pyglet scripts with 'python -O myscript.py', the '-O' flag can make a huge performance difference.</p> <p>See pyglet docs <a href="https://pyglet.readthedocs.io/en/pyglet-1.3-maintenance/programming_guide/gl.html?highlight=performance#error-checking" rel="nofollow noreferrer">here</a> and <a href="https://pyglet.readthedocs.io/en/pyglet-1.3-maintenance/programming_guide/options.html?highlight=debug_gl" rel="nofollow noreferrer">here</a>.</p>
<p>I don't know personally, but I noticed that you haven't posted to <a href="http://groups.google.com/group/pyglet-users" rel="nofollow noreferrer">the pyglet mailing list</a> about this. More Pyglet users, as well as the primary developer, read that list.</p>
9,282
<p>I develop a web application that needs to be load balanced across 4 webservers. My company is purchasing the load balancer hardware (Cisco). There is confusion on how to tell the load balancer that a webserver should be in the rotation.</p> <p>The IT Hardware support team wants me to create a one page web application that will sit next to the main web application. I was told that this small one page app should call the database and do an INSERT, UPDATE, and DELETE on a table. Then the app should return a status code, which in turn the load balancer will be able to read and determine whether to keep this webserver in the rotation. This app will have to reside on all of the load balanced servers. The one page app would then be polled every 5 seconds by the load balancer.</p> <p>I think that this sounds like an absolute HACK. It sounds like unnecessary work and overhead on the database. The hardware team is trying to convince me that this is the right way to go. I completely DISAGREE! My argument is that the load balancer should not care about the database connection. We are only trying to distribute the load across the 4 webservers. One thing to note is that the Main Web Application is useless without its database connection. </p> <p>Does the load balancer itself have a way to determine if a server should be in the rotation? What is the correct way to do this?</p>
<p>Read <a href="https://rads.stackoverflow.com/amzn/click/com/067232699X" rel="nofollow noreferrer" rel="nofollow noreferrer">Scalable Internet Architectures</a>.</p> <p>The balancer can only see the web servers. If the web server appears up, but can't talk to the database (because, say, Apache is running but your app is broken), then you'll have a problem with the non-responsive server getting requests when the app is broken.</p> <p>We have a selftest app that returns some status. Currently used for debugging. In the future, will be used with other HA and load-sharing solutions.</p>
<p>I always put a real simple html page on the webserver. If the HTTP status from status.html comes back 200, then keep the server in the rotation, if not, suspend the web server.</p> <p>What if your DB goes down hard? while you are restoring, you should be able to place a status message that says "sorry, back soon". You don't want to have to reconfigure your load balancer as well. Is there no part of your application that can run without the DB?</p>
49,177
<p>I have a procedure with a lot of </p> <pre><code>i := i +1; </code></pre> <p>in it and I think </p> <pre><code> inc(i); </code></pre> <p>looks a lot better. Is there a performance difference or does the function call just get inlined by the compiler? I know this probably doesn't matter at all to my app, I'm just curious.</p> <p>EDIT: I did some gauging of the performance and found the difference to be very small, in fact as small as 5.1222741794670901427682121946224e-8! So it really doesn't matter. And optimization options really didn't change the outcome much. Thanks for all tips and suggestions!</p>
<p>Modern compilers optimize the code.<br> inc(i) and i:= i+1; are pretty much the same.</p> <p>Use whichever you prefer.</p> <p>Edit: As Jim McKeeth corrected: with Overflow Checking there is a difference. Inc does not do a range checking.</p>
<p>"On some platforms, Inc may generate optimized code, especially useful in tight loops." For optimized compiler such as Delphi it doesn't care. That is about old compilers (e.g. Turbo Pascal)</p>
16,821
<p>I have a set of callback classes that I use for handling callbacks with variable numbers of parameters. Right now I have about 6 different instances of it to handle differing numbers of arguments. Is there a way to make one instance than can handle a variable number of arguments?? Ultimately I would love to have each parameter be a POD type or a class pointer, or a struct pointer. Any ideas?</p> <pre><code>template &lt;class T&gt; class kGUICallBackPtr { public: kGUICallBackPtr() {m_obj=0;m_func=0;} void Set(void *o,void (*f)(void *,T *)); inline void Call(T *i) {if(m_func) m_func(m_obj,i);} inline bool IsValid(void) {return (m_func!=0);} private: void *m_obj; void (*m_func)(void *,T *); }; template &lt;class T,class U&gt; class kGUICallBackPtrPtr { public: kGUICallBackPtrPtr() {m_obj=0;m_func=0;} void Set(void *o,void (*f)(void *,T *,U *)); inline void Call(T *i, U *j) {if(m_func) m_func(m_obj,i,j);} inline bool IsValid(void) {return (m_func!=0);} private: void *m_obj; void (*m_func)(void *,T *,U *j); }; </code></pre>
<p>Not yet in the language itself but C++0x will have support for <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Variadic_templates" rel="nofollow noreferrer">variadic templates</a>.</p>
<p>How about sidestepping this issue through the use of <a href="http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html" rel="nofollow noreferrer">Boost Bind</a>? You could make your code accept a single argument, or none at all, and bind arguments you need at the call site.</p>
18,720
<p>I have the following code sample :</p> <pre><code>public class Base { public virtual void MyMethod(int param) { Console.WriteLine(&quot;Base:MyMethod - Int {0}&quot;, param); } } public class Derived1 : Base { public override void MyMethod(int param) { Console.WriteLine(&quot;Derived1:MyMethod - Int {0}&quot;, param); } public void MyMethod(double param) { Console.WriteLine(&quot;Derived1:MyMethod - Double {0}&quot;, param); } } class Program { static void Main(string[] args) { Base objB = new Base(); objB.MyMethod(5); Base objBD = new Derived1(); objBD.MyMethod(5); Derived1 objD = new Derived1(); objD.MyMethod(5); Console.ReadLine(); } } </code></pre> <p>The output of the above code is as follows:</p> <blockquote> <p>Base:MyMethod - Int 5</p> <p>Derived1:MyMethod - Int 5</p> <p>Derived1:MyMethod - Double 5</p> </blockquote> <p>For the third invocation of 'MyMethod' using 'objD' why is the 'DOUBLE' overload being used when I am actually passing it an INT.</p> <p>The second invocation using 'objBD' seems to behave correctly. Please suggest.</p>
<p>Oddly, I was discussing this with Jon the other evening! There is a precedence issue - the overridden method is <strong>defined</strong> in the base-class, so for "best method" purposes, the overload (even with an implicit cast) is preferable, since it is defined in the most-specific type (the subclass).</p> <p>If you re-declared the method (<code>new</code>), then it would get precedence, but you can't <code>override</code> and <code>new</code> a method with the same name and signature in the same type - you'd have to add an extra level of inheritance to achieve this.</p> <p>The exact logic for this is detailed in 14.5.5 and 14.4.2 of ECMA 334 v4.</p> <p>Basically, to make the base method callable, you'll either have to cast to the base-type, or add a shim method:</p> <pre><code>public void MyMethod2(int param) {base.MyMethod(param);} </code></pre>
<p>I'd guess that when calling MyMethod(5), 5 could be a double or an int as well and double has higher priority. Have you tried calling MyMethod((int)5)?</p>
49,432
<p>Doug McCune had created something that was exactly what I needed (<a href="http://dougmccune.com/blog/2007/05/10/analyze-your-actionscript-code-with-this-apollo-app/" rel="nofollow noreferrer">http://dougmccune.com/blog/2007/05/10/analyze-your-actionscript-code-with-this-apollo-app/</a>) but alas - it was for AIR beta 2. I just would like some tool that I can run that would provide some decent metrics...any idea's?</p>
<p>There is a Code Metrics Explorer in the Enterprise Flex Plug-in below:</p> <p><a href="http://www.deitte.com/archives/2008/09/flex_builder_pl.htm" rel="nofollow noreferrer">http://www.deitte.com/archives/2008/09/flex_builder_pl.htm</a></p>
<p>To get a rough estimate, you could always run <code>find . -type f -exec cat {} \; | wc -l</code> in the project directory if you're using Mac OS X. </p>
5,607
<p>I'd like something like</p> <pre><code>int minIndex = list.FindMin(delegate (MyClass a, MyClass b) {returns a.CompareTo(b);}); </code></pre> <p>Is there a builtin way to do this in .NET?</p>
<p>Try looking at these:</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb909313.aspx" rel="noreferrer">Min</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/bb909073.aspx" rel="noreferrer">Max</a></p> <p>As long as your class implements IComparable, all you have to do is:</p> <pre><code>List&lt;MyClass&gt; list = new List(); //add whatever you need to add MyClass min = list.Min(); MyClass max = list.Max(); </code></pre>
<p>Using Linq you have the Min() and Max() functions.</p> <p>So you can do <code>list.AsQueryable().Min();</code></p>
31,178
<p>I'm trying to make a combo box that behaves somewhat like the Firefox 3 Awesomebar, with the following behavior:</p> <ol> <li>Type in text</li> <li>Asynchronously bring back results</li> <li>Up and down selects results in the list, <strong>BUT</strong> leaves the text that was typed in the entry box so the user can continue editing to limit the resultset differently</li> <li>Enter fires an event that the parent form will handle</li> </ol> <p>I have the asynchronous results and filtering all working, but I don't have a good method for displaying and selecting within the results.</p> <p>A combo box automatically fills the entry box with what is selected when you arrow down. Fails #3.</p> <p>I've got the DevExpress controls, but their combo box does the same thing and I can't figure out how to override either.</p> <p>A LookupEdit does not allow typing arbitrary stuff. Neither does a PopupContainerEdit.</p> <p>I want behavior that's like a textbox with a listbox below it, and up/down events in the textbox get passed to the listbox. But if I try to make a custom control that combines the two like that, I have no clue how to "float" the listbox like the dropdown on a normal combo box.</p> <p>Clues much appreciated!</p>
<p>If you read the documentation, it says, "This member is not meaningful for this control." If you want the control to be drawn utilizing double-buffering, you'll have to implement it yourself. Besides the fact that if you owner-draw the control, you would have to implement double-buffering yourself anyhow.</p>
<p>Not sure, but you might try double-buffering the control that contains the tab control. </p>
27,616
<p>I have an NSDictionary (stored in a plist) that I'm basically using as an associative array (strings as keys and values). I want to use the array of keys as part of my application, but I'd like them to be in a specific order (not really an order that I can write an algorithm to sort them into). I could always store a separate array of the keys, but that seems kind of kludgey because I'd always have to update the keys of the dictionary as well as the values of the array, and make sure they always correspond. Currently I just use [myDictionary allKeys], but obviously this returns them in an arbitrary, non-guaranteed order. Is there a data structure in Objective-C that I'm missing? Does anyone have any suggestions on how to more elegantly do this?</p>
<p>The solution of having an associated NSMutableArray of keys isn't so bad. It avoids subclassing NSDictionary, and if you are careful with writing accessors, it shouldn't be too hard to keep synchronised.</p>
<p>I don’t like C++ very much, but one solution that I see myself using more and more is to use Objective-C++ and <code>std::map</code> from the Standard Template Library. It is a dictionary whose keys are automatically sorted on insertion. It works surprisingly well with either scalar types or Objective-C objects both as keys and as values.</p> <p>If you need to include an array as a value, just use <code>std::vector</code> instead of <code>NSArray</code>.</p> <p>One caveat is that you might want to provide your own <code>insert_or_assign</code> function, unless you can use C++17 (see <a href="http://stackoverflow.com/a/31792377/126192">this answer</a>). Also, you need to <code>typedef</code> your types to prevent certain build errors. Once you figure out how to use <code>std::map</code>, iterators etc., it is pretty straightforward and fast.</p>
49,217
<p>What I want to do is an outer join to a table, where I exclude records from the joined table based on matching a constant, however keep records from the main table. For example:</p> <pre><code>SELECT a.id, a.other, b.baz FROM a LEFT OUTER JOIN b ON a.id = b.id AND b.bar = 'foo' </code></pre> <p>Expected results:</p> <pre> id other baz -- ---------- ------- 1 Has foo Include 2 Has none (null) 3 Has foobar (null) </pre> <p>I can't get the same results by putting it in the filter condition. If I use the following:</p> <pre><code>SELECT a.id, a.other, b.baz FROM a LEFT OUTER JOIN b ON a.id = b.id WHERE (b.bar IS NULL OR b.bar = 'foo') </code></pre> <p>I get these incorrect results:</p> <pre> id other baz -- -------- ------- 1 Has foo Include 2 Has none (null) </pre> <p>Where it excluded records of A that happen to match a record of B where bar = 'foobar'. I don't want that, I want A to be present, but B to be nulls in that case.</p> <p>Table B will have multiple records that need excluding, so I don't think I can filter this on the Crystal side without doing a lot of messing around to avoid problems from duplicate records from table A.</p> <p>I cannot use a SQL command object, as the third party application that we are running the reports from seems to choke on SQL command objects.</p> <p>I cannot use views, as our support contract does not permit database modifications, and our vendor considers adding views a database modification.</p> <p>I am working with Crystal Reports XI, specifically version 11.0.0.895. In case it makes a difference, I am running against a Progress 9.1E04 database using the SQL-92 ODBC driver.</p> <p>The sample tables and data used in the examples can be created with the following:</p> <pre><code>CREATE TABLE a (id INTEGER, other VARCHAR(32)); CREATE TABLE b (id INTEGER, bar VARCHAR(32), baz VARCHAR(32)); insert into A (id, other) values ('1', 'Has foo'); insert into A (id, other) values ('2', 'Has none'); insert into A (id, other) values ('3', 'Has foobar'); insert into B (id, bar, baz) values ('1', 'foo', 'Include'); insert into B (id, bar, baz) values ('1', 'foobar', 'Exclude'); insert into B (id, bar, baz) values ('1', 'another', 'Exclude'); insert into B (id, bar, baz) values ('1', 'More', 'Exclude'); insert into B (id, bar, baz) values ('3', 'foobar', 'Exclude'); </code></pre>
<p>Crystal reports can't generate that commonly used SQL statement based on its links and report selection criteria. You have to use a "command" or build a view.</p> <p>In short, Crystal sucks. </p>
<p>Not sure if you can do this in Crystal but how about joining to a Select?</p> <pre><code>SELECT a.id, x.baz FROM a LEFT OUTER JOIN (SELECT id, baz FROM b WHERE bar = 'foo') As x ON a.id = x.id </code></pre>
27,978
<p>I'm using Repetier and Slic3r and it is printing a gap between the perimeter and infill on the first layer. Also, the infill is lifting (as in photo). Any advise?</p> <p><a href="https://i.stack.imgur.com/mXJCl.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/mXJCl.jpg" alt="infill issue"></a> </p>
<p>You're not sticking to your bed. Adjust your bed height. You are too far. Otherwise you are going too fast and or too hot.</p> <p>Calibrate the bed. Reduce speed. Then adjust temps. </p> <p>Also could be material contamination</p> <p>See this link for a visual troubleshooting.</p> <p><a href="http://reprap.org/wiki/Print_Troubleshooting_Pictorial_Guide" rel="nofollow">http://reprap.org/wiki/Print_Troubleshooting_Pictorial_Guide</a></p> <p><a href="http://support.3dverkstan.se/article/23-a-visual-ultimaker-troubleshooting-guide" rel="nofollow">http://support.3dverkstan.se/article/23-a-visual-ultimaker-troubleshooting-guide</a></p> <p>In addition use some gluestick. That will often solve these issues. Last but not least add a raft if it continues. Or just ignore it. My bet is temp is too hot. I also like to smash my first layer, but not everyone likes that technique as it causes elephant footing.</p>
<p>I found a solution that works for me.</p> <p>I have increased my first layer extrusion width to 250 %, reduced the print speed of perimeters to 30 mm/s, reduced the brim width to 1 and increased the infill/perimeter overlap to 30 %.</p> <p>This was PLA with heat bed off (no heating), printing on glass and using hairspray as an adhesive. Most of my settings were on default. (Repetier &amp; Slic3r).</p>
363
<p>Now that everyone is talking about MVC, I notice that the business rules are not being addressed. In the old days of the 3-tier architecture, The business rules were in the middle layer. Where do they fall in the new MVC?</p>
<p>At first brush, I'd say they belong in the model. The <a href="http://en.wikipedia.org/wiki/Model-view-controller" rel="noreferrer">MVC Entry on Wikipedia</a> seems to agree: "In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data". After all, by 'Business rules' we mean the functional algorithms and logic that encode the domain that your application is involved with, as opposed to input/output related logic. These core business-related logic does not - or should not- change based upon what is being displayed to the user (which is the domain of the View) or the user input (which is primarily received by the Controller).</p> <p>In my experience, asking this sort of question has been very revealing during the software development process: we found a large number of things that were considered 'business rules' by some people, but turned out to be something else. If it is not a true business rule, it might not belong to the model.</p>
<p>You guys are wrong the business rules live within the controller and not the model...</p>
26,056
<p>As far as I know (not much I'll admit), the currently popular programming paradigms are Object Oriented (Java, C#, Ruby) vs functional (F#). As someone who is mostly familiar with the first paradigm, I have several questions:</p> <ul> <li>Can a programmer simply stick with one paradigm all of his/her life? Or in other words, can all problems be reduced to nails for one hammer?</li> <li>If not, which tool is suited for which type of task? For instance: web-based vs desktop, creating beautiful and responsive interfaces, able to crunch data quickly, etc.</li> <li>Have people ever needed to learn a new paradigm? For my past two jobs, my workplaces required Java and C#. Are there workplaces that specifically use non-OO languages?</li> </ul> <p>Obviously, there are no "best" languages, but I'm wondering whether it's worth the investment of time and energy to learn a new paradigm. Thanks in advance!</p>
<p>"Or in other words, can all problems be reduced to nails for one hammer?" Yes. Period. Any programming language you are likely to run into will be as complete as all others. There's actually a formal definition of "completeness" for a programming language.</p> <p>"Have people ever needed to learn a new paradigm?" Always.</p> <p>There's actually a trick to following the ups and downs of the "paradigm shifts". Over the last 30 years of my career, I've seen that programming has grown from a relatively simplistic imperative/procedural model to a number of much richer models that include a better balance between process and data.</p> <p>I've noticed the following...</p> <p>Part of the driving force is the artificial intelligence community. Many of these "new models" started as AI knowledge representation schemes. They got traction there, then they trickled into more mainstream applications.</p> <p>The Entity Relationship model was originally for knowledge representation, not business transactions. The Object model, similarly, was for knowledge representation. Then the simulation folks found it. Now the rest of us have it.</p> <p>Here's my conclusion.</p> <p><strong>Software is Knowledge Representation.</strong></p> <p>Your choice of Paradigm or Model or Approach or Style is based on the answer to the following question:</p> <p>"How Can I Best Represent This Problem?"</p> <p>If the problem has objects and relationships, OO. If the problem has algorithms and transformations, maps, filters and reduces, Functional. If the problem is dynamic, changing and flexible, Dynamic. If the problem is static and will scale up rapidly, Static.</p>
<p>Developing the design and architecting skills with OOP in mind is the most desirable skillset for a great language agnostic career.</p> <p>The benifit when you code in Oops is both for the other team members out there and for the organization as a whole. Because the code will be understandable to all and if the developers quit the job, company doesnt need to worry much. In the other case if you follow functional style it will be real hard for others to understand what you have done.</p>
22,916
<p>I am new to 3D printing. I have just put together my own 3D printer with some help.</p> <p>I was advised I shouldn't print directly onto the aluminium plate - I assume it's aluminium.</p> <ol> <li><p>The manufacturer did give me a piece of matrix board (i.e. no cooper at all) to print on. Will this work well?</p></li> <li><p>If glass is better, does it have to cover the entire bed? My bed is 275 mm deep by 220 mm wide. I'm struggling to find glass for it that will come within the next few days. The only custom cut was on eBay and it's going to take over a week to arrive.</p></li> </ol>
<p>Obviously being in a rush can limit your options, but here are a few thoughts:</p> <p><strong>Quick solutions:</strong></p> <ul> <li><strong>Blue painters tape</strong> (as Carl mentioned) will work directly on your heated bed...assuming it's a flat piece of aluminum with the heating element under it. Your surface does need to be flat.</li> <li><strong>Acrylic plate</strong> will work but is best with no heat, or low heat. PLA sticks to it. It's easy to cut and easy to find at local hardware stores.</li> <li><strong>Scrap glass</strong> is fairly easy to find for free and it's <a href="https://youtu.be/cfdrgrOH50Y" rel="noreferrer">not that hard</a> to cut...or buy some at your local hardware store and have them cut it. Just be careful, it's sharp. You can sand the sharp edges (wet sandpaper) to make it safer. <strong>No, it doesn't have to cover the whole plate, but obviously covering the whole plate would normally be preferred.</strong></li> </ul> <p><strong>Better (but not as fast) solutions:</strong></p> <ul> <li><strong>Buy some custom tempered glass.</strong> I like <a href="https://www.onedayglass.com/" rel="noreferrer">One Day Glass</a> because they're fast and very capable. Like Tom says, many many people print on glass because it's nice and flat and stiff. It's also easy to clean and holds up well. You can print on the bare glass with many materials or use various preparations like PVA (glue stick or white glue diluted with water are popular), hairspray, or others.</li> <li><strong>Touch Screen Glass:</strong> Some people like replacement glass for tablets or touch screens because it has a hardened scratch-resistant surface. I've not tried it, but if you can find one that is the right size, it might be worth a shot.</li> <li><strong>Specialty products:</strong> There are many many print bed products out there that promise an easier/better printing experience. I've used a few that are okay...definitely better than blue painters tape, but I much prefer my current favorite...</li> <li><strong>My current favorite is PEI.</strong> Use a 3M 468MP adhesive sheet (it handles the heat well) to stick a thin sheet PEI (also sold under brand name Ultem) on top of your glass plate. I got this idea from Lulzbot and it's what they use on all of their printers. It works beautifully. Common filaments stick to it while it's hot and release easily while it's cool. For other filaments I just use PVA like I would over glass. For material printing tips and settings that work well on PEI beds, check out Lulzbot's site. When it starts wearing out or getting scuffed up, I just sand it with fine sandpaper and I'm good to go for another hundred prints or so.</li> </ul>
<p>I have been printing for over 2 years directly onto the 3 mm Aluminum heated bed platform using a touch of PVA based print adhesion spray 3DLAC or Dimafix (see e.g. <a href="https://3dprinting.stackexchange.com/a/6861/">this answer</a> on question "<a href="https://3dprinting.stackexchange.com/questions/3710/should-you-use-hairspray-on-a-metal-bed-3d-printer">Should you use hairspray on a metal bed 3D printer? </a>"). I've obtained best results with 3DLAC. Works like a charm! Always good adhesion and a very shiny and flat surface finish. I have not found any downsides of printing directly onto the Aluminum, I find it very easy as I do not have to fight that dreadful tape (application, bubbling, tearing, etc.). </p>
400
<p>I find myself needing to store public key certificates, and a single private key certificate for an in-house application.</p> <p>A member of our team suggested storing the X509 certificates in the database, instead of storing it in the windows certificate store, as we have been doing up until now. I don't like re-inventing the wheel, but I have to at least consider the idea. it would mean keeping our data more centralized, which is good, I suppose.</p> <p>The initial barriers that I can see are:</p> <ul> <li>The private key still needs to be stored somewhere, and I don't know if shoehorning it into a 'public key' table is a good idea. I don't like the idea of setting up a table for a single element, either. Perhaps just keep the private key as a local file? (.pfx file, for instance).</li> <li>Revocation Lists. We would probably have to set up a process to deal with revoked public keys.</li> </ul> <p>I don't have a lot of experience with X509 certificates, so, my question is: Are there any other problems we are likely to encounter storing public key certificates in a database, instead of going with the windows certificate store?</p> <p>It's worth bearing in mind that this application is going to be rolled out onto several business clients servers, so keeping all the data in a single place will make for easier backups. Oh, and the in-house app in question is being developed with C#..</p> <p>Thanks!</p>
<p>What is the purpose of your application?</p> <p>If you are handling all the crypto in your application, and can reference a PKCS#12 cert + private key file, then going the database route is probably fine.</p> <p>If you need to use Windows Crypto API to access the certs, then you'll probably want to keep using the built-in certificate store. You gain some advantages here as you can protect the private key on an external device, like a smart card or Hardware Security Module (HSM).</p> <p>You'll want to make sure that you go through a significant effort to protect the private key if you're storing everything on the local disk. Be sure to use a strong passphrase and use best practices to protect this passphrase in your app.</p>
<p>I would be reluctant to move the private key to any other location unless really necessary. Its not required if the key is being used for signing and would only be required if the key is being used for decrypting and you wish to archive it for the future. Even in this instance the certificate authority that issued the certificate would commonly be able to handle archival and recovery. This is certainly the case for the more popular CAs such as Microsoft and entrust. </p> <p>If you must store it then encrypt it using AES and a key that you are able to protect either in an HSM(Hardware Security Module) or on a smartcard. Do not leave this key in plain text (in a file or the registry).</p> <p>You would also wish to protect this key in transit between its generation location and the central database. SSL or VPN etc</p> <p>Revocation lists are published by the Certificate Authority in most environments, usually to an LDAP or the directory or both.</p>
20,980
<p>I have an application in which a gecko browser is embedded. The application is crashing when I try to access any https url's because nss is not properly initialised at this point. The crash is in PK11_TokenExists(). I want to block my browser from rendering https sites. If a user clicks on a https link I can block that load in OnStartURI() of nsIURIContentListener.But if the user types in say orkut.com I wont know in OnStartURI() whether its a http url or a https one(i.e. whether it will use SSL or not). I wanted to know how I can block https url's in such cases? </p> <p>Thanks jbsp72</p>
<p>I would first try to figure out why your application is crashing on HTTPS/SSL connections. I think it would be better to fix the crash than trying to avoid it.</p>
<p>You can implement this the following way:</p> <p>Implement the <code>OnStateChange</code> method of the <code>nsIWebProgressListener</code> interface.</p> <p>Check the parameter <code>aStateFlags</code>: If this parameter contains the flags <code>STATE_IS_DOCUMENT</code> and <code>STATE_START</code>, then a new location is being navigated to.</p> <p>To find out the URL, use the parameter <code>aRequest</code>. It has type <code>nsIRequest</code>, but cast it to type <code>nsIChannel</code>. Then read the <code>URI</code> property. This contains the URL being navigated to.</p> <p>In case the URI starts with "https", abort the navigation by calling the <code>cancel</code> method of the parameter <code>aRequest</code>, passing <code>NS_BINDING_ABORTED</code> as a parameter.</p>
12,627
<p>I am looking into streaming binary data into a browser (through http). I am looking for opinions as to good ways to go about doing this. Ultimately I will have a real time data source and I would like to manipulate this data and display it (in real-ish time) in a browser. Firefox comes first, IE would be nice... but I'm not that picky. I have a firefox plugin that does what I need, but I would prefer something written in javascript/html that would work without the user having to install any plugins.</p> <p>I've been looking at the multipart/x-mixed-replace MIME/media type and it looks like it might be useful in this project, but I wanted to hear opinions on better ways to do this (if any) before I spend too many hours going down this path.</p> <p>Flash would probably get the job done, but again, I'd like to avoid plugins. I'd like to have the simplest solution possible (don't we all?), ideally with just javascript/html.</p> <p>I've also been looking into Comet to see what that can do for me.</p>
<p>A lot of this depends on what you want to do with the data. I assume render it.</p> <p>Flash probably would be the simplest solution. It's a common enough add-on that just about everyone should have it by now; so you're not running much of a risk for incompatibility.</p> <p>JavaScript just hasn't been considered much of a good platform for binary data handling -- so, there hasn't been too much development in the realm. I don't think you're going to find a lot of help for what you want. Especially when you get the point of rendering -- unless you can <em>maybe</em> convert every binary file to a <a href="http://en.wikipedia.org/wiki/Canvas_(HTML_element)" rel="nofollow noreferrer">canvas script</a>, since it's about the only dynamic imaging available in JavaScript.</p> <p>IE might actually be the exception, since you might be able to use some ActiveX objects to accomplish this for a few file types. But, then you cut out most other browser.</p>
<p>You can use Base64 to convert the binary to text and send that to the browser. With IE you can convert it directly to binary, but I'm not sure if you can do it with Firefox and others. I did see jscripts for Base64 enflate/deflate and a script named base64.js which probably does the conversion as well.</p> <p>However, you are probably better off converting the binary data into JSON and using AJAX to transfer the data and then processing it as a javascript object in the browser. The web server would be responsible for acquiring the data and converting it to JSON, so you should be able to process the binary regardless of which programming language you are using.</p>
44,449
<p>How can I restore a mysql database that was dropped using a "drop database" command? I have access to binary logs which should make this type of rollback possible.</p>
<p>Documentation Sucks. It alludes to DROP DATABASE being recoverable, but only in odd conditions i'm not familiar with <a href="http://dev.mysql.com/doc/refman/5.0/en/binary-log.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/binary-log.html</a> </p> <p>According to Docs, binlogs are just a sequence of commands executed based on a given reference point. So that when you did "DROP DATABASE", instead of going "Oh, hes droppping the database, we should back up now just in case" it merely wrote a "DROP DATABASE" to the last binlog. Recovery is not as simple as playing the tape backwards. </p> <p>What you need to do is recover the database from a last-known-good, and apply the binlogs that happened between that recover point and the DROP command.</p> <p><a href="http://dev.mysql.com/doc/refman/5.0/en/recovery-from-backups.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/recovery-from-backups.html</a></p> <p>How one determines which binlogs to use tho, unclear. </p> <p>There is nothing better than having full file system backups. And you should at least have these to fall back to.</p>
<p>No backup no party.</p> <p>So I'll answer:</p> <p>To never be in your situation again install the ultra simple and ultra powerful automysqlbackup (if you're on linux):</p> <p>sudo apt-get install automysqlbackup</p> <p>configure it:</p> <p>sudo nano /etc/default/automysqlbackup</p> <p>Then upload its content automatically to dropbox, ubuntu one or similar.</p> <p>Only then live happily :)</p>
11,447
<p>We're usually 1-4 developers / art directors / copywriters on each project at my firm, what methodology would you recommend use to use? Agile? XP? Scrum? Something else? (I know they are all variations of essentially the same concept, yes)</p>
<p>I don't think there's a general answer for it, the question is too broad, and you can't just "adopt a methodology" as if it were a product that you take out of the box, it's something that you evolve over time...but in any case I highly recommend you getting a copy of this book: <a href="https://rads.stackoverflow.com/amzn/click/com/0596527357" rel="noreferrer" rel="nofollow noreferrer">Head First Software Development</a></p> <p>Then you adapt the ideas you like into your project. Don't worry about names and buzzwords, they will be all "passé" next year anyway. <strong>Keep it simple</strong> at first, adopt the ideas that make more sense and give the most bang for buck, and don't try to solve problems that don't exist yet. It will be a very good start.</p>
<p>They are very close to business side which is bad thing because programmers often do not understand well implications of accounting, time or risk management, etc. Even if they think they do. They see business as another attractive opportunity to improve their sophisticated technical skills. As company is small it is may be overkill to implement complex methodologies inside development team. They can handle technical questions easily themselves. What they cannot handle is understanding that if they are close to business environment does not mean they are not programmers anymore.</p> <p>I suggest to implement some simple policies which would ensure discipline and focus on technical side rather then talking with customers about technical topics which is what some programmers like so much.</p>
41,947
<p>What books or online resource would you recommend for learning how to do advanced charts and dashboard design with Reporting Services? </p>
<p>While not specific to SSRS <a href="http://www.edwardtufte.com/tufte/books_vdqi" rel="nofollow noreferrer">The Visual Display of Quantitative Information</a> is the place to start.</p>
<p>SSRS might not be the best approach for a dashboard, though it offers great reporting functionality.</p> <p>You may want to take a look at Microsoft PerformancePoint 2007. It can make dashboards and widgets out of SSRS, SQL, Excel etc data and display it visually on Sharepoint.</p>
15,276
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/188444/reading-writing-ms-word-files-in-python">Reading/Writing MS Word files in Python</a> </p> </blockquote> <p>I know there are some libraries for editing excel files but is there anything for editing msword 97/2000/2003 .doc files in python? Ideally I'd like to make some minor changes to the formatting of the text based on the contents of the text. A really trivial example would be highlighting every word starting with a capital.</p>
<p>Why not look at using <a href="http://wiki.services.openoffice.org/wiki/Python" rel="nofollow noreferrer">python-uno</a> to load the document into OpenOffice and manipulate it using the UNO interface. There is some example code on the site I just linked to which can get you started.</p>
<p>The <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="nofollow noreferrer">PyWin32</a> library allows you to access COM objects from Python, including all of the various Office COM APIs. I won't claim it's <strong>easy</strong> to use, but it does work.</p>
49,236
<p>I may be in the minority here, but I very much enjoy <a href="https://perldoc.perl.org/perlform" rel="nofollow noreferrer">Perl's formats</a>. I especially like being able to wrap a long piece of text within a column (&quot;~~ ^&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&quot; type stuff). Are there any other programming languages that have similar features, or libraries that implement similar features? I am especially interested in any libraries that implement something similar for Ruby, but I'm also curious about any other options.</p>
<p><a href="http://formatr.rubyforge.org/" rel="noreferrer">FormatR</a> provides Perl-like formats for Ruby.</p> <p>Here is an example from the documentation:</p> <pre><code>require "formatr" include FormatR top_ex = &lt;&lt;DOT Piggy Locations for @&lt;&lt; @#, @### month, day, year Number: location toe size ------------------------------------------- DOT ex = &lt;&lt;TOD @) @&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; @#.## num, location, toe_size TOD body_fmt = Format.new (top_ex, ex) body_fmt.setPageLength(10) num = 1 month = "Sep" day = 18 year = 2001 ["Market", "Home", "Eating Roast Beef", "Having None", "On the way home"].each {|location| toe_size = (num * 3.5) body_fmt.printFormat(binding) num += 1 } </code></pre> <p>Which produces:</p> <pre><code> Piggy Locations for Sep 18, 2001 Number: location toe size ------------------------------------------- 1) Market 3.50 2) Home 7.00 3) Eating Roast Beef 10.50 4) Having None 14.00 5) On the way home 17.50 </code></pre>
<p>There is the <a href="http://gigamonkeys.com/book/a-few-format-recipes.html" rel="nofollow noreferrer">Lisp <code>(format ...)</code> function</a>. It supports looping, conditionals, and a whole bunch of other fun stuff.</p> <p>for example (copied from above link):</p> <pre><code>(defparameter *english-list* "~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~}") (format nil *english-list* '()) ;' ==&gt; "" (format nil *english-list* '(1)) ;' ==&gt; "1" (format nil *english-list* '(1 2)) ;' ==&gt; "1 and 2" (format nil *english-list* '(1 2 3)) ;' ==&gt; "1, 2, and 3" (format nil *english-list* '(1 2 3 4));' ==&gt; "1, 2, 3, and 4" </code></pre>
29,282
<p>How can I make a SQL Compact 2008 application for the desktop? I know how to connect to a .SDF file with SQL Management Studio 2008, but I can't figure out how to connect to it with my app. I have seen tutorials about this and I can see in the C# code they are referencing some special namespaces, but I can't seem to get it to work. What I did is download the Microsoft SQL Compact SDK but I get an error whenever I try to add references to any of the DLL's that came with it. Does anyone know where I can find the correct binaries for this.</p>
<p>Have you <a href="http://msdn.microsoft.com/en-us/library/aa983341.aspx" rel="nofollow noreferrer">gone here and downloaded all the components</a> listed (including the design tools)?</p> <p>If you post the "error" you get it might be easier to diagnose your problem.</p>
<p>You need to download SQL Sever Compact 3.5.</p> <p>Then you could create a LINQ2SQL model (dbml) using the sqlmetal tool that comes with the .NET SDK (and Visual Studio). Currently it is not possible to create LINQ2SQL classes for the compact framework inside Visual Studio, but you will be able to view and edit them.</p> <p>I haven't got much time now, as I really need to get going, but I hope this gets you started.</p> <p>PS: References in my project are System.Data, System.Data.Linq and System.Data.DataSetExtensions</p> <p>UPDATE: </p> <p>As for the DLL's you are referencing... I don't think they are .NET assemblies but native win32 DLL's intended to be used by C++ developers.</p>
31,686
<p>What is a good way to create and read an OpenOffice spreadsheet in Perl?</p>
<p>I think that the open office native document format is based around the OpenDocument specifications, and is bascially a zip compressed XML format. This being true you could probably manipulate it using your perl XML manipulation tools of choice. </p> <p>Alternatively, there's the <a href="http://search.cpan.org/perldoc?OpenOffice::OODoc::Intro" rel="noreferrer">Open Office OpenDocument Connector suite of modules on the CPAN</a> which offers a high level API to the OpenDocument spec. </p> <p>To my knowledge, the table methods in these modules should allow for both reading and writing data in OO Calc documents.</p>
<p>This is with version 2.4, because the latest version is unstable. It does work with the latest though sometimes. This will allow realtime DDE features in Calc as opposed to manipulating files. This is using Cygwin Perl on XP but should work with others. I just want to say the Excel VBA programming API is 10 times better and 10 times less confusing. That is pretty bad. </p> <p>[code]</p> <pre><code>use Win32::OLE; Win32::OLE-&gt;Option(Warn =&gt; 3); # Turn on warnings for easier debugging #Win32::OLE-&gt;GetActiveObject # Get the currently running process or create a new one $objServiceManager = Win32::OLE-&gt;GetActiveObject("com.sun.star.ServiceManager") || Win32::OLE-&gt;new("com.sun.star.ServiceManager") || die "CreateObject: $!"; $Stardesktop = $objServiceManager-&gt;createInstance("com.sun.star.frame.Desktop"); # $Stardesktop-&gt;terminate();exit; # will kill ALL OpenOffice docs!!! # Doc = StarDesktop.loadComponentFromURL(sURL, "_default", 0, aMediaDesc) $propValue[0] = $objServiceManager-&gt;Bridge_GetStruct("com.sun.star.beans.PropertyValue"); $propValue[0]-&gt;{Name} = "Hidden"; # This does not work! $propValue[0]-&gt;{Value} = 1; #Open the file and update its links if you have DDE links in your file $propValue[1] = $objServiceManager-&gt;Bridge_GetStruct("com.sun.star.beans.PropertyValue"); $propValue[1]-&gt;{Name} = "UpdateDocMode"; $propValue[1]-&gt;{Value} = 3; # com.sun.star.document.UpdateDocMode.FULL_UPDATE $calc = $Stardesktop-&gt;loadComponentfromUrl("file:///C:/Documents and Settings/Chloe/Desktop/MyFile.ods", "MyCalc", 0, \@propValue ); # load a new blank spreadsheet $calc = $Stardesktop-&gt;loadComponentFromURL( "private:factory/scalc", "_blank", 0, [] ); # How to hide, as loading the document hidden does not work. $calc-&gt;getCurrentController-&gt;getFrame-&gt;getContainerWindow()-&gt;setVisible(0); $oSheet = $calc-&gt;getSheets-&gt;getByIndex(0); # how to execute an UNO command, such as menu items # http://wiki.services.openoffice.org/wiki/Framework/Article/OpenOffice.org_2.x_Commands $frame = $calc-&gt;getCurrentController-&gt;getFrame; $dispatchHelper = $objServiceManager-&gt;createInstance("com.sun.star.frame.DispatchHelper"); $dispatchHelper-&gt;executeDispatch( $frame, ".uno:CalculateHard", #".uno:UpdateAll", #".uno:UpdateAllLinks", #".uno:DataAreaRefresh", "_self", 0, [] ); $row = 5; $cellValue = $oSheet-&gt;getCellByPosition(0, $row)-&gt;getString(); # get a cell value # sort in decending order $range = $oSheet-&gt;getCellRangeByName("A1:P$row"); $fields[0] = $objServiceManager-&gt;Bridge_GetStruct("com.sun.star.table.TableSortField"); $fields[0]-&gt;{Field} = 7; # column number $fields[0]-&gt;{IsAscending} = 0; $unoWrap = $objServiceManager-&gt;Bridge_GetValueObject; $unoWrap-&gt;Set ("[]com.sun.star.table.TableSortField", \@fields); $sortDx = $range-&gt;createSortDescriptor(); $sortDx-&gt;[0]-&gt;{Name} = "ContainsHeader"; $sortDx-&gt;[0]-&gt;{Value} = 1; $sortDx-&gt;[3]-&gt;{Name} = "SortFields"; $sortDx-&gt;[3]-&gt;{Value} = $unoWrap; #$sortDx-&gt;[3]-&gt;{Value} = \@fields; # You would think this would work? It doesn't. $range-&gt;sort($sortDx); # create a new sheet to paste to $calc-&gt;getSheets-&gt;insertNewByName("NewSheet", 1 ); $sheet2 = $calc-&gt;getSheets-&gt;getByIndex(1); $calc-&gt;CurrentController-&gt;Select($sheet2); # copy row $pasteHere = $sheet2-&gt;getCellByPosition(0, 0)-&gt;CellAddress; $copyRange = $oSheet-&gt;getCellRangeByName("A1:Q1")-&gt;RangeAddress; $oSheet-&gt;copyRange($pasteHere, $copyRange); $cellValue = $sheet2-&gt;getCellByPosition(16, $row)-&gt;getValue()); # get cell value as integer $date = $sheet2-&gt;getCellByPosition(5, $row)-&gt;getString(); # must get dates as strings $calc-&gt;getCurrentController-&gt;getFrame-&gt;getContainerWindow()-&gt;setVisible(1); # set visible $calc-&gt;close(0); # close program window #print Win32::OLE-&gt;LastError, "\n"; </code></pre> <p>[/code]</p>
35,110
<p>Does anyone know a good way to do this? I need to have simple forms that submit to email without writing a lot of code. These forms will be hosted in content-viewer web parts or similar in MOSS 2007. I'd like to avoid using InfoPath.</p>
<p>You could use a list which would give you the input form.</p> <p>It depends on a) whether people should be able to see each other's submissions and b) who the e-mail should go to.</p> <p>You could set an alert (Actions -> Alert Me) to send an e-mail to a person/people when a new item is added to the list.</p> <p>In Settings -> List Settings -> Advanced Settings, there's the options for which items a user can see/edit. Alerts however cannot be set on lists where users can only see their own items. In this case, I would use a simple workflow to send the e-mail. I've only worked with MOSS 2007 and SharePoint Designer though - I'm not sure about WSS.</p>
<p>With the sharepoint sdk, you can create your own webparts. If you add them to the GAC you can include them on your sharepoint site. You'd of course have to build a webpart for emailing though.</p>
8,917
<p>I am getting the following error when I try to call a stored procedure that contains a SELECT Statement:</p> <blockquote> <p>The operation is not valid for the state of the transaction</p> </blockquote> <p>Here is the structure of my calls:</p> <pre><code>public void MyAddUpdateMethod() { using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew)) { using(SQLServer Sql = new SQLServer(this.m_connstring)) { //do my first add update statement //do my call to the select statement sp bool DoesRecordExist = this.SelectStatementCall(id) } } } public bool SelectStatementCall(System.Guid id) { using(SQLServer Sql = new SQLServer(this.m_connstring)) //breaks on this line { //create parameters // } } </code></pre> <p>Is the problem with me creating another connection to the same database within the transaction?</p>
<p>After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:</p> <pre><code>public void MyAddUpdateMethod() { using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew)) { using(SQLServer Sql = new SQLServer(this.m_connstring)) { //do my first add update statement } //removed the method call from the first sql server using statement bool DoesRecordExist = this.SelectStatementCall(id) } } public bool SelectStatementCall(System.Guid id) { using(SQLServer Sql = new SQLServer(this.m_connstring)) { //create parameters } } </code></pre>
<p>You can't have two transactions open at the same time. What I do is that I specify <strong>transaction.Complete()</strong> before returning results that will be used by the 2nd transaction ;)</p>
23,480
<p>I need to do a modulus operation on very large integers. The biggest integer supported by my platform (edit: .NET 2.0) is a 64 bit integer, which aren't big enough for the numbers I'm working with.</p> <p>How can I do a modulus on really big integers, like 12654875632126424875387321657498462167853687516876876?</p> <p>I have a solution that treats the number as a string and works it in pieces one by one, but I wanted to know if there's a better way.</p> <p>Here's my function treating the number as a string. It basically does long division the way you'd do it by hand.</p> <pre><code> Public Function MyMod(ByVal numberString As String, ByVal modby As Integer) As Integer Dim position As Integer = -1 Dim curSubtraction As Integer = 0 While position &lt; numberString.Length - 1 position += 1 curSubtraction = curSubtraction * 10 + CInt(numberString.Substring(position, 1)) If (curSubtraction / modby) &lt; 1 And position = numberString.Length - 1 Then Return curSubtraction ElseIf (curSubtraction / modby) &lt; 1 Then Continue While Else curSubtraction = curSubtraction Mod modby End If End While Return curSubtraction End Function </code></pre> <p>Is there a cleaner, more efficient way?</p> <p>EDIT: To clarify, the integers are coming from IBAN bank account numbers. According to the specification, you have to convert the IBAN account number (containing letters) into one integer. Then, you do a modulus on the integer. So, I guess you could say that the real source of the integer to perform the modulus on is a string of digits.</p>
<p>You haven't specified where the numbers are coming from, but you might be able to make some simplifications. If the numbers are originally smaller, then consider things like:</p> <pre><code>(a + b) MOD n = ((a MOD n) + (b MOD n)) MOD n </code></pre> <p>or</p> <pre><code>ab MOD n = (a MOD n)(b MOD n) MOD n </code></pre>
<p>You need an arbitrary-precision integer math library such as <a href="http://www.codeplex.com/IntX/" rel="nofollow noreferrer">IntX</a>.</p>
35,163
<p>I'm subclassing a native window (the edit control of a combobox...)</p> <p>oldWndProc = SetWindowLong(HandleOfCbEditControl, GWL_WNDPROC, newWndProc);</p> <p>In my subclassing wndproc, I'll have code like this, right, but I can't figure out the syntax for calling the oldWndProc.</p> <pre><code> int MyWndProc(int Msg, int wParam, int lParam) { if (Msg.m == something I'm interested in...) { return something special } else { return result of call to oldWndProc &lt;&lt;&lt;&lt; What does this look like?*** } } </code></pre> <p>EDIT: The word "subclassing" in this question refers to the WIN32 API meaning, not C#. Subclassing here doesn't mean overriding the .NET base class behavior. It means telling WIN32 to call your function pointer instead of the windows current callback. It has nothing to do with inheritence in C#.</p>
<p>You'll call <a href="http://msdn.microsoft.com/en-us/library/aa452919.aspx" rel="nofollow noreferrer">CallWindowProc</a> by P/Invoke. Just define the parameters as int variables (as it looks like that's how you defined them in the SetWindowLong call), so something like this:</p> <p>[DllImport("CallWindowProc"...] public static extern int CallWindowProc(int previousProc, int nativeControlHandle, int msg, int lParam, int wParam);</p> <p>Remember, that for marshaling, int, uint and IntPtr are all identical.</p>
<p>This <a href="http://www.pinvoke.net/" rel="nofollow noreferrer">site</a> will be very helpful with all of your interop/p-invoke efforts (<a href="http://www.pinvoke.net/default.aspx/user32/SetWindowLong.html" rel="nofollow noreferrer">SetWindowLong</a>)</p>
24,528
<p>What is your favorite technique for launching a windbg user-mode remote debugging session? Why is do you prefer this technique over other techniques? (pros/cons)</p> <p>There are at least four different ways to do user-mode remote debug using windbg, as documented in the "Remote Debugging" section of the debugging tools for windows help file.</p> <ol> <li>run app on target then attach to it from the host windbg</li> <li>have the host windbg use remote.exe to launch the app on the target</li> <li>have the "smart client" host windbg launch the app on the target via a process server that is running on the target</li> <li>run a windbg instance on the target machine using the option "-server" to automatically start a server, then connect to the server from a 2nd machine.</li> </ol>
<p>There is no "the best" solution. Each of the possibilities has advantages and disadvantages and it's good to understand all of them. It depends on several factors like:</p> <ul> <li>where are the symbols located</li> <li>which PC has access to the Internet to download the OS symbols</li> <li>what amount of data may you copy to the server (clients often accept better if it's just a single Exe)</li> <li>what's the bandwidth between client and server</li> <li>do you need other commands that just CDB/WinDbg, e.g. access to CMD, then consider remote.exe</li> <li>who's available on the server side, a debugging expert whom you can easily tell a lot of cryptic commands or a normal user who barely knows how to start a command prompt</li> <li>are both sides in a private network, so you need a "man in the middle" server to be able to access each other (or port forwarding as an alternative, which IT guys don't want and it may take days to get it set up)</li> </ul> <p>From those 4 options, don't forget that clients often want to see exactly what you do, so they require an RDP session, Teamviewer or similar. That's something they understand.</p>
<p>Option 1 is my favourite because it is the simplest. I get to launch the app in the normal way without worry about getting WinDbg to set the right working directory, pass any command line arguments, etc.</p> <p>Fortunately I've not run into any cases where this hasn't worked!</p>
7,620
<p>I've become very comfortable in the world of pointer-free, garbage-collected programming languages. Now I have to write a small Mac component. I've been learning Objective-C, but as I confront the possibility of dangling pointers and the need to manage retain counts, I feel disheartened.</p> <p>I know that Objective-C now has garbage collection but this only works with Leopard. My component must work with Tiger, too.</p> <p>I need to access some Cocoa libraries not available to Java, so that rules out my usual weapon of choice.</p> <p>What are my alternatives? Especially with no explicit pointers and automatic garbage collection.</p>
<p>What do you mean by "component?" Do you mean a chunk of code or a library you are going to hand to other people to link into their apps? If so then it is not realistic to use any of the bridged languages at this time. While a lot of the bridges are very nice, they almost always have complications and issues that most app developers will not be willing to deal with to use a single component, especially if it involves bringing in a substantial runtime.</p> <p>The bridges are most valuable to bridge other language libraries into your Objective C app. While you can write fairly complete apps using them, doing so often requires a better understanding of Objective C than simply writing an Objective C application, since you need to understand and cope with the language, object model, threading, and memory allocation impedance mismatches that occur. </p> <p>This is also why many people argue that even if you are quite familiar with a language, trying to learn Cocoa using that language through a bridge is generally more difficult that learning it using Objective C.</p> <p>Finally, much of the recent support for bridged languages was due to "BridgeSupport," a feature was added in Leopard. Even bridges that predate that have been migrating towards, sometimes in such a way that using the bridged language on Tiger and Leopard can have substantial differences. Also, there is currently no bridge support for iPhone, and most bridged languages will not work on it, if that is an issue.</p> <p>Ultimately, if you are writing a library that is going to be linked into other apps, you need to run on Tiger and Leopard, and you need to access Cocoa only APIs I think you will find using any non-Objective C solution quite difficult.</p>
<p>Look at <a href="http://www.python.org" rel="nofollow noreferrer">Python</a> and <a href="http://wxpython.org/" rel="nofollow noreferrer">wxPython</a> (the wxWidgets in Python).</p> <p>The wxWidgets have a very elegant App-Doc-View application design pattern that's very, very nice. It's not used enough, IMO. I haven't found any wxPython examples of this App-Doc-View example, so you have to use the C examples to reason out how it would work in Python.</p> <p>I'd post examples, but I haven't got it all working yet, either. </p>
33,667
<p>Which is better (for the user, for longevity, for performance, for whatever) to have:</p> <p>http://{site}/{login} e.g. <a href="http://wildobs.com/adam_jack" rel="nofollow noreferrer">http://wildobs.com/adam_jack</a></p> <p>or</p> <p>http://{site}/user/{login}</p> <p>Pros of former:</p> <ul> <li>User feels more special.</li> <li>URLs are shorter.</li> </ul> <p>Cons of former:</p> <ul> <li>Cannot have users w/ logins matching keywords, and keywords likely grow over time.</li> </ul> <p>Clearly this is important to get right (or get wrong and stick to) since all user define URLs are based off it. Changing it would seem site suicide.</p> <p>Do the cons (especially over time) outweigh the pros?</p>
<p>I would say the cons outweigh the pros, so go with /user/login over /login. Consider stackoverflow, since it's MVC as well: I think it's easier to program knowing that everything in /user/blah will always refer to a user, whereas if you don't do this you'll have to consider every possibility.</p> <p>For example, in site/foo, foo could be a username, admin page, or some other keyword. It's much easier to deal with if you properly segment everything all out so you know if you see site/user/foo it's always a user named foo.</p>
<p>Personally I'd go for /user/{login}</p> <p>Using /{login} feels too much like cluttering up the global namespace, and we all know globals are bad ;)</p>
26,255
<p>I've uploaded a bunch of images to Amazon S3, and now want to add a Cache-Control header to them. </p> <p>Can the header be updated without downloading the entire image? If so, how?</p>
<p>It's beta functionality, but you can specify new meta data when you <a href="http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?RESTObjectCOPY.html" rel="noreferrer">copy an object</a>. Specify the same source and destination for the copy, and this has the effect of just updating the meta data on your object.</p> <pre><code>PUT /myObject HTTP/1.1 Host: mybucket.s3.amazonaws.com x-amz-copy-source: /mybucket/myObject x-amz-metadata-directive: REPLACE x-amz-meta-myKey: newValue </code></pre>
<p>Here is a helping code in Python. <div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import boto one_year = 3600*24*365 cckey = 'cache-control' s3_connection = S3Connection() bucket_name = 'my_bucket' bucket = s3_connection.get_bucket(bucket_name validate=False) for key in bucket: key_name = key.key if key.size == 0: # continue on directories continue # Get key object key = bucket.get_key(key_name) if key.cache_control is not None: print("Exists") continue cache_time = one_year #set metdata key.set_metadata(name=cckey, value = ('max-age=%d, public' % (cache_time))) key.set_metadata(name='content-type', value = key.content_type) # Copy the same key key2 = key.copy(key.bucket.name, key.name, key.metadata, preserve_acl=True) continue </code></pre> </div> </div> </p> <p>Explanation: Code adds new metadata to the existing key and then copies the same file.</p>
33,909
<p>The developer environment db server is SqlServer 2005 (developer edition)</p> <p>Is there any way to make sure my SQL Queries will run in SqlServer 2000?</p> <p>This database is set to Compatibility level "SQL Server 2000 (80)" but some queries that run without problems in the development system can not run in the Test Server (SqlServer).</p> <p>(The problems seems to be in subqueries)</p>
<p>Compatibility levels are designed to work the opposite way - to allow an older version of T-SQL code to work without modifications on a newer version of SQL Server. The changes typically involve T-SQL syntax and reserved words, and it's possible to use SQL Server 2005 features such as INCLUDED columns in indexes on a database in Compatibility Level 80. However, you can't use 2005 T-SQL features such as CROSS APPLY.</p> <p>Your best option is to develop/test all your code against a SQL Server 2000 instance. Note that you can use 2005's Management Studio to connect to the SQL Server 2000 instance, so you don't have to go backwards with regards to tools.</p>
<p>Problem solved:</p> <p>In correlated subqueries you have to (in SQL2000) explicitly define the external field.</p> <p>SQL2005:</p> <pre>SELECT * FROM Loans WHERE EXISTS (SELECT * FROM Collaterals WHERE COLLATERAL_LOAN=LOAN_NUMBER) </pre> <p>SQL2000:</p> <pre>SELECT * FROM Loans WHERE EXISTS (SELECT * FROM Collaterals WHERE COLLATERAL_LOAN=Loans.LOAN_NUMBER) </pre>
41,875
<p>Is a new (or different) instance of <code>TestCase</code> object is used to run each test method in a JUnit test case? Or one instance is reused for all the tests?</p> <pre><code>public class MyTest extends TestCase { public void testSomething() { ... } public void testSomethingElse() { ... } } </code></pre> <p>While running this test, how many instances of <code>MyTest</code> class is created?</p> <p>If possible, provide a link to a document or source code where I can verify the behaviour.</p>
<p>Yes, a separate instance is created.</p> <p>While running that test, 2 instances of MyTest gets created.</p> <p>If you want a different behavior, one option is to use a similar tool called TestNG(<a href="http://testng.org/doc/" rel="noreferrer">http://testng.org/doc/</a>).</p>
<p>Yes, definitely. I found that data I stored in instance variables could not be accessed between tests due to this design.</p>
21,854
<p>I came across several issues which seem to have been lowered. Firstly, I changed from a 0.4 to a 0.5 mm nozzle. Because of the backpressure I was not able to print my PETG (Colorfabb XT filament) below 270°C which caused unresolvable oozing. After that I was able to extrude till 230°C.</p> <p>The left print below shows the result. I disassembled the hotend, there was no leak or whatsoever. Maybe it was too cold for printing. However, the temperature displayed was 250°C. Then I replaced the cheap aluminum heat block with a copper alloy based one. After that my PIDs did not work anymore. I had to greatly enhance the d-term, otherwise there was a big overshoot. Guess there was a serious heat conducting issue with the old BQ hotend. </p> <p><a href="https://i.stack.imgur.com/uxd43.jpg" rel="nofollow noreferrer" title="Prints using BQ Alu Heatblock (left) and Copper alloy heatblock (right)"><img src="https://i.stack.imgur.com/uxd43.jpg" alt="Prints using BQ Alu Heatblock (left) and Copper alloy Heatblock (right)" title="Prints using BQ Alu Heatblock (left) and Copper alloy heatblock (right)"></a></p> <p>Anyway, from there it became better. However, I noticed that I still have severe underextrusion after travel moves (second piece, first picture, first piece, second picture). I use Cura, so I activated retraction with the feature to prime after travel moves. I got the wall closed just after 0.35 mm³. </p> <p><a href="https://i.stack.imgur.com/Oj1Ey.jpg" rel="nofollow noreferrer" title="Prints using Copper alloy Heatblock (left)"><img src="https://i.stack.imgur.com/Oj1Ey.jpg" alt="Prints using Copper alloy Heatblock (left)" title="Prints using Copper alloy Heatblock (left)"></a></p> <p>My Question: Is this underextrusion after travel moves normal for PETG/XT? I did not discover such behavior with PLA or ABS in the past. </p> <p>Current Site Advice: Despite the weight, copper heat blocks seem to be worth the upgrade. </p>
<p>Have you tried adjusting the Extra Restart Distance in Simplify3D or Retraction Extra Prime in Ultimaker Cura? Most slicers should have a similar setting, perhaps named just slightly differently. A small positive value can help prime the nozzle after a long travel when you've lost back pressure or oozed a little.</p>
<p>Zero retraction is just a special (worst) case of under-retraction. You'll pretty much always lose material to oozing if you don't retract before travel. At best this ends up hidden inside the print (but can still affect weight and weight balance); usually it'll also harm the surface.</p> <p>Ensure that retraction is set to <em>always</em> happen (not skipping short travel), and at least 5-6 mm for bowden extruders. Direct extruders can get away with less but I'm not sure exactly how much less. Less-rigid materials need more retraction to make up for compression of the filament between the extruder gear and the nozzle.</p>
950
<p>I want to use HTTP GET and POST commands to retrieve URLs from a website and parse the HTML. How do I do this?</p>
<p>You can use <a href="http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html" rel="noreferrer">HttpURLConnection</a> in combination with <a href="http://java.sun.com/javase/6/docs/api/java/net/URL.html" rel="noreferrer">URL</a>.</p> <pre><code>URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); InputStream stream = connection.getInputStream(); // read the contents using an InputStreamReader </code></pre>
<p>The easiest way to do a GET is to use the built in java.net.URL. However, as mentioned, httpclient is the proper way to go, as it will allow you among others to handle redirects.</p> <p>For parsing the html, you can use <a href="http://htmlparser.sourceforge.net/" rel="nofollow noreferrer">html parser</a>.</p>
46,888
<p>I'm searching a small <strong>Java</strong> based RSS/Feed Generator, something like the <a href="http://www.bitfolge.de/rsscreator-en.html" rel="noreferrer">FeedCreator.class.php</a> library, any suggestions?, thanks!</p>
<p>There's the Rome framework as well</p> <p><a href="http://rometools.github.io/rome/" rel="nofollow noreferrer">http://rometools.github.io/rome/</a></p> <p>Does RSS and Atom</p>
<p>How about <a href="http://jrss.sourceforge.net/" rel="nofollow noreferrer">jRSS</a>? It looks promising -- supports generating RSS 2 and is relatively small.</p>
17,417
<p>I am getting this warning: "Missing XML comment for publicly visible type or member".</p> <p>How to solve this?</p>
<p>5 options:</p> <ul> <li>Fill in the documentation comments (great, but time-consuming)</li> <li>Turn off the comment generation (in project properties)</li> <li>Disable the warning in project properties (in 'Project properties' go to Project properties -> Build > "Errors and warnings" (section), Suppress Warnings (textbox), add 1591 (comma separated list)). By default it will change Active Configuration, consider to change configuration to All.</li> <li>Use <code>#pragma warning disable 1591</code> to disable the warning just for some bits of code (and <code>#pragma warning restore 1591</code> afterwards)</li> <li>Ignore the warnings (bad idea - you'll miss new "real" warnings)</li> </ul>
<p>I got that message after attached an attribute to a method</p> <pre><code>[webMethod] public void DoSomething() { } </code></pre> <p>But the correct way was this:</p> <pre><code>[webMethod()] // Note the Parentheses  public void DoSomething() { } </code></pre>
24,941
<p>I heard that Visual Studio came with an Image Library, but I can't find it anywhere. Does anyone know where it is?</p>
<p>From Visual Studio 2012 onward, the icons are downloadable separately from Visual Studio:</p> <ul> <li><a href="https://learn.microsoft.com/en-us/visualstudio/designers/the-visual-studio-image-library" rel="noreferrer">The Visual Studio Image Library</a></li> </ul> <p>The library contains application images that appear in Microsoft Visual Studio, Microsoft Windows, the Office system, and other Microsoft software.</p> <p>The download <a href="http://connect.microsoft.com/VisualStudio/feedback/details/758881/image-library-missing-from-visual-studio-2012" rel="noreferrer">wasn't initially available</a> when Visual Studio 2012 launched.</p>
<p>Visual Studio 2012 for windows phone</p> <p>C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Icons</p>
38,758
<p>A few years ago I developed a web app for which we wanted to make sure the users weren't sharing credentials.</p> <p>One of the things we decided to to, was only allow the user to be logged in from one computer at a time. The way I did this, was to have a little iframe ping the server every N seconds; as long as the server had a heartbeat for a particular user (from a particular IP), that user was not allowed to log in from any other IP.</p> <p>The solution, although approved by my manger, always seemed hacky to me. Also, it seems like it would be easy to circumvent.</p> <p>Is there a good way to make sure a web app user only logs in once? To be honest, I never understood why management even wanted this feature. Does it make sense to enforce this on distributed apps?</p>
<p>I've implemented this by maintaining a hashtable of currently logged in users, the key was the username, the value was their last activity time.</p> <p>When logging in, you just check this hashtable for the key, and if it exists, reject the login.</p> <p>When the user does anything, you update the hashtable with the time (This is easy if you make it part of the core page framework).</p> <p>If the time in the hashtable is greater than 20 minutes of inactivity, you remove them. You can do this every time the hashtable is checked, so even if you only had one user, and the tried to login several hours later, during that initial check, it would remove them from the hashtable for being idle.</p> <p>Some examples in C# (Untested):</p> <pre><code>public Dictionary&lt;String,DateTime&gt; UserDictionary { get { if (HttpContext.Current.Cache["UserDictionary"] != null) { return HttpContext.Current.Cache["UserDictionary"] as Dictionary&lt;String,DateTime&gt;; } return new Dictionary&lt;String,DateTime&gt;(); } set { HttpContext.Current.Cache["UserDictionary"] = value; } } public bool IsUserAlreadyLoggedIn(string userName) { removeIdleUsers(); return UserDictionary.ContainsKey(userName); } public void UpdateUser(string userName) { UserDictionary[userName] = DateTime.Now; removeIdleUsers(); } private void removeIdleUsers() { for (int i = 0; i &lt; UserDictionary.Length; i++) { if (user[i].Value &lt; DateTime.Now.AddMinutes(-20)) user.RemoveAt(i); } } </code></pre>
<p>In a highly secure application, you may be required to do such. What you can do is keep a login count incrementing that for the user that logs in and the IP address. The count should never be 2. If it is then you log the other IP out and whomever it is logged into that IP gets thrown out. That wont prevent user-1 from giving his credentials to user-2, it will just make it frustrating for user-1 to do his work if user-2 logs in somewhere else at the same time. </p>
16,561
<p>I have a query form that I would like to submit as a GET request so the result page may be bookmarked and otherwise RESTful. It's your classical text field with a submit button. How do I induce Seam/JSF to use GET and include the query expression as a parameter rather than POST, the default?</p>
<p>All you need to do is enable the SeamFilter in web.xml. See <a href="http://docs.jboss.com/seam/2.0.2.SP1/reference/en-US/html_single/#blog" rel="nofollow noreferrer">Blog Example</a> for an example RESTful application using Seam. The key is to use a Seam page parameter, defined in WEB-INF/pages.xml</p>
<p>you can use a PhaseListener to convert POST requests to GET requests or just to interpret GET requests so that they can be bookmarkable.</p> <p>This page should explain in more detail:</p> <p><a href="http://balusc.blogspot.com/2007/03/post-redirect-get-pattern.html" rel="nofollow noreferrer">http://balusc.blogspot.com/2007/03/post-redirect-get-pattern.html</a></p>
12,842
<p>Before I ask my question, here's the offending code:</p> <pre><code>var coords = dojo.coords(g); g.style.left = coords.x + "px"; g.style.top = coords.y + "px"; g.style.position = "absolute"; </code></pre> <p>Now imagine that <code>g</code> is a relatively positioned element with an <code>x</code> position of 70 and a <code>y</code> position of 30. If I comment out the last line of the above code, that's what <code>dojo.coords(g)</code> gives me. But as soon as I add the last line, <code>dojo.coords(g)</code> returns an <code>x</code> position of 18, which is where the element would be if it were absolutely positioned. It seems to me that the call to <code>dojo.coords()</code> shouldn't be affected by code below it, but it is.</p> <p>I'm also seeing the same problem with <code>dojo.require()</code> where if I call it directly before the function call that it's loading, I get an undefined error for that given function.</p> <p>I'm testing in Firefox 3, but I also am noticing similar problems in Safari 3. Any ideas?</p>
<p>I still would love someone to explain why this works, but here's a solution:</p> <pre><code>var coords = dojo.coords(g); g.style.left = coords.x + "px"; g.style.top = coords.y + "px"; setTimeout(function(h) { h.style.position = "absolute"; }, 0, g); </code></pre> <p>Cheers</p>
<p>sorry to not respond your question, (because I do not know dojo) but unless coords.x and coords.y returns a string, there is an error in your function,</p> <blockquote> <p>g.style.left = coords.x + &quot;px&quot;;</p> <p>g.style.top = coords.y + &quot;px&quot;;</p> </blockquote> <p>You need to pass always a string to style, so add these also:</p> <pre><code>g.style.left = parseInt(coords.x) + &quot;px&quot;; g.style.top = parseInt(coords.y) + &quot;px&quot;; </code></pre> <p>You would be surprised how many times this kind of error got my head spinning. About the answer, sorry, but I can't help you.</p> <p>Good luck!</p> <p>Edited:</p> <p>Oh, if I understood, I can help you now.. well, since I do not know dojo, I can point out to you a javascript similar that will do what you want.</p> <pre><code>g.offsetTop </code></pre> <p>and</p> <pre><code>g.offsetLeft </code></pre> <p>Will give you the coords from the position of the element. Try them out and see if it works..</p>
37,801
<p>Oftentimes a developer will be faced with a choice between two possible ways to solve a problem -- one that is idiomatic and readable, and another that is less intuitive, but may perform better. For example, in C-based languages, there are two ways to multiply a number by 2:</p> <pre><code>int SimpleMultiplyBy2(int x) { return x * 2; } </code></pre> <p>and</p> <pre><code>int FastMultiplyBy2(int x) { return x &lt;&lt; 1; } </code></pre> <p>The first version is simpler to pick up for both technical and non-technical readers, but the second one may perform better, since bit shifting is a simpler operation than multiplication. (For now, let's assume that the compiler's optimizer would not detect this and optimize it, though that is also a consideration).</p> <p>As a developer, which would be better as an initial attempt?</p>
<p>You missed one.</p> <p>First code for correctness, then for clarity (the two are often connected, of course!). Finally, and only if you have real empirical evidence that you actually need to, you can look at optimizing. Premature optimization really is evil. Optimization almost always costs you time, clarity, maintainability. You'd better be sure you're buying something worthwhile with that.</p> <p>Note that good algorithms almost always beat localized tuning. There is no reason you can't have code that is correct, clear, and fast. You'll be unreasonably lucky to get there starting off focusing on `fast' though.</p>
<p>If you're going to release your software, you must care about the result, not the process.</p> <p>The users are not going to read your code, they are going to use your software, and they don't want to be frustrated by unnecessary long waiting. They will hate you if your well-indented properly-commented application runs slowly or eats a lot of memory.</p> <p>In short, think about the users, not yourself, so prefer performance over readability.</p> <p>One of the best examples of this rule is Quake video game. Its code is not well-structured and is often hardly readable, but it can render thousands of polygons at very high frame rates on 1995-1996 PCs. Quake, and a lot of other video games including Call of Duty (which is derived from Quake 3 engine), wouldn't exist if Carmack preferred readability over performance.</p>
22,148
<p>Apply / find / create a stainless steel coating to apply to a PETG or PLA part to make it react to a magnet.</p> <p>My goal is to make a small tubular and conical shapes that can be painted with a stainless steel coating and will react with a magnet.</p> <p>I know I can buy iron filled PLA but these rust which I want to avoid. <strong>I'm trying to get the magnetic properties of stainless steel (no rusting / reacts to magnets)</strong></p> <p>I have found videos on how to coat with copper / silver / carbon but I'm looking for stainless steel no rust / magnetic properties. <div class="youtube-embed"><div> <iframe width="640px" height="395px" src="https://www.youtube.com/embed/Nx-GwKOH5qc?start=0"></iframe> </div></div></p> <hr /> <p><em>I'm looking for a &quot;low-cost&quot; solution just for testing.</em></p>
<h1>The surface won't work</h1> <p>The only true-metallic surface treatments I know to be actual metal in large enough amounts to conduct electricity would be leafmetal, akin to leaf gold, and electroplating. However, you can't use the procedures for stainless steels, and even then, the thickness is in the tenth of a µm area and lower. Not only would that be far too thin to adhere a magnet to, it also would be super easy to damage with rubbing.</p> <h1>Filling?</h1> <p>PLA itself does not block magnetism - I have printed a PLA holder for a magnetic GPS device, into which I inserted a simple 0.5 mm steel plate for a magnetic surface with 0.5 mm of PLA acting as the container and seal against water.</p> <p>If the prints can be done with one end open and no infill or have a dedicated area that a cheap piece of steel can be inserted into, this method can be used too. The only requirement is that there is a cavity on the inside that at some point is accessible. This also can be during the print.</p> <p>This cavity could either take a piece of shaped steel sheet or be filled with a different magnetic filler, for example, simple iron powder. The powder could be bound in a non-oxidizing polymer, for example, epoxy resin. This method has been used to <a href="https://www.windstuffnow.com/main/poured_stator.htm" rel="nofollow noreferrer">create cast stators for electro motors</a>. It's <a href="https://www.fieldlines.com/index.php/topic,136931.msg902507.html?PHPSESSID=f201710e153b4520d5b59ec4d1475370#msg902507" rel="nofollow noreferrer">not the most efficient</a>, but might work in your application - if your walls are thin enough.</p> <p>With the correct mixture, such a material can be used to coat or fill the inside with enough magnetic material to give the magnets something to stick to and not rust away - the shell and the resin together would shield the iron from any air that could rust it. Indeed, a quite stuffed Resin-Iron-mix and a strong magnet have been <a href="https://www.sightunseen.com/2012/04/at-the-2012-milan-furniture-fair/" rel="nofollow noreferrer">used in 2012 to create furniture by the name of &quot;Gravity Stools&quot;</a> or other art pieces like in <a href="https://youtu.be/pxUUTIUOkW0" rel="nofollow noreferrer">this video</a></p>
<p>No rust but has magnetic properties? You could try varnishing the iron filled PLA.</p>
1,854
<p>Using the Qt Visual studio integration, adding a new Qt class adds two separate moc.exe generated files - one for debug and one for release (and one for any other configuration currently existing). Yet the two eventual generated files seem to be identical.</p> <p>On the other hand when adding a UI class, the uic.exe generated files don't have this separation and are the same file for all configurations.</p> <p>Does anybody have an idea why there's a need for a separate moc file for every configuration? When is there a difference between the two?</p>
<p>My guess would be that separate debug and release versions are needed because the moc output is generated from user-defined source code. So the moc output might be different between debug and release builds if the preprocessed class source differs between debug and release (for example, a signal that exists only in the debug build).</p> <p>This doesn't apply to the uic-generated files because those are generated from the .ui XML, which can't vary between debug and release configurations.</p>
<p>Moc parses the source for pre-processor directives. So if you had a header file like this:</p> <pre><code>class Test : public QObject { Q_OBJECT public: Test(); public slots: #ifndef DEBUG void Foo(); #endif }; </code></pre> <p>Then the slot Foo will only exist in the release build and not the debug build. Moc will generate different moc.cpp files depending on whether the DEBUG (in this case) symbol is set.</p>
22,483
<p>In Visual Studio, when I type the line "<code>Implements IDisposable</code>", the IDE automatically adds:</p> <ul> <li>a <code>disposedValue</code> member variable</li> <li>a <code>Sub Dispose() Implements IDisposable.Dispose</code></li> <li>a <code>Sub Dispose(ByVal disposing As Boolean)</code></li> </ul> <p>The <code>Dispose()</code> should be left alone, and the clean up code should be put in <code>Dispose(disposing)</code>.</p> <p>However the <a href="http://msdn.microsoft.com/en-us/library/s9bwddyx.aspx" rel="noreferrer" title="Dispose Finalize Pattern">Dispose Finalize Pattern</a> says you should also override <code>Sub Finalize()</code> to call <code>Dispose(False)</code>. Why doesn't the IDE also add this? Must I add it myself, or is it somehow called implicitly?</p> <p><strike><strong>EDIT:</strong> Any idea why the IDE automatically adds 80% of the required stuff but leaves out the Finalize method? Isn't the whole point of this kind of feature to help you <em>not</em> forget these things?</strike></p> <p><strong>EDIT2:</strong> Thank you all for your excellent answers, this now makes perfect sense!</p>
<p>If you actually are holding non-managed resources that will not be automatically cleaned up by the garbage collector and cleaning those up in your Dispose(), then yes, you should do the same in Finalize().</p> <p>If you're implementing IDisposable for some other reason, implementing Finalize() isn't required.</p> <p>The basic question is this: If Dispose() wasn't called and your object garbage collected, would memory leak? If yes, implement Finalize. If no, you don't need to. Also, avoid implementing Finalize "just because it's safer". Objects with custom finalizers can potentially need two GC passes to free them -- once to put them on the pending finalizers queue, and a second pass to actually free their memory.</p>
<p>As others have said, you don't need to implement a finalizer unless you're directly holding unmanaged resources. Also, assuming you're working in .NET 2.0 or later, it's unlikely you'll ever need to implement a finalizer because typically SafeHandle can be used to wrap your unmanaged resources.</p> <p>I wrote a <a href="http://gregbeech.com/blogs/tech/archive/2007/03/07/implementing-and-using-the-idisposable-interface.aspx" rel="nofollow noreferrer">fairly long blog post</a> covering the background and implementation of IDisposable and finalizers a while back, which may be worth a read if you're not totally clear about it.</p>
13,834
<p>Unit tests are cheaper to write and maintain, but they don't cover all scenarios. What is the right balance between them?</p>
<p>I like <a href="http://www.exampler.com/old-blog/2003/08/21/#agile-testing-project-1" rel="nofollow noreferrer">Brian Marick's quadrant</a> on automated tests where the distinctions are business vs. technology facing and support programming vs. critique product.</p> <p>With that framework the question of balance becomes, what do I need right now?</p>
<p>On the app I am working on at the moment, there are probably 10:1 unit to functional tests. The unit test work simply things like retrieving entities from DB, error handling tests for db/network connectivity etc. These things run quick - minutes or less and are run by devs daily.</p> <p>functional tests while fewer tend to be kitchen sink approach - can user complete order etc. tend to cover the business domain end of things are run by business analsyts and operations - sadly for us, often by hand. These things take weeks to run and usually to finalize a release cycle.</p>
40,328
<p>How do I use grep to perform a search which, when a match is found, will print the file name as well as the first n characters in that file? Note that <code>n</code> is a parameter that can be specified and it is irrelevant whether the first n characters actually contains the matching string.</p>
<pre><code>grep -l pattern *.txt | while read line; do echo -n "$line: "; head -c $n "$line"; echo; done </code></pre> <p>Change <code>-c</code> to <code>-n</code> if you want to see the first <code>n</code> lines instead of bytes. </p>
<p>Two thoughts here:</p> <p>1) If efficiency was not a concern (like that would ever happen), you could check <em>$status</em> [csh] after running <em>grep</em> on each file. E.g.: (For <strong>N</strong> characters <strong>= 25</strong>.)</p> <pre><code>foreach FILE ( file1 file2 ... fileN ) grep targetToMatch ${FILE} &gt; /dev/null if ( $status == 0 ) then echo -n "${FILE}: " head -c25 ${FILE} endif end </code></pre> <p>2) GNU [FSF] <em>head</em> contains a <em>--verbose</em> <em>[-v]</em> switch. It also offers <em>--null</em>, to accomodate filenames with spaces. And there's <em>'--'</em>, to handle filenames like <em>"-c"</em>. So you could do:</p> <pre><code>grep --null -l targetToMatch -- file1 file2 ... fileN | xargs --null head -v -c25 -- </code></pre>
48,875
<p>I'm hopeless at Javascript. This is what I have:</p> <pre><code>&lt;script type="text/javascript"&gt; function beginrefresh(){ //set the id of the target object var marquee = document.getElementById("marquee_text"); if(marquee.scrollLeft &gt;= marquee.scrollWidth - parseInt(marquee.style.width)) { marquee.scrollLeft = 0; } marquee.scrollLeft += 1; // set the delay (ms), bigger delay, slower movement setTimeout("beginrefresh()", 10); } &lt;/script&gt; </code></pre> <p>It scrolls to the left but I need it to repeat relatively seamlessly. At the moment it just jumps back to the beginning. It might not be possible the way I've done it, if not, anyone have a better method?</p>
<p>Here is a jQuery plugin with a lot of features:</p> <p><a href="http://jscroller2.markusbordihn.de/example/image-scroller-windiv/" rel="noreferrer">http://jscroller2.markusbordihn.de/example/image-scroller-windiv/</a></p> <p>And this one is "silky smooth"</p> <p><a href="http://remysharp.com/2008/09/10/the-silky-smooth-marquee/" rel="noreferrer">http://remysharp.com/2008/09/10/the-silky-smooth-marquee/</a></p>
<p>Working with @Stano code and some jQuery I have created a script that will replace the old <code>marquee</code> tag with standard <code>div</code>. The code will also parse the <code>marquee</code> attributes like <code>direction</code>, <code>scrolldelay</code> and <code>scrollamount</code>.</p> <p>Here is the code: </p> <pre><code>jQuery(function ($) { if ($('marquee').length == 0) { return; } $('marquee').each(function () { let direction = $(this).attr('direction'); let scrollamount = $(this).attr('scrollamount'); let scrolldelay = $(this).attr('scrolldelay'); let newMarquee = $('&lt;div class="new-marquee"&gt;&lt;/div&gt;'); $(newMarquee).html($(this).html()); $(newMarquee).attr('direction',direction); $(newMarquee).attr('scrollamount',scrollamount); $(newMarquee).attr('scrolldelay',scrolldelay); $(newMarquee).css('white-space', 'nowrap'); let wrapper = $('&lt;div style="overflow:hidden"&gt;&lt;/div&gt;').append(newMarquee); $(this).replaceWith(wrapper); }); function start_marquee() { let marqueeElements = document.getElementsByClassName('new-marquee'); let marqueLen = marqueeElements.length for (let k = 0; k &lt; marqueLen; k++) { let space = '&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;'; let marqueeEl = marqueeElements[k]; let direction = marqueeEl.getAttribute('direction'); let scrolldelay = marqueeEl.getAttribute('scrolldelay') * 100; let scrollamount = marqueeEl.getAttribute('scrollamount'); let marqueeText = marqueeEl.innerHTML; marqueeEl.innerHTML = marqueeText + space; marqueeEl.style.position = 'absolute'; let width = (marqueeEl.clientWidth + 1); let i = (direction == 'rigth') ? width : 0; let step = (scrollamount !== undefined) ? parseInt(scrollamount) : 3; marqueeEl.style.position = ''; marqueeEl.innerHTML = marqueeText + space + marqueeText + space; let x = setInterval( function () { if ( direction.toLowerCase() == 'left') { i = i &lt; width ? i + step : 1; marqueeEl.style.marginLeft = -i + 'px'; } else { i = i &gt; -width ? i - step : width; marqueeEl.style.marginLeft = -i + 'px'; } }, scrolldelay); } } start_marquee (); }); </code></pre> <p>And here is a working <a href="https://codepen.io/alordiel/pen/xypEWb" rel="nofollow noreferrer">codepen</a></p>
43,769
<p>I know that one of the defining principles of Test driven development is that you write your Unit tests first and then write code to pass those unit tests, but is it necessary to do it this way?</p> <p>I've found that I often don't know what I am testing until I've written it, mainly because the past couple of projects I've worked on have more evolved from a proof of concept rather than been designed.</p> <p>I've tried to write my unit tests before and it can be useful, but it doesn't seem natural to me.</p>
<p>Some good comments here, but I think that one thing is getting ignored.</p> <p>writing tests first drives your design. This is an important step. If you write the tests "at the same time" or "soon after" you might be missing some design benefits of doing TDD in micro steps.</p> <p>It feels really cheesy at first, but it's amazing to watch things unfold before your eyes into a design that you didn't think of originally. I've seen it happen.</p> <p>TDD is hard, and it's not for everybody. But if you already embrace unit testing, then try it out for a month and see what it does to your design and productivity.</p> <p>You spend less time in the debugger and more time thinking about outside-in design. Those are two gigantic pluses in my book.</p>
<p>I don't write the actual unit tests first, but I do make a test matrix before I start coding listing all the possible scenarios that will have to be tested. I also make a list of cases that will have to be tested when a change is made to any part of the program as part of regression testing that will cover most of the basic scenarios in the application in addition to fully testing the bit of code that changed.</p>
30,682
<p>I have a PHP application that will on occasion have to handle URLs where more than one parameter in the URL will have the same name. Is there an easy way to retrieve all the values for a given key? PHP $_GET returns only the last value. </p> <p>To make this concrete, my application is an OpenURL resolver, and may get URL parameters like this:</p> <pre><code>ctx_ver=Z39.88-2004 &amp;rft_id=info:oclcnum/1903126 &amp;rft_id=http://www.biodiversitylibrary.org/bibliography/4323 &amp;rft_val_fmt=info:ofi/fmt:kev:mtx:book &amp;rft.genre=book &amp;rft.btitle=At last: a Christmas in the West Indies. &amp;rft.place=London, &amp;rft.pub=Macmillan and co., &amp;rft.aufirst=Charles &amp;rft.aulast=Kingsley &amp;rft.au=Kingsley, Charles, &amp;rft.pages=1-352 &amp;rft.tpages=352 &amp;rft.date=1871 </code></pre> <p>(Yes, I know it's ugly, welcome to my world). Note that the key "rft_id" appears twice:</p> <ol> <li><code>rft_id=info:oclcnum/1903126</code></li> <li><code>rft_id=http://www.biodiversitylibrary.org/bibliography/4323</code></li> </ol> <p><code>$_GET</code> will return just <code>http://www.biodiversitylibrary.org/bibliography/4323</code>, the earlier value (<code>info:oclcnum/1903126</code>) having been overwritten.</p> <p>I'd like to get access to both values. Is this possible in PHP? If not, any thoughts on how to handle this problem?</p>
<p>Something like:</p> <pre><code>$query = explode('&amp;', $_SERVER['QUERY_STRING']); $params = array(); foreach( $query as $param ) { // prevent notice on explode() if $param has no '=' if (strpos($param, '=') === false) $param += '='; list($name, $value) = explode('=', $param, 2); $params[urldecode($name)][] = urldecode($value); } </code></pre> <p>gives you:</p> <pre><code>array( 'ctx_ver' =&gt; array('Z39.88-2004'), 'rft_id' =&gt; array('info:oclcnum/1903126', 'http://www.biodiversitylibrary.org/bibliography/4323'), 'rft_val_fmt' =&gt; array('info:ofi/fmt:kev:mtx:book'), 'rft.genre' =&gt; array('book'), 'rft.btitle' =&gt; array('At last: a Christmas in the West Indies.'), 'rft.place' =&gt; array('London'), 'rft.pub' =&gt; array('Macmillan and co.'), 'rft.aufirst' =&gt; array('Charles'), 'rft.aulast' =&gt; array('Kingsley'), 'rft.au' =&gt; array('Kingsley, Charles'), 'rft.pages' =&gt; array('1-352'), 'rft.tpages' =&gt; array('352'), 'rft.date' =&gt; array('1871') ) </code></pre> <p>Since it's always possible that one URL parameter is repeated, it's better to always have arrays, instead of only for those parameters where you anticipate them.</p>
<p>AFAIK there is no way to get duplicate values using <code>$_GET</code> as the second value will overwrite the first</p> <p>To get around it you could access the raw querystring using <code>$_SERVER['QUERY_STRING']</code> and then parse it yourself.</p>
46,022
<p>If I have a table in my database called 'Users', there will be a class generated by LINQtoSQL called 'User' with an already declared empty constructor.</p> <p>What is the best practice if I want to override this constructor and add my own logic to it?</p>
<p>The default constructor which is generated by the O/R-Designer, calls a partial function called <code>OnCreated</code> - so the best practice is not to override the default constructor, but instead implement the partial function <code>OnCreated</code> in <code>MyDataClasses.cs</code> to initialize items:</p> <pre><code>partial void OnCreated() { Name = ""; } </code></pre> <p>If you are implementing other constructors, always take care to call the default constructor so the classes will be initialized properly - for example entitysets (relations) are constructed in the default constructor.</p>
<p>Here's the C# version:</p> <pre><code>public partial class PENCILS_LinqToSql_DataClassesDataContext { public PENCILS_LinqToSql_DataClassesDataContext() : base(ConnectionString(), mappingSource) { } public static String ConnectionString() { String CS; String Key; Key = System.Configuration.ConfigurationManager.AppSettings["DefaultConnectionString"].ToString(); /// Get the actual connection string. CS = System.Configuration.ConfigurationManager.ConnectionStrings[Key].ToString(); return CS; } } </code></pre>
10,813
<p>Wizards can kick-start features. They can also obfuscate your code, and are anti-YAGNI.</p> <p>On balance, do you think Wizards are more useful or more harmful?</p>
<p>They are more useful than harmful <strong>if</strong> and only if you understand the code they generate. Only after you mastered the problem the wizard is trying to solve they are really useful. Otherwise you'll hit walls later in the project, because the generated code <strong>will</strong> need modifications at some point.</p> <p><a href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html" rel="nofollow noreferrer">"The Law of Leaky Abstractions"</a> really nails it on the head.</p>
<p>Wizards are "mostly harmless" when they generate an encapsulated entity - a function, a class or a set of classes - which you don't need to modify and which you interact with through a well-defined, well-designed interface.</p> <p>On the other end of the spectrum is a wizard that that generates skeleton code that needs to be extended and modified. This is especially troublesome if you can't change some of the wizard option later without losing your edits. </p> <p>These are still "ok" for the pro who could write the same code by himself and uses the wizard to save time. However, when they are used to make something complicated look easy for beginners, they are a paint job over a rusty car: they help selling something that you otherwise wouldn't buy.</p> <p>In practice, they may still be useful to ease adoption of a platform. But that's a business aspect, and whether business aspects may justify code blunders is a question of the development environment.</p>
31,963
<p>I like to generate a thread dump programmatically. I've learned that there a basically two ways to do it:</p> <ol> <li>Use the "Java Virtual Machine Tool Interface" JVM-TI</li> <li>Use the higher abstracted "Java Debugger Interface" JDI</li> </ol> <p>For the JVM-TI I was able to find some useful information, but I would have to write a JNI-DLL which, at least for the moment, I would like to avoid. With the JDI I can use Java and it seems I'm able to use it from within the application. But I wasn't able to find some kind of tutorial or HOWTO for it. The only documentation I could find, were the Java-Docs <a href="http://java.sun.com/j2se/1.5.0/docs/guide/jpda/jdi/" rel="noreferrer">http://java.sun.com/j2se/1.5.0/docs/guide/jpda/jdi/</a> which isn't very helpful, because it doesn't show me how to use this classes.</p> <p>So, does anybody know of a good tutorial/book I could read?</p> <p>Thx for any help!</p>
<p>There is a third way: Thread.getAllStackTraces()</p> <p><a href="http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getAllStackTraces()" rel="noreferrer">http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getAllStackTraces()</a></p> <p>This is much easier than the debugger interface...</p>
<p>Did you consider the remote alternative ? I.e. <a href="http://java.sun.com/javase/6/docs/technotes/guides/visualvm/applications_local.html" rel="nofollow noreferrer">VisualVM</a></p> <p><img src="https://i.stack.imgur.com/U0ckF.png" alt="thead dump with visualVM"></p> <p><a href="http://wiki.caucho.com/Thread_dump" rel="nofollow noreferrer">jps and jstack</a> are also useful tools included in JDK 5, providing a quick command line method for obtaining stack traces of all current threads. </p> <p>This article suggest JDI is also used as a <a href="http://xudegui.blogspot.com/2008/03/jdb-example-generating-thread-dump.html" rel="nofollow noreferrer">remote tool</a>.</p> <p>So I am not sure you can triggers a thread dump within your own program, instead you find a way to send to yourself a SIGQUIT signal (kill -3) on Unix platforms, or press the Ctrl-\ key on Unix or Ctrl-Break on Windows platforms.</p> <p>Plus, <a href="http://x86.sun.com/thread.jspa?threadID=5284700&amp;tstart=0" rel="nofollow noreferrer">JDI wasn't intended to be used to debug the same process in which the JDI client is running</a>. Still this thread I just linked to is the closest I have found to actually use JDI within the same program.</p>
29,641
<p>I have read the documentation on this and I think I understand. An <a href="http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx" rel="noreferrer"><code>AutoResetEvent</code></a> resets when the code passes through <code>event.WaitOne()</code>, but a <a href="http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx" rel="noreferrer"><code>ManualResetEvent</code></a> does not.</p> <p>Is this correct?</p>
<p>Yes. It's like the difference between a tollbooth and a door. The <code>ManualResetEvent</code> is the door, which needs to be closed (reset) manually. The <code>AutoResetEvent</code> is a tollbooth, allowing one car to go by and automatically closing before the next one can get through.</p>
<p>If you want to understand AutoResetEvent and ManualResetEvent you need to understand not threading but interrupts!</p> <p>.NET wants to conjure up low-level programming the most distant possible.</p> <p>An interrupts is something used in low-level programming which equals to a signal that from low became high (or viceversa). When this happens the program interrupt its normal execution and move the execution pointer to the function that handles this <em>event</em>.</p> <p>The first thing to do when an interrupt happend is to <strong>reset</strong> its state, becosa the hardware works in this way:</p> <ol> <li>a pin is connected to a signal and the hardware listen for it to change (the signal could have only two states).</li> <li>if the signal changes means that something happened and the hardware put a <strong>memory variable</strong> to the state happened (and it remain like this even if the signal change again).</li> <li>the program notice that variable change states and move the execution to a handling function.</li> <li>here the first thing to do, to be able to listen again this interrupt, is to <strong>reset</strong> this memory variable to the state not-happened.</li> </ol> <p>This is the difference between ManualResetEvent and AutoResetEvent.<br> <strong>If a ManualResetEvent happen and I do not reset it, the next time it happens I will not be able to listen it.</strong></p>
18,586
<p>When using SQLBulkCopy on a table with a GUID primary key and default newsequentialid()</p> <p>e.g</p> <pre><code>CREATE TABLE [dbo].[MyTable]( [MyPrimaryKey] [uniqueidentifier] NOT NULL CONSTRAINT [MyConstraint] DEFAULT (newsequentialid()), [Status] [int] NULL, [Priority] [int] NULL, CONSTRAINT [PK_MyTable] PRIMARY KEY NONCLUSTERED ( [MyPrimaryKey] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] </code></pre> <p>wIth the C# code</p> <pre><code> tran = connection.BeginTransaction(); SqlBulkCopy sqlCopy = new SqlBulkCopy(connection,SqlBulkCopyOptions.Default, tran); sqlCopy.DestinationTableName = "MyTable"; sqlCopy.WriteToServer(dataTable); </code></pre> <p>Gives you an error...</p> <p>Column 'MyPrimaryKey' does not allow DBNull.Value</p> <p>I've tried fiddling the the SqlBulkCopyOptions. The only thing that works is setting the MyPrimaryKey field to allow nulls and removing the primary key.</p> <p>Anyone know if there is a workaround for this issue? Or can you verify that there is no workaround (other than changing the table structure)?</p>
<p>You need to set up the column mappings. First call</p> <pre><code>sqlCopy.ColumnMappings.Clear(); </code></pre> <p>Then call</p> <pre><code>sqlBulkCopy.ColumnMappings.Add("Status", "Status"); sqlBulkCopy.ColumnMappings.Add("Priority", "Priority"); </code></pre> <p>This means the bulk copy will stop trying to insert into MyPrimaryKey column and will only insert into the status and Priority columns.</p>
<p>You're only options are to remove the MyPrimaryKey field from the data that is being loaded or to modify the table structure.</p> <p>With the field being there with no values you are telling SQL that you want to force a null into the field, which, obviously, is not allowed.</p>
16,739
<p>We have a simple project where we read data from a socket and we want to populate a table with the coming data, but we can't find a way to add rows to a yet created <code>JTable</code> object, we can only find how to add rows at creation time of the table.</p> <p>Is it possible to add rows dynamically to a <code>JTable</code>, or there is a better alternative object to deal with this way of showing data?</p> <p><strong>EDIT</strong>: Thanks a lot for your answers.</p> <p>All three of them look very promising, but I have to choose only one and I think the best is Guillaume's.</p>
<p>You should create a custom <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/table/TableModel.html" rel="noreferrer"><code>TableModel</code></a>. A <code>JTable</code> doesn't actually store the rows, it always delegates that to a <code>TableModel</code>. To help you implementing it, you should make use of <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/table/AbstractTableModel.html" rel="noreferrer"><code>AbstractTableModel</code></a>. Don't forget to call <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/table/AbstractTableModel.html#fireTableRowsInserted(int,%20int)" rel="noreferrer"><code>fireTableRowsInserted()</code></a> every time you add rows. For better performances if you add a lot of rows, try to batch the updates and add many rows at a time.</p>
<p>Once you start dynamically adding and removing elements from a JTable, you really need to start using a TableModel.</p> <p>See the <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/table.html" rel="noreferrer">Java Tutorial</a> for more details.</p>
37,793
<p>What are the common algorithms being used to measure the processor frequency?</p>
<p>Intel CPUs after Core Duo support two Model-Specific registers called IA32_MPERF and IA32_APERF.<br> MPERF counts at the maximum frequency the CPU supports, while APERF counts at the actual current frequency.</p> <p>The actual frequency is given by:</p> <p><img src="https://chart.apis.google.com/chart?cht=tx&amp;chl=%5CLARGE%5C%21freq%20%3D%20%5Cfrac%7Bmax%20frequency%20%5Ccdot%20APERF%7D%7BMPERF%7D" alt="freq = max_frequency * APERF / MPERF"></p> <p>You can read them with this flow</p> <pre><code>; read MPERF mov ecx, 0xe7 rdmsr mov mperf_var_lo, eax mov mperf_var_hi, edx ; read APERF mov ecx, 0xe8 rdmsr mov aperf_var_lo, eax mov aperf_var_hi, edx </code></pre> <p>but note that rdmsr is a privileged instruction and can run only in ring 0.</p> <p>I don't know if the OS provides an interface to read these, though their main usage is for power management, so it might not provide such an interface.</p>
<p>I'm not sure why you need assembly for this. If you're on a machine that has the /proc filesystem, then running:</p> <pre><code>&gt; cat /proc/cpuinfo </code></pre> <p>might give you what you need.</p>
9,085
<p>I am not able to get the selection object's start and end offsets in Opera (v9.50) when the selection is collapsed (i.e. just point and click instead of highlighting text). This is my simple test code, which works in FF and Safari but does not work in Opera. </p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function showSelection() { userSelection = window.getSelection(); alert('Start: '+userSelection.anchorOffset+'\nEnd: '+userSelection.focusOffset); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div onmouseup="showSelection();"&gt; &lt;p&gt;Lorem ipsum dolor &lt;strong&gt;sit amet&lt;/strong&gt;&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>When I select a text, it works, but just pointing and clicking always return the offsets as 0. What am I missing? Thanks in advance.</p>
<p>This question is very similar to <a href="https://stackoverflow.com/questions/49378/deploy-mysql-server-db-with-net-application">another question</a>. However, the answers don't really help.</p> <p>You can <a href="http://www.simple-talk.com/dotnet/visual-studio/visual-studio-setup---projects-and-custom-actions/" rel="nofollow noreferrer">run executables from a custom action in the .Net deployment project</a>, that's what I'd recommend. (Look under the heading "Calling an executable as a custom action")</p> <p>Hopefully everything can be taken care of by via the command line. If not, try a scripted installer like Wise or InstallShield, I think they have better support for stuff like this.</p> <p>Hope that helps!</p>
<p>Have a look at using Visual Studio's package and deployment tool. It should automatically bring in the MySQL dependencies if you connect natively (MySQL .NET components) rather than an ODBC connection. In any case it allows you to add other software to an installation program that can be automatically unpacked if you need it. I have used it to deploy C# apps using the MySQL libraries that you download from MySQL website and for CoreLab's MySQL 3rd party libraries.</p>
49,339
<p>I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page.</p> <p>What can I do to resolve this?</p>
<p>If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example:</p> <pre><code>&lt;asp:Label runat="server" id="Label1" style="display: none;" /&gt; </code></pre> <p>Then, you could make it visible on the client side with:</p> <pre><code>document.getElementById('Label1').style.display = 'inherit'; </code></pre> <p>You could make it hidden again with:</p> <pre><code>document.getElementById('Label1').style.display = 'none'; </code></pre> <p>Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ.</p>
<p>If you wait until the page is loaded, and then set the button's display to none, that should work. Then you can make it visible at a later point.</p>
2,937
<p>Are declaring custom .NET event such as <a href="http://www.c-sharpcorner.com/UploadFile/rmcochran/customgenericeventargs05132007100456AM/customgenericeventargs.aspx" rel="nofollow noreferrer">this</a>, more common in a winform app than webform?</p>
<p>Create a user/login to the DB that you can control. Assign that user as the owner (using grants) of the tables you need to "hide/lock". Use grants to make the tables inaccessible ( or read only) to other users.</p>
<p>After creating the user, make sure you remove the grants for other users. By default, default users have the grant. So make sure only your user has all the the grants</p>
44,594
<p>The log file from a JVM crash contains all sorts of useful information for debugging, such as shared libraries loaded and the complete environment. Can I force the JVM to generate one of these programmatically; either by executing code that crashes it or some other way? Or alternatively access the same information another way?</p>
<p>You can try throwing an OutOfMemoryError and adding the -XX:+HeapDumpOnOutOfMemoryError jvm argument. This is new as of 1.6 as are the other tools suggested by McDowell. <a href="http://blogs.oracle.com/watt/resource/jvm-options-list.html" rel="nofollow noreferrer">http://blogs.oracle.com/watt/resource/jvm-options-list.html</a></p>
<p>I am pretty sure this can be done with the IBM JDK as I was playing around with their stack analyzer some time ago. One option to force the dump would just to cause an outOfMemoryException. </p> <p>These tools may provide some clues <a href="http://www.ibm.com/developerworks/java/library/j-ibmtools1/" rel="nofollow noreferrer">http://www.ibm.com/developerworks/java/library/j-ibmtools1/</a></p>
43,841
<p>I've currently got a tool which allows me to configure a database connection (using JDBC) and specify a set of queries to run against the database. This is scheduled to run at a specific time of day (using cron or windows scheduler currently). The tool then exports the results to a file (xml) and sends this file to my server via HTTPS. This tool is installed on customers computers so that I can get some data feeds from them for later processing.</p> <p>I'd like to write a front-end to this that will make it easy for customers to set up the data extraction themselves. However I'm not really familiar with Rich Client front-end development (being a integration software developer) and was wondering whether there was an existing tool that would do all this, or if it was worth learning a bit of Swing say so I could knock up a front-end. Do any of you know of a suitable tool? (I'm looking for a one function kind of thing rather than a full data extraction and transformation suite which may scare off some customers)</p>
<p>If your tool already exists and is working, I think the best approach would be to just read a bit about GUI events programming (it's fairly easy once you get the grasp of it and have a nice GUI Builder) and wrap up a small GUI using a GUI Builder.</p> <p>For Java I can recommend the Netbeans IDE and its GUI Builder.</p> <p>The easiest path then would be for the GUI to just pass the received arguments to the existing tool, via Runtime.exec() or a similar approach.</p>
<p>In my opinion, it's quite easy and fast to make a decent UI via Swing. <a href="http://java.sun.com/docs/books/tutorial/uiswing/" rel="nofollow noreferrer">The Swing tutorial</a> may be a good start.</p>
49,850
<p>The first time I load the website in the production web server, it start very slow, subsequent pages load very quickly (included the home page).</p> <p>I precompiled the site, but nothing changes. </p> <p>I don't have any code at Application start. I don't have cached items.</p> <p>Any ideas? How can I find out what is happening?</p>
<p>It's just your app domain loading up and loading any binaries into memory. Also, it's initializing static variables, so if you have a static variable that loads up a lot of data from the db, it might take a bit.</p>
<p>This sounds very much like background compiling; though if you're precompiling, that shouldn't be an issue.</p> <p>First thing I would look at is your ORM (if any). NHibernate, in particular, has a serious startup penalty, as it runs multiple compilers in the background at startup to turn each class in your data layer into its own in-memory assembly.</p>
4,586
<p>I've seen a couple questions around here like <a href="https://stackoverflow.com/questions/165720/how-to-debug-restful-services">How to debug RESTful services</a>, which mentions:</p> <blockquote> <p>Unfortunately that same browser won't allow me to test HTTP PUT, DELETE, and to a certain degree even HTTP POST.</p> </blockquote> <p>I've also heard that browsers support only GET and POST, from some other sources like:</p> <ul> <li><a href="http://www.packetizer.com/ws/rest.html" rel="noreferrer">http://www.packetizer.com/ws/rest.html</a></li> <li><a href="http://www.mail-archive.com/jmeter-user@jakarta.apache.org/msg13518.html" rel="noreferrer">http://www.mail-archive.com/jmeter-user@jakarta.apache.org/msg13518.html</a></li> <li><a href="http://www.xml.com/cs/user/view/cs_msg/1098" rel="noreferrer">http://www.xml.com/cs/user/view/cs_msg/1098</a></li> </ul> <p>However, a few quick tests in Firefox show that sending <code>PUT</code> and <code>DELETE</code> requests works as expected -- the <code>XMLHttpRequest</code> completes successfully, and the request shows up in the server logs with the right method. Is there some aspect to this I'm missing, such as cross-browser compatibility or non-obvious limitations?</p>
<p>No. The <a href="http://w3c.github.io/html/sec-forms.html#form-control-infrastructure-form-submission" rel="noreferrer">HTML 5 spec</a> mentions:</p> <blockquote> <p>The method and formmethod content attributes are enumerated attributes with the following keywords and states:</p> <p>The keyword <strong>get</strong>, mapping to the state GET, indicating the HTTP GET method. The GET method should only request and retrieve data and should have no other effect. </p> <p>The keyword <strong>post</strong>, mapping to the state POST, indicating the HTTP POST method. The POST method requests that the server accept the submitted form's data to be processed, which may result in an item being added to a database, the creation of a new web page resource, the updating of the existing page, or all of the mentioned outcomes.</p> <p>The keyword <strong>dialog</strong>, mapping to the state dialog, indicating that submitting the form is intended to close the dialog box in which the form finds itself, if any, and otherwise not submit. </p> <p>The invalid value default for these attributes is the GET state</p> </blockquote> <p>I.e. HTML forms only support <strong>GET</strong> and <strong>POST</strong> as HTTP request methods. A workaround for this is to tunnel other methods through POST by using a hidden form field which is read by the server and the request dispatched accordingly.</p> <p>However, <strong>GET</strong>, <strong>POST</strong>, <strong>PUT</strong> and <strong>DELETE</strong> <em>are</em> supported by the implementations of XMLHttpRequest (i.e. AJAX calls) in all the major web browsers (IE, Firefox, Safari, Chrome, Opera).</p>
<p>Just to add - Safari 2 and earlier definitely didn't support PUT and DELETE. I get the impression 3 did, but I don't have it around to test anymore. Safari 4 definitely does support PUT and DELETE.</p>
20,021
<p>I have two SQL scripts which get called within a loop that accept a number parameter. Here is what I'm currently using:</p> <pre><code>for /l %%i in (1, 1, 51) do ( sqlplus u/p@name @script.sql a%%i.html %%i sqlplus u/p@name @script.sql b%%i.html %%i ) </code></pre> <p>Everything works fine, but it seems like a waste of time and resources to connect twice for each pass through. Is there a way I could simply log into sqlplus, run the for loop, then exit? I tried many alternatives such as putting</p> <pre><code>sqlplus u/p@name </code></pre> <p>before the for loop, but then it would simply hang at the SQL> prompt without executing any of my two scripts.</p> <p>Thank you.</p>
<p>You can create a masterscript.sql that contains your two script.sql statements. The only thing I'm not sure about is if it will pass in your variables.</p> <p>MasterScript.sql would contain:</p> <pre><code>@@script1.sql @@script2.sql </code></pre> <p>and neither of your sub-scripts should contain an exit.</p> <p><a href="http://www.orafaq.com/wiki/SQL*Plus_FAQ#What_is_the_difference_between_.40_and_.40.40.3F" rel="nofollow noreferrer">Differences between "@" and "@@"</a>:</p> <p><a href="http://www.orafaq.com/wiki/SQL" rel="nofollow noreferrer">http://www.orafaq.com/wiki/SQL</a>*Plus_FAQ#What_is_the_difference_between_.40_and_.40.40.3F</p>
<p>Try This</p> <p>( echo @%query% user )<br> | sqlplus username/password@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host=XX.XX.XX.XX)(Port=152X))(CONNECT_DATA=(SID=ABC))) </p>
40,634
<p>I'm working on a java web application that uses thousands of small files to build artifacts in response to requests. I think our system could see performance improvements if we could map these files into memory rather than run all over the disk to find them all the time. </p> <p>I have heard of mmap in linux, and my basic understanding of that concept is that when a file is read from disk the file's contents get cached somewhere in memory for quicker subsequent access. What I have in mind is similar to that idea, except I'd like to read the whole mmap-able set of files into memory as my web app is initializing for minimal request-time responses.</p> <p>One aspect of my thought-train here is that we'd probably get the files into jvm memory faster if they were all tarred up and somehow mounted in the JVM as a virtual file system. As it stands it can take several minutes for our current implementation to walk through the set of source files and just figure out what all is on the disk.. this is because we're essentially doing file stats for upwards of 300,000 files.</p> <p>I have found the apache VFS project which can read information from a tar file, but I'm not sure from their documentation if you can specify something such as "also, read the entire tar into memory and hold it there..". </p> <p>We're talking about a multithreaded environment here serving artifacts that usually piece together about 100 different files out of a complete set of 300,000+ source files to make one response. So whatever the virtual file system solution is, it needs to be thread safe and performant. We're only talking about reading files here, no writes. </p> <p>Also, we're running a 64 bit OS with 32 gig of RAM, our 300,000 files take up about 1.5 to 2.5 gigs of space. We can surely read a 2.5 gigabyte file into memory much quicker than 300K small several-kilobyte-sized files.</p> <p>Thanks for input!</p> <ul> <li>Jason</li> </ul>
<p>You can try to put all the files in a JAR and put that on the classpath. Java uses some built-in tricks to make reading from a JAR file very fast. That will also keep the directory of all files in RAM, so you don't have to access the disk to find a file (that happens before you can start loading it).</p> <p>The JVM won't load the whole JAR into RAM at once and you probably don't want that anyway because your machine would start swapping. But it will be able to find the pieces very quickly because it will keep the file open the whole time and therefore, you won't loose any time opening/closing the file resource.</p> <p>Also, since you're using this single file all the time, chances are that the OS will keep it longer in the file caches.</p> <p>Lastly, you can try to compress the JAR. While this may sound like a bad idea, you should give it a try. If the small files compress very well, the time to unpack with current CPUs is much lower than the time to read the data from the disk. If you don't have to keep the intermediate data anywhere, you can stream the uncompressed data to the client without needing to write to a file (which would ruin the whole idea). The drawback of this is that it does eat CPU cycles and if your CPU is busy (just check with some load tool; if it's above 20%, then you loose), then you will make the whole process slower.</p> <p>That said, when you're using the HTTP protocol, you can tell the client that you're sending compressed data! This way, you don't have to unpack the data <em>and</em> you can load very small files.</p> <p>Main disadvantage of the JAR solution: You can't replace the JAR as long as the server is running. So replacing a file means you will have to restart the server.</p>
<p>Just to clarify, <code><a href="http://linux.die.net/man/2/mmap" rel="nofollow noreferrer">mmap()</a></code> in Unix-like systems would not allow you to access files as such; it simply makes the contents of a file available in memory, as memory. You cannot use <code>open()</code> to further open any contained files. There is no such thing as a "<code>mmap()</code>able set of files".</p> <p>Can't you just add a pass that loads all your "templates" initially, and then quickly finds them based on something simple, like a hash on the name of each? That should let you leverage your memory, and get down to O(1) access for any template.</p>
43,669
<p>I would like to create an HTML table with row colors changing based on position and content. But instead of alternating every row, I'd like to be able to group rows together, so that I can have some XML like this:</p> <pre><code>&lt;itemlist&gt; &lt;item group="0"&gt;Conent...blah blah&lt;/item&gt; &lt;item group="0"&gt;Content...who cares&lt;/item&gt; &lt;item group="1"&gt;Content&lt;/item&gt; &lt;item group="2"&gt;Content&lt;/item&gt; &lt;item group="2"&gt;Content&lt;/item&gt; &lt;/itemlist&gt; </code></pre> <p>And all of the items with group=0 are one color, and items with group=1 are another, and group=2 are either toggled back to the first color, or are their own color.</p> <p>All I can seem to find out there is ways to alternate every row, but I can't seem to "get it" when it comes to actually using the node data to help me make the decision.</p>
<p>Here's an example of using "choose" to apply a different class value based on the group value. Something similar to this would work if you want to treat each group in a specific way. If your decision logic for handling group 2 is more complex, then you could place additional decision logic inside the "when" statement testing for group 2.</p> <p></p> <pre><code>&lt;xsl:template match="/"&gt; &lt;ul&gt; &lt;xsl:apply-templates select="itemlist/item"/&gt; &lt;/ul&gt; &lt;/xsl:template&gt; &lt;xsl:template match="item"&gt; &lt;li&gt; &lt;xsl:attribute name="class"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="@group = 0"&gt; red &lt;/xsl:when&gt; &lt;xsl:when test="@group = 1"&gt; green &lt;/xsl:when&gt; &lt;xsl:when test="@group = 2"&gt; blue &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; black &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:attribute&gt; &lt;xsl:value-of select="."/&gt; &lt;/li&gt; &lt;/xsl:template&gt; </code></pre> <p> </p>
<p>The first two groups are simple as you can parse them based on their group number.</p> <p>To handle group 2, consider using the <a href="http://www.zvon.org/xxl/XSLTreference/Output/axis_preceding.html" rel="nofollow noreferrer">preceding</a> function to get a list of proir notes, and use <a href="http://www.zvon.org/xxl/XSLTreference/Output/function_count.html" rel="nofollow noreferrer">count</a> to determine how many there are. You can can then alternate values based on whether the count is even or odd.</p>
31,867
<p>What would be the best way to calculate someone's age in years, months, and days in T-SQL (SQL Server 2000)?</p> <p>The <code>datediff</code> function doesn't handle year boundaries well, plus getting the months and days separate will be a bear. I know I can do it on the client side relatively easily, but I'd like to have it done in my <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">stored procedure</a>.</p>
<p>Here is some T-SQL that gives you the number of years, months, and days since the day specified in @date. It takes into account the fact that DATEDIFF() computes the difference without considering what month or day it is (so the month diff between 8/31 and 9/1 is 1 month) and handles that with a case statement that decrements the result where appropriate.</p> <pre><code>DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int SELECT @date = '2/29/04' SELECT @tmpdate = @date SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) &gt; MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) &gt; DAY(GETDATE())) THEN 1 ELSE 0 END SELECT @tmpdate = DATEADD(yy, @years, @tmpdate) SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) &gt; DAY(GETDATE()) THEN 1 ELSE 0 END SELECT @tmpdate = DATEADD(m, @months, @tmpdate) SELECT @days = DATEDIFF(d, @tmpdate, GETDATE()) SELECT @years, @months, @days </code></pre>
<pre><code>DECLARE @DoB AS DATE = '1968-10-24' DECLARE @cDate AS DATE = CAST('2000-10-23' AS DATE) SELECT --Get Year difference DATEDIFF(YEAR,@DoB,@cDate) - --Cases where year difference will be augmented CASE --If Date of Birth greater than date passed return 0 WHEN YEAR(@DoB) - YEAR(@cDate) &gt;= 0 THEN DATEDIFF(YEAR,@DoB,@cDate) --If date of birth month less than date passed subtract one year WHEN MONTH(@DoB) - MONTH(@cDate) &gt; 0 THEN 1 --If date of birth day less than date passed subtract one year WHEN MONTH(@DoB) - MONTH(@cDate) = 0 AND DAY(@DoB) - DAY(@cDate) &gt; 0 THEN 1 --All cases passed subtract zero ELSE 0 END </code></pre>
8,193
<p>When I first got my 3D printer (a FlashForge Adventurer 3), it came with a sample pack of filament. With this filament, I was able to use skirts for my first layer. When the sample filament ran out, I switched to Hatchbox PLA filament. For some reason, I cannot use skirts with the Hatchbox filament. Now, whenever I try to print something with a skirt, the print moves around, ruining it. The only first-layer that works now are rafts, which I do not like, as they use up more filament and are more of a pain to remove. Is anyone else having this problem? If so, what are some workarounds to this issue?<img src="https://i.stack.imgur.com/913g2.jpg" alt="Here are the failed prints. I terminated them mid-way, as they started to shift on the build plate." /></p> <blockquote> <p>Here are the failed prints. I terminated them mid-way, as they started to shift on the build plate.</p> </blockquote>
<p>PLA is a forgiving filament, you can even print such filament without a heated bed. Although there are differences in quality between brands, PLA shouldn't need a raft to be printed. Hatchbox filament is not considered as a low quality type of filament; it is economical and has been around since 2013. A raft is a structured platform that is specifically used for high temperature and or high shrinkage types of filament, PLA is not such a filament and shouldn't need a raft. This implies that something is wrong with getting the filament sticking to the plate. Good adhesion requires a levelled bed, a correct initial nozzle to build plate distance (e.g. paper thickness) and possibly an adhesive like a glue stick, special adhesion spray, a textured bed or blue tape, etc.</p>
<p>Please try one (or more) of the following:</p> <ol> <li><p>Change the temperature of your heated bed (50 - 60 °C)</p> </li> <li><p>Check your nozzle height (0.15 - 0.25 mm is what I use)</p> </li> <li><p>Make sure your bed is level (Maybe use a leaving stick (or whatever those bubble things are called))</p> </li> <li><p>Use adhesion. Start with painter's tape (least damaging, easy to remove), then use a glue stick or even hair spray if necessary.</p> </li> <li><p>Be sure the bed is clean (I recommend glass cleaner 1-3 squirts and then a light scrub of a paper towel)</p> </li> </ol>
1,933
<p>I am looking for a best practice for End to End Authentication for internal Web Applications to the Database layer.</p> <p>The most common scenario I have seen is to use a single SQL account with the permissions set to what is required by the application. This account is used by all application calls. Then when people require access over the database via query tools or such a separate Group is created with the query access and people are given access to that group.</p> <p>The other scenario I have seen is to use complete Windows Authentication End to End. So the users themselves are added to groups which have all the permissions set so the user is able to update and change outside the parameters of the application. This normally involves securing people down to the appropriate stored procedures so they aren't updating the tables directly. </p> <p>The first scenario seems relatively easily to maintain but raises concerns if there is a security hole in the application then the whole database is compromised.</p> <p>The second scenario seems more secure but has the opposite concern of having to much business logic in stored procedures on the database. This seems to limit the use of the some really cool technologies like Nhibernate and LINQ. However in this day and age where people can use data in so many different ways we don't foresee e.g. mash-ups etc is this the best approach.</p>
<p>Dale - That's it exactly. If you want to provide access to the underlying data store to those users then do it via services. And in my experience, it is those experienced computer users coming out of Uni/College that damage things the most. As the saying goes, they know just enough to be dangerous.</p> <p>If they want to automate part of their job, and they can display they have the requisite knowledge, then go ahead, grant their <strong>domain account</strong> access to the backend. That way anything they do via their little VBA automation is tied to their account and you know exactly who to go look at when the data gets hosed. </p> <p>My basic point is that the database is the proverbial holy grail of the application. You want as few fingers in that particular pie as possible. </p> <p>As a consultant, whenever I hear that someone has allowed normal users into the database, my eyes light up because I know it's going to end up being a big paycheck for me when I get called to fix it.</p>
<p>I've been responsible for developing several internal web applications over the past year.</p> <p>Our solution was using Windows Authentication (Active Directory or LDAP).</p> <p>Our purpose was merely to allow a simple login using an existing company ID/password. We also wanted to make sure that the existing department would still be responsible for verifying and managing access permissions.</p> <p>While I can't answer the argument concerning Nhibernate or LINQ, unless you have a specific killer feature these things can implement, Active Directory or LDAP are simple enough to implement and maintain that it's worth trying.</p>
10,442
<p>After some months of good quality prints, since yesterday my heatbed does not heat anymore.</p> <p>I've a BQ Prusa i3 Hephestos with <a href="https://www.reprap.org/wiki/File:RRD-Mk2b-dual-power_blk.jpg" rel="nofollow noreferrer">this</a> heatbed, controlled by <a href="https://images-na.ssl-images-amazon.com/images/I/71M29xMMLZL._AC_SY355_.jpg" rel="nofollow noreferrer">this</a> mechanical relay and powered by <a href="https://www.amazon.it/Lixada-Trasformatore-Tensione-Interruttore-Alimentazione/dp/B00ECW6K74" rel="nofollow noreferrer">this</a> power source. I know that a mechanical relay is not the best choice for a 3D printer, but I only had one of those when I've built the bed and setting <em>bang bang control</em> for the plate gave me some satisfactory prints.</p> <p>Since if I connect directly the heatbed to the power source, the latter stops working (I think because of its shortage protection), I'm almost sure that in some way I've managed to fry my heatbed. Before buying a new one, though, I'd like to understand how I've broken the current heatbed without doing anything but printing, to avoid similar situations in the future.</p> <p>I'm afraid I've forgotten some component whose functionality is to protect the heatbed (maybe a diode or something similar, I'm sorry but I have never studied electronics).</p> <p>I've attached a very simple wiring diagram showing the current configuration.</p> <p><a href="https://i.stack.imgur.com/8bHA7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8bHA7.png" alt="Wiring diagram" /></a></p>
<p>I see four points of error:</p> <ul> <li>The heatbed could be faulty.</li> <li>The lines could be faulty.</li> <li>The trigger signal could be faulty.</li> <li>The power supply could be faulty.</li> </ul> <p>So, how to check what it might be? We need to measure, but we need to measure in a setup of 12/24 V circuits while they are live. While not necessarily considered &quot;dangerous&quot;, take extra precautions! Remove the parts you will need to access from the machine, ground the power supply, and use your utmost care! Make sure the heatbed is not connected to the Power supply, so we can measure it in the safest way.</p> <h1>Ruling out the Heatbed</h1> <p>The first step can be done without power: the resistance of the heatbed should be non-0, non-open line. It's best to measure directly at the input pins to the bed. If it shows close to 0 (some milli-Ohms), open line (OL), or no continuity (NC), it has a short or is burned out and needs to be replaced.</p> <h1>Ruling out the Power Supply</h1> <p>Once we have reached a safe setup, take a voltmeter and measure the voltage (potential difference) on the pins you reserve for the heatbed. If it is 12 V with some tolerance, it's good, otherwise you might need to get a new power supply or have a professional fix yours.</p> <h1>Ruling out the trigger signal</h1> <p>Next, move your measuring to the output of the board. Now order your board to heat up the bed. Make no illusions, we <strong>will</strong> trigger TRP, as the bed is disconnected. This will need us to reset the board between tests. You should see a 5 V trigger signal. If not, your board or firmware might be faulty and require different investigations.</p> <h1>Ruing out the lines and switch</h1> <p>Next step is to swap to Resistance mode on the multimeter and measure the resistance of the switch, best with the whole power line. Under &quot;heating&quot;, the setup should show a close to 0 Ohm resistance, if not it should show an infinite or open line.</p> <h1>What now?!</h1> <p>If it is neither of the 4, reassemble on the test stand, reconnect the bed to the power supply and investigate all connections between the elements we just checked. Now order a heating procedure - as all components should be ok, it has to be one of the interfaces between the parts.</p>
<p>Assuming you are using the correct voltage hot bed, what you have set up should be just fine.</p> <p>On the other hand, if it’s a 12 volt bed with a 24 volt power supply, you could have easily burned it out.</p> <p>If the voltages were matched properly, you may have just gotten unlucky.</p>
1,758
<p>I am playing with a CAD application using MFC. I was thinking it would be nice to save the document (model) as an SQLite database.</p> <p>Advantages:</p> <ul> <li>I avoid file format changes (SQLite takes care of that)</li> <li>Free query engine</li> <li>Undo stack is simplified (table name, column name, new value and so on...)</li> </ul> <p>Opinions?</p>
<p>This is a fine idea. Sqlite is very pleasant to work with!</p> <p>But remember the old truism (I can't get an authoritative answer from Google about where it originally is from) that storing your data in a relational database is like parking your car by driving it into the garage, disassembling it, and putting each piece into a labeled cabinet.</p> <p>Geometric data, consisting of points and lines and segments that refer to each other by name, is a good candidate for storing in database tables. But when you start having composite objects, with a heirarchy of subcomponents, it might require a lot less code just to use serialization and store/load the model with a single call.</p> <p>So that would be a fine idea too.</p> <p>But serialization in MFC is not nearly as much of a win as it is in, say, C#, so on balance I would go ahead and use SQL.</p>
<p>This is a great idea but before you start I have a few recommendations:</p> <ul> <li><p>Be careful that each database is uniquely identifiable in some way besides file name such as having a table that describes the file within the database.</p></li> <li><p>Take a look at some of the MFC based examples and wrappers already available before creating your own. The ones I have seen had borrowed on each to create a better result. Google: MFC SQLite Wrapper.</p></li> <li><p>Using SQLite database is also useful for maintaining state. Think ahead about how you would manage keeping in mind what features are included and are missing in SQLite.</p></li> <li><p>You can also think now about how you may extend your application to the web by making sure your database table structure is easily exportable to other SQL database systems- as well as easy enough to extend to a backup system.</p></li> </ul>
18,581
<p>I've been trying to learn about Neural Networks for a while now, and I can understand some basic tutorials online, and I've been able to get through portions of <a href="https://rads.stackoverflow.com/amzn/click/com/0852742622" rel="noreferrer" rel="nofollow noreferrer">Neural Computing - An Introduction</a> but even there, I'm glazing over a lot of the math, and it becomes completely over my head after the first few chapters. Even then its the least book "math-y" I can find. </p> <p>Its not that I'm afraid of the math or anything, its just I haven't learned what I need, and I'm not sure what I need exactly. I'm currently enrolled at my local university, working on catching up on classes I need to enter the MS in Comp. Sci program (my BA is in Business/Info. Sys.) and I haven't gotten very far. According to the university's little course descriptions, NN's are actually covered in a Electrical Engineering course on Pattern Recognition (seems odd to me that this course is EE), which has a few EE prereq's that I don't need to get into the MS Comp. Sci. Program.</p> <p>I'm extremely interested in this topic, and know I eventually want to learn a lot more about it, the problem is, I don't know what I need to know first. Here are topics I think I might need, but this is just speculation from ignorance:</p> <ul> <li>Single Variable Calculus (I've had Calc I and II, so I think I'm covered here, just listing for completeness)</li> <li>Multi Variable Calculus</li> <li>Linear Algebra (I've not taken this formally yet, but can actually understand many of the concepts from what I've managed to grok on Wikipedia and other sites)</li> <li>Discrete Mathematics (Another I've not taken formally, but learned a portion of on my own</li> <li>Graph Theory</li> <li>Probability Theory</li> <li>Bayesian Statistics</li> <li>Circuit Design</li> <li>Other maths?</li> <li>Other comp sci topics </li> </ul> <p>Obviously there is a neuroscience component here as well, but I actually haven't had any trouble understanding books when they talk about it as applied to NN's, largely because its conceptual</p> <p>In short, Can someone lay out a semi-clear path that one needs to really understand, read book on and eventually implement Neural Networks?</p>
<p>If you want a list of college courses that you'll need to understand the book, here it is:</p> <ul> <li>Calculus (I, II and III)</li> <li>Differential Equations</li> <li>Linear Algebra</li> <li>Statistics (or a good covering of Bayes)</li> </ul> <p>However, I did just fine in my NN classes without Diff. Eq. and just had to look up concepts I hadn't studied yet.</p> <p>You can take the black box approach as above, but if you really want to understand the math and implementation of the networks, you'll have to study. It's going to be a steep learning curve to fully grasp the more advanced networks no matter what you do. You can either take the above classes first, or you can start reading the book and look up everything you don't grasp on wikipedia, and then from those articles read whatever you have to read to understand them, etc. You will find that, either way, you'll eventually get past that initial peek and things will be easier.</p> <p>It would be good if you told us why you want to learn neural networks. I've not found a single use for them in my professional career, though I'm not a game developer or telecommunications developer.</p>
<p>even though i am answering it in 2018 but i think it will help a lot of newcomers who are trying to learn neural network. All the online course material available online expect the reader to have high degree of mathematical knowledge or experience. There is a book called "MAKE YOUR OWN NEURAL NETWORK" by Tariq Rashid. It expects the reader to have highschool maths knowledge. that's all . by the end of the book you would be capable of making a program that reads your handwriting.</p>
43,641
<p>I have this PHP script that I wrote to automatically follow users that post messages with certain terms. It works 100% of the time on a bunch of test accounts but then does not work on the account I'd like to use it with. </p> <p>I've checked the account's API rate limit and it's well within the boundaries. I've also verified that the username and password are correct. If I change nothing else but the username and password to another account it will work, but when changed back (correctly) to the main account nothing happens. I am totally baffled. Has anyone ever come across this?</p> <p>I'm including the two files used below. If there's any other info that would be helpful, let me know and I'll provide it if I can. Thanks!</p> <p>Index.php </p> <pre><code>&lt;?php $url = "http://search.twitter.com/search.atom?q=SEARCHTERM&amp;show_user=true&amp;rpp=100"; $search = file_get_contents($url); $regex_name = '/\&lt;name\&gt;(.+?) \(/'; preg_match_all($regex_name,$search,$user); for($i=0;$user[1][$i];$i++) { $follow = $user[1][$i]; include("follow.php"); } ?&gt; </code></pre> <p>Follow.php</p> <pre><code>&lt;?php define('TWITTER_CREDENTIALS', 'username:password'); $url = "http://twitter.com/friendships/create/".$follow.".xml"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_USERPWD, TWITTER_CREDENTIALS); $result= curl_exec ($ch); curl_close ($ch); ?&gt; </code></pre> <p>Quick update on this: Turns out the problem was on Twitter's end--the account in question had tighter than normal API limits imposed for some reason. I'm not marking any responses as the answer since it was a rather idiosyncratic instance.</p>
<p>To debug your cURL request everything has been said, but maybe you could use <a href="http://pear.php.net/package/Services_Twitter" rel="nofollow noreferrer">Services_Twitter</a>, which is a package wrapped around the Twitter-API. It provides pretty robust response handling.</p> <p>Currently supports search and friendships also.</p> <p>If you don't want to do that, then just for the Twitter-Search API, I'd use JSON and do something like this:</p> <pre><code>&lt;?php $url = "http://search.twitter.com/search.json?q=SEARCHTERM&amp;show_user=true&amp;rpp=100"; $search = file_get_contents($url); if ($search === false) { die('Error occurred.'); } $hits = json_decode($search); var_dump($hits); ?&gt; </code></pre> <p>It's less parsing, and <a href="http://docs.php.net/json" rel="nofollow noreferrer">ext/json</a> is available in <em>most</em> PHP5 installations.</p>
<p>Try using:</p> <pre><code>curl_setopt($ch, CURLOPT_VERBOSE, 1); </code></pre> <p>to and see if it helps identifying the problem.</p>
35,843
<p>I'm sure that all of us have had to deal with telecommuters at some point in time, and I'm facing a situation now where my new project will have a "core" group of office workers and some off-site telecommuters. Not wanting to repeat past mistakes, I'd really like to know what ways people have tried in the past to effectively integrate telecommuters in an agile process, namely scrum.</p> <p>My first fear is that the telecommuters will be the first ones to break the "daily scrum" routine. And, as human nature often goes, once that gets broken, it's hard to resume and get people back on track. Scrum recommends enforcing small, fun "penalties" for people missing or being late to the daily scrum, like donating a few bucks to a jar which would later be used to buy a case of beers for the end-project party or something. This is obviously something that would be difficult to enforce online.</p> <p>The other big problem with telecommuters is the "out of sight, out of mind" problem. Aside from using webcams/skype/teleconferencing, what other tips do people have for keeping the team as closely knit as possible?</p> <p>Also, what about dealing with telecommuters from different timezones? At the moment, we're lucky enough not to have this problem, but it's definitely a possibility at some point in the future. How have other teams dealt with this problem?</p>
<p>Set the ground rules upfront. Don't be wishy-washy about them.</p> <p>You've probably eliminated the "I got stuck in traffic" excuse for missing the meeting or whatever when they're working from home (or a satellite site) and so there's no reason to expect less out of them.</p> <p>Take advantage of technology:</p> <ul> <li>Use IM. We use it here and it is great for 'reaching out and touching' the guy four states away. Make it a requirement to be available via IM.</li> <li>Use other tools to help break down the barriers. It'll depend on your situation.</li> </ul> <p>If you're having the daily meeting, it should be clear to everyone that you're going to be asking the questions:</p> <ul> <li><p>What did you accomplish since we last met?</p></li> <li><p>What are you going to be doing today?</p></li> <li><p>What's in the way that needs to be moved?</p></li> </ul> <p>Just because you can't see Matt in his cube doesn't give me a right to be lazy or unproductive and unresponsive. It's like dealing with my kids - let them know the rules and what is expected, then nobody can claim ignorance.</p>
<p>One place I worked used Asterisk instead of a normal phone system. It worked well because when you are working from home, you simply log on, people can call your direct line number, outsiders don't need to know. Even though phone call cost are relativity trivial these days, having a 'always on' connection encourages more communication. The sound quality is better too. </p>
23,194
<p>How can I play audio (it would be like a 1 second sound) from a Python script?</p> <p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p> <p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
<p>Your best bet is probably to use <a href="http://www.pygame.org" rel="noreferrer">pygame/SDL</a>. It's an external library, but it has great support across platforms.</p> <pre><code>pygame.mixer.init() pygame.mixer.music.load("file.mp3") pygame.mixer.music.play() </code></pre> <p>You can find more specific documentation about the audio mixer support in the <a href="http://www.pygame.org/docs/ref/music.html" rel="noreferrer">pygame.mixer.music documentation</a></p>
<p>If you're on OSX, you can use the "os" module or "subprocess" etc. to call the OSX "play" command. From the OSX shell, it looks like </p> <p>play "bah.wav"</p> <p>It starts to play in about a half-second on my machine.</p>
32,602
<p>In a C# Web app, VS 2005 (I am avoiding 2008 because I find the IDE to be hard to deal with), I am getting into a layout stew.</p> <p>I am moving from absolute positioning toward CSS relative positioning.</p> <p>I'd like to divide the screen into four blocks: top (header band), middle left (a stacked menu), middle right (content - here the AJAX tab container), and bottom (footer band), with all 4 blocks positioned relatively, but the controls in the middle right (content) block positioned absolutely relative to the top left corner of the block. A nice side benefit would be to have the IDE design window show all controls as they actually would be displayed, but I doubt this is possible. The IDE is positioning all controls inside the tab panels relative to the top left of the design window; quite a mess.</p> <p>Right now, my prejudice is that CSS is good for relatively positioning blocks, artwork, text etc, but not good for input forms where it is important to line up lots of labels, text boxes, ddl's, check boxes, etc.</p> <p>At any rate, my CSS is not yet up to the task - does anyone know of a good article, book, blog, etc which discusses CSS as it is implemented in ASP.NET, and which might include an example with an AJAX tab control? Any help would be appreciated. </p> <p>Many thanks</p> <p>Mike Thomas </p>
<p>So far as I know, there's nothing specific to ASP.NET, and you are right (at least in 2008) about it not using referenced stylesheets.</p> <p>These may be of use to you, however:</p> <p><a href="http://www.positioniseverything.net/" rel="nofollow noreferrer">http://www.positioniseverything.net/</a> - Position is Everything, an excellent CSS resource.</p> <p><a href="http://www.alistapart.com/topics/code/css/" rel="nofollow noreferrer">http://www.alistapart.com/topics/code/css/</a> - A List Apart's CSS section, advice on specific techniques.</p> <p>Essentially, what you want is 4 main divs for your sight: header, footer, menu, content. Position each div as you like, and then adjust the positioning of their children, which most browsers will treat as 'position relative to my parent' (unless it's absolute, IIRC).</p>
<p>As Jeff says, there is nothing specific to ASP.NET with regards to how CSS is implemented. As for styling your forms with CSS have a read of these to give you some ideas:</p> <ul> <li><a href="http://www.sitepoint.com/article/fancy-form-design-css/" rel="nofollow noreferrer">http://www.sitepoint.com/article/fancy-form-design-css/</a></li> <li><a href="http://www.smashingmagazine.com/2006/11/11/css-based-forms-modern-solutions/" rel="nofollow noreferrer">http://www.smashingmagazine.com/2006/11/11/css-based-forms-modern-solutions/</a></li> <li><a href="http://www.quirksmode.org/css/forms.html" rel="nofollow noreferrer">http://www.quirksmode.org/css/forms.html</a></li> </ul>
19,087
<p>Have you used the Application Recovery APIs with vista? </p> <p><a href="http://msdn.microsoft.com/en-us/library/aa373347(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa373347(VS.85).aspx</a></p> <p>Do you find them to be reliable and easy to work with? </p> <p>I am reading through some of the docs and it seems rolling my own might be a better way to go because I can make my solution compatible with XP. Has anyone taken a stab at writing their own? Is there anything that the native methods can offer that cannot easily be reproduced by hand? What are some potential approaches for writing this type of solution, I feel that I may need a background service running to monitor the health of my application, is this the only way?</p>
<p>It would be helpful if you describe why you need to monitor it. </p> <p>Is it running unattended without a GUI? Then you might create a Windows Service instead. There are restart options for Services already in XP.</p> <p>Is it a GUI app, that provides some background services even if the user is away? Consider separating it into a Windows Service (that needs to run all the time), and a GUI app, which can crash without affecting the service operation.</p> <p>Or are you writing a "kiosk" app that can't rely on a user to restart it? </p> <p>You could write a small "wrapper" application that simply launches your real application and waits for it to exit. When it exits, examine e.g. the exit code to decide whether it crashed or exited regularly.</p> <p>To monitor application hangs, have your real application "Ping" the wrapper in regular intervals (using a timer). If the wrapper doesn't receive a ping for a certain amount of time, it can kill and restart the real application.</p> <p>Since the wrapper is small, the risk that it crashes as well is low. But if this is an issue for you, the real app could probably monitor the wrapper in reverse.</p>
<p>The only way is to have a service monitoring the application. </p> <p>The reason being that if the application has a truly fatal error that the app itself can't handle, then something outside of it has to perform the recovery operation.</p> <p>The background service can use WMI (works on XP, Vista, etc) to monitor the application. When it starts, how much memory it is using, when it closes down, etc. </p>
46,483
<p>What's a more elegant way of having the code below where i want to return a derived class based on the type of another class.</p> <pre><code> if (option_ is Rectangle) { modelInputs = new Foo(); } else if (option_ is Circle) { modelInputs = new Bar(); } else if (option_ is Triangle) { modelInputs = new Bar2(); } </code></pre>
<p>Have Rectangle, Circle and Triangle implement IHasModelInput:</p> <pre><code>interface IHasModelInput { IModelInput GetModelInput(); } </code></pre> <p>then you can do</p> <pre><code>IModelInput modelInputs = option_.GetModelInput(); </code></pre>
<p>You could associate a type with "option_", if it allows, and then just create an instance of it.</p>
29,970
<p>I would like to ensure that I only subscribe once in a particular class for an event on an instance.</p> <p>For example I would like to be able to do the following:</p> <pre><code>if (*not already subscribed*) { member.Event += new MemeberClass.Delegate(handler); } </code></pre> <p>How would I go about implementing such a guard?</p>
<p>If you are talking about an event on a class that you have access to the source for then you could place the guard in the event definition.</p> <pre><code>private bool _eventHasSubscribers = false; private EventHandler&lt;MyDelegateType&gt; _myEvent; public event EventHandler&lt;MyDelegateType&gt; MyEvent { add { if (_myEvent == null) { _myEvent += value; } } remove { _myEvent -= value; } } </code></pre> <p>That would ensure that only one subscriber can subscribe to the event on this instance of the class that provides the event.</p> <p><strong>EDIT</strong> please see comments about why the above code is a bad idea and not thread safe.</p> <p>If your problem is that a single instance of the client is subscribing more than once (and you need multiple subscribers) then the client code is going to need to handle that. So replace </p> <blockquote> <p><em>not already subscribed</em></p> </blockquote> <p>with a bool member of the client class that gets set when you subscribe for the event the first time.</p> <p><strong>Edit (after accepted):</strong> Based on the comment from @Glen T (the submitter of the question) the code for the accepted solution he went with is in the client class:</p> <pre><code>if (alreadySubscribedFlag) { member.Event += new MemeberClass.Delegate(handler); } </code></pre> <p>Where alreadySubscribedFlag is a member variable in the client class that tracks first subscription to the specific event. People looking at the first code snippet here, please take note of @Rune's comment - it is not a good idea to change the behavior of subscribing to an event in a non-obvious way.</p> <p><strong>EDIT 31/7/2009:</strong> Please see comments from @Sam Saffron. As I already stated and Sam agrees the first method presented here is not a sensible way to modify the behavior of the event subscription. The consumers of the class need to know about its internal implementation to understand its behavior. Not very nice.<br> @Sam Saffron also comments about thread safety. I'm assuming that he is referring to the possible race condition where two subscribers (close to) simultaneously attempt to subscribe and they may both end up subscribing. A lock could be used to improve this. If you are planning to change the way event subscription works then I advise that you <a href="https://stackoverflow.com/questions/1037811/c-thread-safe-events">read about how to make the subscription add/remove properties thread safe</a>.</p>
<p>Invoke only distinct elements from <code>GetInvocationList</code> while raising:</p> <pre><code>using System.Linq; .... public event HandlerType SomeEvent; .... //Raising code foreach (HandlerType d in (SomeEvent?.GetInvocationList().Distinct() ?? Enumerable.Empty&lt;Delegate&gt;()).ToArray()) d.Invoke(sender, arg); </code></pre> <p>Example unit test:</p> <pre><code>class CA { public CA() { } public void Inc() =&gt; count++; public int count; } [TestMethod] public void TestDistinctDelegates() { var a = new CA(); Action d0 = () =&gt; a.Inc(); var d = d0; d += () =&gt; a.Inc(); d += d0; d.Invoke(); Assert.AreEqual(3, a.count); var l = d.GetInvocationList(); Assert.AreEqual(3, l.Length); var distinct = l.Distinct().ToArray(); Assert.AreEqual(2, distinct.Length); foreach (Action di in distinct) di.Invoke(); Assert.AreEqual(3 + distinct.Length, a.count); } [TestMethod] public void TestDistinctDelegates2() { var a = new CA(); Action d = a.Inc; d += a.Inc; d.Invoke(); Assert.AreEqual(2, a.count); var distinct = d.GetInvocationList().Distinct().ToArray(); Assert.AreEqual(1, distinct.Length); foreach (Action di in distinct) di.Invoke(); Assert.AreEqual(3, a.count); } </code></pre>
47,967
<p>I have an XLL Excel addin and now another team wants to use the same functionality in their project (unmanaged C++). Is there a way to interface with this XLL directly from C++?</p>
<p>PreviewMouseDown is your friend...</p> <p>Add this event to your control, and set the Handled property on true...</p> <p>All events tunnel first from root to leaves in the preview fase, then they are handled from leaves to root in the actual event case...</p> <p>So PreviewMouseDown handles the Grid before the Button, while the MouseDown event handles the Button before the Grid...</p> <p>hope this helps...</p>
<p>You should be able to extend whatever control you want (assuming it is not sealed). In your extended class you can override the click event and swallow it (do not pass it to the base class).</p>
35,096
<p>There is a simple C++ method to use pattern matching on strings? The code should sound like this:</p> <pre><code>if (regexpcmp("l?nole*[0-9]", "linoleum1")) { //we have a match! } else { //no match } </code></pre>
<p>Did you already look at <a href="http://www.boost.org/doc/libs/release/libs/regex/" rel="nofollow noreferrer">Boost.Regex</a>?</p> <pre><code>const boost::regex e("l?nole*[0-9]"); if (regex_match("linoleum1", e)) { //we have a match! } else { //no match } </code></pre>
<p>A standard regex library (that is based on boost::regex) is available in the TR1 namespace if you use lasts versions of the most used compilers : std::tr1::regex.</p>
42,696
<p>I created a program using dev-cpp and wxwidgets which solves a puzzle.</p> <p>The user must fill the operations blocks and the results blocks, and the program will solve it. I'm solving it using brute force, I generate all non-repeated 9 length number combinations using a recursive algorithm. It does it pretty fast.</p> <p>Up to here all is great!</p> <p>But the problem is when my program operates depending the character on the blocks. Its extremely slow (it never gets the answer), because of the chars comparation against +, -, *, etc. I'm doing a CASE.</p> <p>Is there some way or some programming language which allows dynamic creation of operators? So I can define the operator ROW1COL2 to be a +, and the same way to all other operations.</p> <p>I leave a screenshot of the app, so its easier to understand how the puzzle works.</p> <p><a href="http://www.imageshare.web.id/images/9gg5cev8vyokp8rhlot9.png" rel="nofollow noreferrer">http://www.imageshare.web.id/images/9gg5cev8vyokp8rhlot9.png</a><br> <a href="http://www.imageshare.web.id/" rel="nofollow noreferrer"></a></p> <p>PD: The algorithm works, I tried it with a trivial puzzle, and solved it in a second.</p>
<p>Not sure that this is really what you're looking for but..<br> Any Object Oriented language such as C++ or C# will allow you to create an "Operator" base class and then to derive from this base class a "PlusOperator" or "MinusOperator" etc'. this is the standard way to avoid such case statements. </p> <p>However I am not sure this will solve your performance problem.<br> Using plain brute force for such a problem will result you in an exponential solution. this will seem to work fast for small input - say completing all the numbers. But if you want to complete the operations its a much larger problem with alot more possibilities.<br> So its likely that even without the CASE your program is not going to be able to solve it.</p> <p>The right way to try to solve this kind of problems is using some advanced search methods which use some Heuristic function. See the <a href="http://en.wikipedia.org/wiki/A_star" rel="nofollow noreferrer">A* (A-star) algorithm</a> for example.</p> <p>Good luck!</p>
<p>You can represent the numbers and operators as objects, so the parsing is done only once in the beginning of the solving.</p>
13,440
<p>I work in a biological laboratory where we have been using the FABtotum personal fabricator for several months now. The machine is good, however not flawless, and has set us back from doing experiments.</p> <p>I have overcome many common 3D printing issues, which I find necessary to do when becoming proficient in this technique. However the printer has also had its own personal mechanical and software issues.</p> <p>Our lab is seeking a printer that is more reliable, can produce parts relatively quick, good resolution, and it is nice if it has multiple modes (i.e FDM, SLA, and even 3D scanning is nice). This is what we figured we were getting with the FABtotum, but as I mentioned it has produced setbacks.</p> <p>Now I would love to tinker with the printer and modify it to my needs, but unfortunately our lab is strapped for time, however we have funding for a higher quality printer if there is one.</p> <p>Can you anyone recommend a printer fitting these needs in these budget categories?:</p> <ul> <li><p>3000 USD</p></li> <li><p>5000 USD</p></li> <li><p>8000 USD or more</p></li> </ul> <p>I know price doesn't equate quality, but I am saying that we are willing to pay more if that is where the quality lies.</p> <p>For example, I have come across the Form 2, Ultimaker, and BCN3D sigma printers which seem quite nice. Any opinions are very appreciated.</p>
<p>I have only tried 2 different printers. I started with an Up plus printer and it was good to get started. After a few years you really want more control. I did a lot of research and ended up buying the Extrabot. It is based on the ultimaker however the guy that puts them together upgrades the motors and a few other parts to really make them work with multiple filament.</p> <p>You have control over all the settings so using exotic filaments is a viable option.</p>
<p>I have only tried 2 different printers. I started with an Up plus printer and it was good to get started. After a few years you really want more control. I did a lot of research and ended up buying the Extrabot. It is based on the ultimaker however the guy that puts them together upgrades the motors and a few other parts to really make them work with multiple filament.</p> <p>You have control over all the settings so using exotic filaments is a viable option.</p>
596
<p>Greetings,</p> <p>I need to include a property in my class which is a collection of System.IO.FileInfo objects. I am not really sure how to do this and how I would add and removed objects from an instance of the the class (I would assume like any other collection). </p> <p>Please let me know if I need to add more information.</p> <p>Thank you</p> <p>Update: Am I approaching this the wrong way? I have read comments that adding to a collection which is a property is bad practice. If this is true what is good practice? I have a bunch of objects I need to store in a collection. The collection will be added to and removed from before a final action will be taken on it. Is this a correct approach or am I missing something?</p>
<p><code>File</code> is a static class. So let's assume you meant <code>FileInfo</code>.</p> <p>There are lots of ways, you can:</p> <ul> <li>Expose a private field</li> <li>Use Iterators</li> <li>Expose a private field through a ReadOnlyCollection&lt;></li> </ul> <p>For example,</p> <pre><code>class Foo { public IEnumerable&lt;FileInfo&gt; LotsOfFile { get { for (int i=0; i &lt; 100; i++) { yield return new FileInfo("C:\\" + i + ".txt"); } } } private List&lt;FileInfo&gt; files = new List&lt;FileInfo&gt;(); public List&lt;FileInfo&gt; MoreFiles { get { return files; } } public ReadOnlyCollection&lt;FileInfo&gt; MoreFilesReadOnly { get { return files.AsReadOnly(); } } } </code></pre> <p>With this code, you can easily add to the property <code>MoreFiles</code>:</p> <pre><code>Foo f = new Foo(); f.MoreFiles.Add(new FileInfo("foo.txt")); f.MoreFiles.Add(new FileInfo("BAR.txt")); f.MoreFiles.Add(new FileInfo("baz.txt")); Console.WriteLine(f.MoreFiles.Count); </code></pre>
<p>One simple way to do this is to create a property as such (sorry for the VB.Net)</p> <pre><code>Public ReadOnly Property Files As Generic.List(Of IO.File) GET Return _Files END GET END Property </code></pre> <p>Where _Files is a private class variable of type Generic.List(Of IO.File), which holds the list of files. That will allow files to be added and removed by calling the functions of the List data type. Some people will probably say this is bad practice, and that you should never expose the collection itself, and instead recode all the necessary functions as separate parameters, which would basically just call the appropriate functions from your private collection. </p>
20,469
<p>With the asp.net MVC framework the blogs of the team members (Rob Conery, Phil Haack etc) really helped me on my way and made me feel comfortable the development was going in the right direction. Is there something similar for Silverlight?</p> <p>-Edit: I would like to mention that I would like to find members of the dev team themselves. Currently the support for Silverlight across OS and browser is just too poor to make me care and invest time in it. But I would like to keep a spying eye out so I can start caring when the framework fulfils it's potentials.</p>
<p>Method ~ of ~ failed by Tim Heuer: <a href="http://feeds.timheuer.com/timheuer-silverlight" rel="nofollow noreferrer">http://feeds.timheuer.com/timheuer-silverlight</a></p> <p>Jesse Liberty - Silverlight Geek: <a href="https://feeds.feedburner.com/JesseLiberty-SilverlightGeek" rel="nofollow noreferrer">http://feeds.feedburner.com/JesseLiberty-SilverlightGeek</a></p> <p>Community Silverlight content: <a href="https://web.archive.org/web/20090813030220/http://silverlight.net/blogs/community/rss.aspx" rel="nofollow noreferrer">http://silverlight.net/blogs/community/rss.aspx</a></p> <p>Silverlight Tips of the Day <a href="https://web.archive.org/web/20090628120009/http://silverlight.net:80/blogs/msnow/default.aspx" rel="nofollow noreferrer">http://silverlight.net/blogs/msnow/default.aspx</a></p> <p>Podcasts: <a href="https://sparklingclient.com/" rel="nofollow noreferrer">http://www.sparklingclient.com/</a></p> <p>Wynapse (Mining the Web for Silverlight so YOU don't have to): <a href="https://web.archive.org/web/20170226214423/http://www.geekswithblogs.net:80/WynApseTechnicalMusings/Default.aspx" rel="nofollow noreferrer">http://geekswithblogs.net/WynApseTechnicalMusings/Default.aspx</a></p>
<p><a href="http://weblogs.asp.net/Scottgu/" rel="nofollow noreferrer">Scott Guthrie</a> the product manager of .NET Framework writes form time to time about Silverlight in his <a href="http://weblogs.asp.net/Scottgu/" rel="nofollow noreferrer">blog</a>. He reports about new releases and the feature they come with it and sometimes he posts some really nice tutorials to give examples how to use these features. </p> <p>But of course the blog's focus lies more on the whole .NET Framework as only on Silverlight. </p>
26,756
<p>Interested if anyone has used VSTS Database Edition extensively and, if so, which features did you find the most useful over the standard Visual Studio database projects?</p> <p>What are the most compelling features as opposed to alternative schema management options or tools like RedGate's SqlCompare etc?</p> <p><strong>Edit</strong>: Microsoft just released the <b>RTM version of Database Edition (GDR)</b> which adds support for SQL Server 2008 - link is <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=bb3ad767-5f69-4db9-b1c9-8f55759846ed&amp;displaylang=en" rel="nofollow noreferrer">here</a>. I've previously blogged (briefly) about it <a href="http://internationalized.spaces.live.com/blog/cns!43F3A7682D1564E4!1177.entry" rel="nofollow noreferrer">here.</a></p> <p>Has anyone had a chance to do any real work with the GDR? It looks like there are some real enhancements including refactoring support. I'd be really interested to hear if people are using it with SQL Server 2008...</p> <p>Download From: [<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=bb3ad767-5f69-4db9-b1c9-8f55759846ed&amp;displaylang=en]" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyID=bb3ad767-5f69-4db9-b1c9-8f55759846ed&amp;displaylang=en]</a></p>
<p>We use the database edition functionality of Team Suite on Stack Overflow. As Vaibhav said, <strong>mostly it is useful because it gives you a one-click way to reverse engineer a database into source control</strong>, and keep it up to date.</p> <p>Note that it also has decent Data and Schema compare tools as well. You can compare projects to physical databases and vice-versa. This makes it pretty easy to keep your database up to date, no matter where you make changes -- in the filesystem database project, or in the physical database itself.</p>
<p>You can do database versioning for one. That is useful.</p> <p>The other thing that is really useful is the ability to define type of seed data for testing. Through this Visual Studio will populate the database with random data and this is great for testing purposes.</p> <p>There are other benefits as well of course.</p>
20,497
<p>I've been thinking lately, would it be a good form of syntactic sugar in languages like Java and C#, to include a "duck" type as a method parameter type? This would look as follows:</p> <pre><code>void myFunction(duck foo) { foo.doStuff(); } </code></pre> <p>This could be syntactic sugar for invoking doStuff() via reflection, or it could be implemented differently. Foo could be any type. If foo does not have a doStuff() method, this would throw a runtime exception. The point is that you would have the benefits of the more rigid pre-specified interface paradigm (performance, error checking) when you want them, i.e. most of the time. At the same time, you'd have a simple, clean-looking backdoor to duck typing, which would allow you to cleanly make changes not foreseen in the initial design without massive refactoring. Furthermore, it would likely be 100% backwards compatible and mesh cleanly with existing language constructs. I think this might help cut down on the overengineered just-in-case programming style that leads to confusing, cluttered APIs. Do you believe that something like this would be a good or bad thing in static OO languages like C# and Java?</p>
<p>The <code>dynamic</code> keyword supports these exact semantics and will be in C# 4.0.</p> <p>It is not just for reflection, though. It is an implementation of <a href="http://en.wikipedia.org/wiki/Dynamic_dispatch" rel="nofollow noreferrer">dynamic dispatch</a> which uses reflection only if no other mechanism is available.</p> <p><a href="https://stackoverflow.com/questions/244302/what-do-you-think-of-the-new-c-40-dynamic-keyword">This question</a> also has lots of good information.</p>
<p>Actually, that's very much like the "dynamic" type that will be part of C#4.</p>
40,157
<p>The scriptaculous wiki has a demo (<a href="http://github.com/madrobby/scriptaculous/wikis/effect-slidedown" rel="nofollow noreferrer">http://github.com/madrobby/scriptaculous/wikis/effect-slidedown</a>) that shows the SlideDown effect in use. However I need to have the same link to slide down if a certain DIV is hidden and SlideUp if that DIV is showing.</p> <p>How do I achieve this?</p> <p>Thanks.</p>
<p>Use <a href="http://github.com/madrobby/scriptaculous/wikis/effect-toggle" rel="noreferrer">Effect.toggle</a>.</p> <pre><code>Effect.toggle('element_id', 'slide'); </code></pre>
<p>Wrap it in a function, call the function instead.</p> <pre><code>function slideMe(myDiv) { if(Element.visible(myDiv)) { //slide up } else { //slide down } } </code></pre>
30,788
<p>I am in the process of designing a .net windows forms application that uses metadata to drive the UI. Apart from finding <a href="http://msdn.microsoft.com/en-us/library/ms954610.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms954610.aspx</a>, I have nothing much to look forward to. Anyone here worked on metadata driven User interfaces? What are the implications of following this methodology and any pointers would be greatly helpful. </p>
<p>The most obvious answer would be that Microsoft have themselves embraced this concept through their use of Xaml in <a href="http://en.wikipedia.org/wiki/Windows_Presentation_Foundation" rel="nofollow noreferrer">Windows Presentation Foundation</a> which replaces WinForms (to an extent).</p> <p>If you want to stick to a WinForms, you may want to consider <a href="http://www.myxaml.com/" rel="nofollow noreferrer">MyXaml</a> which is kind of a homage to Xaml for WinForms!</p>
<p>You may want to check out Evolutility CRUD framework. It is an open source metadata driven framework for CRUD generating all UI at run-time.</p> <p>It comes w/ source code (in C# and JS) and many samples.</p> <p><a href="http://www.evolutility.org" rel="nofollow noreferrer">http://www.evolutility.org</a></p>
12,995
<p>I am using the following function to load a PlayList of Songs from 'PlayListJSON.aspx' but somethings seems wrong,evrytime OnFailure is getting called, I am unable to debug it further. any help would be really gr8.</p> <pre><code>Player.prototype.loadPlaylist = function(playlistId, play) { req = new Ajax.Request('/PlaylistJSON.aspx?id=' + playlistId, { method: 'GET', onSuccess: function(transport, json) { eval(transport.responseText); player.setPlaylist(playlist.tracklist, playlist.title, playlistId); player.firstTrack(); if (play) player.playSong(); }, onFailure: function() { //error } }); } </code></pre>
<p>Generally, OnFailure gets called when the page you are calling out to can't be reached for some reason.</p> <p>Are you positive that the URL <strong>/PlaylistJSON.aspx</strong> is valid?</p> <hr> <p>Have you tried passing the parameters argument instead of specifying them as part of the url?</p> <pre><code>req = new Ajax.Request('/PlaylistJSON.aspx', { method: 'GET', parameters: { 'id': playlistId }, onSuccess: function(transport,json){ eval(transport.responseText); player.setPlaylist(playlist.tracklist,playlist.title, playlistId); player.firstTrack(); if (play) player.playSong(); }, onFailure: function() { //error } }); </code></pre>
<p>Yes the Page PlayListJSon.aspx is in the root directory.</p>
29,242
<p>Given a latitude and longitude, what is the easiest way to find the name of the city and the US zip code of that location.</p> <p>(This is similar to <a href="https://stackoverflow.com/questions/23572/latitude-longitude-database">https://stackoverflow.com/questions/23572/latitude-longitude-database</a>, except I want to convert in the opposite direction.)</p> <hr> <p>Related question: <a href="https://stackoverflow.com/questions/158557/get-street-address-at-latlong-pair">Get street address at lat/long pair</a></p>
<p>This is the web service to call. <a href="http://developer.yahoo.com/search/local/V2/localSearch.html" rel="nofollow noreferrer">http://developer.yahoo.com/search/local/V2/localSearch.html</a></p> <p>This site has ok web services, but not exactly what you're asking for here. <a href="http://www.usps.com/webtools/" rel="nofollow noreferrer">http://www.usps.com/webtools/</a></p>
<p>geonames has an extensive set of ws that can handle this (among others): <br><br> <a href="http://www.geonames.org/export/web-services.html#findNearbyPostalCodes" rel="nofollow noreferrer">http://www.geonames.org/export/web-services.html#findNearbyPostalCodes</a><br> <a href="http://www.geonames.org/export/web-services.html#findNearbyPlaceName" rel="nofollow noreferrer">http://www.geonames.org/export/web-services.html#findNearbyPlaceName</a></p>
5,081
<p>These days, i came across a problem with Team System Unit Testing. I found that the automatically created accessor class ignores generic constraints - at least in the following case:</p> <p>Assume you have the following class:</p> <pre><code>namespace MyLibrary { public class MyClass { public Nullable&lt;T&gt; MyMethod&lt;T&gt;(string s) where T : struct { return (T)Enum.Parse(typeof(T), s, true); } } } </code></pre> <p>If you want to test MyMethod, you can create a test project with the following test method:</p> <pre><code>public enum TestEnum { Item1, Item2, Item3 } [TestMethod()] public void MyMethodTest() { MyClass c = new MyClass(); PrivateObject po = new PrivateObject(c); MyClass_Accessor target = new MyClass_Accessor(po); // The following line produces the following error: // Unit Test Adapter threw exception: GenericArguments[0], 'T', on // 'System.Nullable`1[T]' violates the constraint of type parameter 'T'.. TestEnum? e1 = target.MyMethod&lt;TestEnum&gt;("item2"); // The following line works great but does not work for testing private methods. TestEnum? e2 = c.MyMethod&lt;TestEnum&gt;("item2"); } </code></pre> <p>Running the test will fail with the error mentioned in the comment of the snippet above. The problem is the accessor class created by Visual Studio. If you go into it, you will come up to the following code:</p> <pre><code>namespace MyLibrary { [Shadowing("MyLibrary.MyClass")] public class MyClass_Accessor : BaseShadow { protected static PrivateType m_privateType; [Shadowing(".ctor@0")] public MyClass_Accessor(); public MyClass_Accessor(PrivateObject __p1); public static PrivateType ShadowedType { get; } public static MyClass_Accessor AttachShadow(object __p1); [Shadowing("MyMethod@1")] public T? MyMethod(string s); } } </code></pre> <p>As you can see, there is no constraint for the generic type parameter of the MyMethod method.</p> <p>Is that a bug? Is that by design? Who knows how to work around that problem?</p>
<p>I vote bug. I don't see how this could be by design.</p>
<p>Search for unit tests with generics on msdn. This is a known limitation. Vote for a resolution on Microsoft Connect, as it is definately needs resolving.</p>
9,042