instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm in the process of building a site with embedded videos. I'd prefer not dealing with the videos myself and instead use something like Vimeo Plus. I also would like the future administrators of the site to be able to upload videos directly from the administration interface of the site (i.e. so that they don't have to go to Vimeo for uploading). Vimeo doesn't appear to have an embeddable upload control. I could upload the videos to my server first, and then transfer it to Vimeo using their API, but a lot of things can go wrong in the process...</p> <p>Has anyone found a video service with an embeddable upload control, or solved this problem some other way?</p> <p>UPDATE: Looks like <a href="http://www.bitsontherun.com/api-documentation/" rel="nofollow noreferrer">bitsontherun</a> may be an option, or perhaps <a href="http://www.brightcove.com/products/developer-tools/technology-integrations/" rel="nofollow noreferrer">brightcove</a>. (Neither turn out to have prepackaged upload component).</p>
<p>Brightcove is definitely one way to go. They have full API's that allows you build a component for upload. They also provide a batch ingest process. I know this doesn't solve your embeddable component desire, but this can get on your way to creating one.</p>
<p>I just deployed a site where the administrators can upload videos to the server using <a href="http://www.fckeditor.net/" rel="nofollow noreferrer">FCKEditor</a>'s upload functionality hooked into a Drupal site. Security isn't as much of a worry since the capability is locked down by role, and like you say you can do whatever you want with the video file once it's on your server.</p>
37,092
<p>I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of</p> <pre><code>function editRecord() { var gridView = document.getElementById("&lt;%= GridView.ClientID %&gt;"); var id = // somehow get the id here ??? window.open("edit.aspx?id=" + id); } </code></pre> <p>The question is how do I retrieve the selected records ID in javascript?</p>
<p>I worked it out based on JasonS response. What I did was create a hidden field in the Grid View like this:</p> <pre><code>&lt;asp:TemplateField ShowHeader="False"&gt; &lt;ItemTemplate&gt; &lt;asp:HiddenField ID="hdID" runat="server" Value='&lt;%# Eval("JobID") %&gt;' /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField Visible="False"&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton ID="lnkSelect" runat="server" CommandName="select" Text="Select" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre> <p>Then on the OnRowDataBind have code to set the selected row</p> <pre><code>protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // Click to highlight row Control lnkSelect = e.Row.FindControl("lnkSelect"); if (lnkSelect != null) { StringBuilder click = new StringBuilder(); click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty)); click.AppendLine(String.Format("onGridViewRowSelected('{0}')", e.Row.RowIndex)); e.Row.Attributes.Add("onclick", click.ToString()); } } } </code></pre> <p>And then in the Javascript I have code like this</p> <pre><code>&lt;script type="text/javascript"&gt; var selectedRowIndex = null; function onGridViewRowSelected(rowIndex) { selectedRowIndex = rowIndex; } function editItem() { if (selectedRowIndex == null) return; var gridView = document.getElementById('&lt;%= GridView1.ClientID %&gt;'); var cell = gridView.rows[parseInt(selectedRowIndex)+1].cells[0]; var hidID = cell.childNodes[0]; window.open('JobTypeEdit.aspx?id=' + hidID.value); } &lt;/script&gt; </code></pre> <p>Works a treat :-)</p>
<p>one could avoid javascript altogether, by setting anchor tags pre-populated with the query string for each row (although this will effect your table layout, it will need only one click rather than 2 from the user) </p> <p>insert in the gridview template:</p> <pre><code>&lt;asp:HyperLink runat="server" ID="editLink" Target="_blank" NavigateURL='&lt;%# Eval("JobID","edit.aspx?id={0}") %&gt;'&gt; Edit.. &lt;/asp:HyperLink&gt; </code></pre>
28,281
<p>Suppose we have <em>n</em> elements, <em>a</em><sub>1</sub>, <em>a</em><sub>2</sub>, ..., <em>a</em><sub>n</sub>, arranged in a circle. That is, <em>a</em><sub>2</sub> is between <em>a</em><sub>1</sub> and <em>a</em><sub>3</sub>, <em>a</em><sub>3</sub> is between <em>a</em><sub>2</sub> and <em>a</em><sub>4</sub>, <em>a</em><sub><em>n</em></sub> is between <em>a</em><sub><em>n</em>-1</sub> and <em>a</em><sub>1</sub>, and so forth.</p> <p>Each element can take the value of either 1 or 0. Two arrangements are different if there are corresponding <em>a</em><sub><em>i</em></sub>'s whose values differ. For instance, when <em>n</em>=3, (1, 0, 0) and (0, 1, 0) are different arrangements, even though they may be isomorphic under rotation or reflection.</p> <p>Because there are <em>n</em> elements, each of which can take two values, the total number of arrangements is 2<sup><em>n</em></sup>.</p> <p><strong>Here is the question:</strong></p> <p>How many arrangements are possible, such that no two adjacent elements both have the value 1? If it helps, only consider cases where <em>n</em>>3. </p> <p>I ask here for several reasons:</p> <ol> <li>This arose while I was solving a programming problem</li> <li>It sounds like the problem may benefit from Boolean logic/bit arithmetic</li> <li>Maybe there is no closed solution.</li> </ol>
<p>Let's first ask the question "how many 0-1 sequences of length n are there with no two consecutive 1s?" Let the answer be A(n). We have A(0)=1 (the empty sequence), A(1) = 2 ("0" and "1"), and A(2)=3 ("00", "01" and "10" but not "11").</p> <p>To make it easier to write a recurrence, we'll compute A(n) as the sum of two numbers:<br/> B(n), the number of such sequences that end with a 0, and<br/> C(n), the number of such sequences that end with a 1.</p> <p>Then B(n) = A(n-1) (take any such sequence of length n-1, and append a 0)<br/> and C(n) = B(n-1) (because if you have a 1 at position n, you must have a 0 at n-1.)<br/> This gives A(n) = B(n) + C(n) = A(n-1) + B(n-1) = A(n-1) + A(n-2). By now it should be familiar :-)</p> <p>A(n) is simply the Fibonacci number F<sub>n+2</sub> where the Fibonacci sequence is defined by<br/> F<sub>0</sub>=0, F<sub>1</sub>=1, and F<sub>n+2</sub>= F<sub>n+1</sub>+F<sub>n</sub> for n &ge; 0.<br/></p> <p>Now for your question. We'll count the number of arrangements with a<sub>1</sub>=0 and a<sub>1</sub>=1 separately. For the former, a<sub>2</sub> &hellip; a<sub>n</sub> can be any sequence at all (with no consecutive 1s), so the number is A(n-1)=F<sub>n+1</sub>. For the latter, we must have a<sub>2</sub>=0, and then a<sub>3</sub>&hellip;a<sub>n</sub> is any sequence with no consecutive 1s that <em>ends with a 0</em>, i.e. B(n-2)=A(n-3)=F<sub>n-1</sub>.</p> <p>So <strong>the answer is F<sub>n+1</sub> + F<sub>n-1</sub>.</strong></p> <p><sub>Actually, we can go even further than that answer. Note that if you call the answer as<br/> G(n)=F<sub>n+1</sub>+F<sub>n-1</sub>, then <br/> G(n+1)=F<sub>n+2</sub>+F<sub>n</sub>, and <br/> G(n+2)=F<sub>n+3</sub>+F<sub>n+1</sub>, so even G(n) satisfies the same recurrence as the Fibonacci sequence! [Actually, any linear combination of Fibonacci-like sequences will satisfy the same recurrence, so it's not all that surprising.] So another way to compute the answers would be using:<br/> G(2)=3<br/> G(3)=4<br/> G(n)=G(n-1)+G(n-2) for n&ge;4.</p> <p>And now you can also use the <a href="http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html" rel="nofollow noreferrer">closed form</a> F<sub>n</sub>=(&alpha;<sup>n</sup>-&beta;<sup>n</sup>)/(&alpha;-&beta;) (where &alpha; and &beta; are (1±√5)/2, the roots of x<sup>2</sup>-x-1=0), to get <br/> <strong>G(n) = ((1+√5)/2)<sup>n</sup> + ((1-√5)/2)<sup>n</sup>.</strong><br/> [You can ignore the second term because it's very close to 0 for large n, in fact G(n) is the <strong>closest integer to ((1+√5)/2)<sup>n</sup></strong> for all n&ge;2.] </sub></p>
<p>Throwing my naive script into the mix. Plenty of opportunity for caching partial results, but it ran fast enough for small n that I didn't bother.</p> <pre><code>def arcCombinations(n, lastDigitMustBeZero): """Takes the length of the remaining arc of the circle, and computes the number of legal combinations. The last digit may be restricted to 0 (because the first digit is a 1)""" if n == 1: if lastDigitMustBeZero: return 1 # only legal answer is 0 else: return 2 # could be 1 or 0. elif n == 2: if lastDigitMustBeZero: return 2 # could be 00 or 10 else: return 3 # could be 10, 01 or 00 else: # Could be a 1, in which case next item is a zero. return ( arcCombinations(n-2, lastDigitMustBeZero) # If it starts 10 + arcCombinations(n-1, lastDigitMustBeZero) # If it starts 0 ) def circleCombinations(n): """Computes the number of legal combinations for a given circle size.""" # Handle case where it starts with 0 or with 1. total = ( arcCombinations(n-1,True) # Number of combinations where first digit is a 1. + arcCombinations(n-1,False) # Number of combinations where first digit is a 0. ) return total print circleCombinations(13) </code></pre>
46,198
<p>My requirements:</p> <ul> <li>Support .NET Compact Framework 2.0 and Windows Mobile 6.0 devices.</li> <li>Only need to unzip the contents to a directory on a storage card. Creation of zip files is not required.</li> <li>Must be able to use in corporate/commercial software.</li> <li>Can be open source, but not have GPL or other viral license.</li> </ul> <p>I've seen the <a href="http://xceed.com/Zip_NET_CF_Intro.html" rel="noreferrer">Xceed Zip for CF</a> library. What other options are there?</p>
<p>Have a look at #ziplib (www.icsharpcode.com). It's GPL, but you can use it in closed-source, commercial applications. They don't say anything specifically on their page about using it with the Compact Framework, so you'd have to give it a test yourself (that said, it's pure C# without any external dependencies, so the chances are somewhat good that it will work).</p>
<p>I use the Resco MobileForms toolkit for a variety of functionality: <a href="http://www.resco.net/developer/mobileformstoolkit/overview.aspx" rel="nofollow noreferrer">http://www.resco.net/developer/mobileformstoolkit/overview.aspx</a></p> <p>It includes a good ZIP library.</p>
2,895
<p>In C#, I can do this:</p> <pre><code>class Program { static void Main(string[] args) { List&lt;Animal&gt; animals = new List&lt;Animal&gt;(); animals.Add(new Dog()); animals.Add(new Cat()); foreach (Animal a in animals) { Console.WriteLine(a.MakeNoise()); a.Sleep(); } } } public class Animal { public virtual string MakeNoise() { return String.Empty; } public void Sleep() { Console.Writeline(this.GetType().ToString() + " is sleeping."); } } public class Dog : Animal { public override string MakeNoise() { return "Woof!"; } } public class Cat : Animal { public override string MakeNoise() { return "Meow!"; } } </code></pre> <p>Obviously, the output is (Slightly paraphrased):</p> <ul> <li>Woof</li> <li>Dog is Sleeping</li> <li>Meow</li> <li>Cat is Sleeping</li> </ul> <p>Since C# is often mocked for its verbose type syntax, how do you handle polymorphism/virtual methods in a duck typed language such as Ruby?</p>
<p>edit: added more code for your updated question</p> <p>disclaimer: I haven't used Ruby in a year or so, and don't have it installed on this machine, so the syntax might be entirely wrong. But the concepts are correct.</p> <hr> <p>The exact same way, with classes and overridden methods:</p> <pre><code>class Animal def MakeNoise return "" end def Sleep print self.class.name + " is sleeping.\n" end end class Dog &lt; Animal def MakeNoise return "Woof!" end end class Cat &lt; Animal def MakeNoise return "Meow!" end end animals = [Dog.new, Cat.new] animals.each {|a| print a.MakeNoise + "\n" a.Sleep } </code></pre>
<p>This is how I would write it:</p> <pre><code>class Animal def make_noise; '' end def sleep; puts "#{self.class.name} is sleeping." end end class Dog &lt; Animal; def make_noise; 'Woof!' end end class Cat &lt; Animal; def make_noise; 'Meow!' end end [Dog.new, Cat.new].each do |animal| puts animal.make_noise animal.sleep end </code></pre> <p>It's not <em>really</em> different from the other solutions, but this is the style that I would prefer.</p> <p>That's 12 lines vs. the 41 lines (actually, you can shave off 3 lines by using a collection initializer) from the original C# example. Not bad!</p>
16,650
<p>I am just getting started with Silverlight and have recently added a Silverlight project to an established solution. In this particular scenario my solution included an existing ASP.NET web site (not application) which Visual Studio kindly offered to integrated my Silverlight application into, which I accepted.</p> <p>So everything is fine and all, and the Silverlight XAP is being copied to the web site's ClientBin directory. Now I have decided to start a new ASP.NET MVC web application that will eventually replace the older (non-MVC) web site. But I cannot for the life of me figure out what Visual Studio modified to get the XAP to automatically appear in the web site's ClientBin on build, so that I can reproduce that on my MVC site.</p> <p>So my question is essentially, what are the manually steps for getting Visual Studio to autocopy a Silverlight application's XAP to a newly added ASP.NET MVC web application?</p>
<p>The copying of the XAP to the ClientBin is a MSBuild task. If you're using a standard ASP.NET project template it can be found under the Silverlight Link section.</p> <p>For everything else you might be able to figure out the name of the MSBuild task and add it to your ASP.NET MVC project. The easier solution would probably be to use a custom post-build event on the APS.NET project to copy the file. </p> <p>There is no "magic" happening, oter than copying the XAP file from the BIN directory of your Silverlight project to the ClientBin of your web application. It doesn't even have to live inside the ClientBin directory - you can copy it to any directory, or the root of your site.</p> <p><strong>Update:</strong> The recently released Beta 1 of ASP.NET MVC includes support for Silverlight projects, so you can link it to your ASP.NET MVC application the same way you do for regular ASP.NET applications.</p>
<p>Go to the property pages of your Silverlight application, Choose Build Events Tab, Enter following line in Post-Build events command line:</p> <pre><code>copy $(TargetDir)*.xap $(SolutionDir)&lt;youar web solution folder name such as app.web&gt;\ClientBin </code></pre> <p>Now onwards, on each successful build, the xap file will be copied automatically.</p>
25,398
<p>Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users.</p> <p>Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel)</p> <p>Thanks, Janosch</p>
<p>I would suggest checking out <a href="http://code.google.com/p/django-multilingual/" rel="noreferrer">django-multilingual</a>. It is a third party app that lets you define translation fields on your models.</p> <p>Of course, you still have to type in the actual translations, but they are stored transparently in the database (as opposed to in static PO files), which is what I believe you are asking about.</p>
<p>It depends on who will provide the translations. If you want to provide a web interface to translation, then you need to develop that yourself, and also represent the translations in the database.</p> <p>If the same translators who translated the site will also translate the data, you can provide them with the same model that they use for the site (presumably gettext), and you can then also use gettext for this content.</p>
47,876
<p>I have a DataGridViewComboBoxColumn in a DataGridView in a windows application. The user can change settings elsewhere to potentially invalidate a selection in a DataGridViewComboBoxColumn. I have a requirement to retain/display the invalid item while only leaving valid items selectable in the list.</p> <p>Without correcting the selection an exception is thrown:<br> DataGridViewComboBoxCell value is not valid.</p> <p>Catching and ignoring the setting reverts the selected value to the first valid item in the list.</p> <p>Is there a way to provide a value to a DataGridViewComboBoxColumn so that it does not show up in the list of selectable values?</p>
<p>I found a very strange solution:</p> <p>Set the autosizecolumnmode to none...</p> <p>Here's an explaination</p> <p><a href="http://www.kebabshopblues.co.uk/2007/03/24/more-on-that-datagridviewcombobox-error/" rel="nofollow noreferrer">http://www.kebabshopblues.co.uk/2007/03/24/more-on-that-datagridviewcombobox-error/</a></p>
<p>Presumably your bound datasource to populate the combobox is read only. If so, why not just temporarily insert the invalid value into the underlying datasource. That way it would still be displayed. You could add a temporary column to flag invalid items and not allow the user to leave it selected and then delete it when the user navigated off of the cell. I've never done this with a datagridview but we did something very similar with a different 3rd party grid. Good Luck!</p>
21,779
<p>I need to return a list of record id's from a table that may/may not have multiple entries with that record id on the same date. The same date criteria is key - if a record has three entries on 09/10/2008, then I need all three returned. If the record only has one entry on 09/12/2008, then I don't need it.</p>
<pre><code>SELECT id, datefield, count(*) FROM tablename GROUP BY datefield HAVING count(*) &gt; 1 </code></pre>
<p><code>GROUP BY</code> with <code>HAVING</code> is your friend:</p> <pre><code>select id, count(*) from records group by date having count(*) &gt; 1 </code></pre>
10,235
<p>Example</p> <p>I have <code>Person</code>, <code>SpecialPerson</code>, and <code>User</code>. <code>Person</code> and <code>SpecialPerson</code> are just people - they don't have a user name or password on a site, but they are stored in a database for record keeping. User has all of the same data as <code>Person</code> and potentially <code>SpecialPerson</code>, along with a user name and password as they are registered with the site.</p> <hr> <p>How would you address this problem? Would you have a <code>Person</code> table which stores all data common to a person and use a key to look up their data in <code>SpecialPerson</code> (if they are a special person) and User (if they are a user) and vice-versa?</p>
<p>There are generally three ways of mapping object inheritance to database tables. </p> <p>You can make one big table with all the fields from all the objects with a special field for the type. This is fast but wastes space, although modern databases save space by not storing empty fields. And if you're only looking for all users in the table, with every type of person in it things can get slow. Not all or-mappers support this.</p> <p>You can make different tables for all the different child classes with all of the tables containing the base-class fields. This is ok from a performance perspective. But not from a maintenance perspective. Every time your base-class changes all the tables change.</p> <p>You can also make a table per class like you suggested. This way you need joins to get all the data. So it's less performant. I think it's the cleanest solution.</p> <p>What you want to use depends of course on your situation. None of the solutions is perfect so you have to weigh the pros and cons.</p>
<p>Personally, I would store all of these different user classes in a single table. You can then either have a field which stores a 'Type' value, or you can imply what type of person you're dealing with by what fields are filled in. For example, if UserID is NULL, then this record isn't a User.</p> <p>You could link out to other tables using a one to one-or-none type of join, but then in every query you'll be adding extra joins.</p> <p>The first method is also supported by LINQ-to-SQL if you decide to go down that route (they call it 'Table Per Hierarchy' or 'TPH').</p>
6,756
<p>What's everyone take on tieing code enum's to row ID's in a database table? I'm really looking for a cleaner alternative. What if for example your static rows in a given table are ID's 1,2,3, and then that table gets filled with user transactional data using ID's 4-100, and then you later want to add a new row ID which in your local production database is row ID 4, but when that row goes to a customers database it will have to be 101...well that kinda breaks everything.</p> <p>So how do you handle static locked rows in a table that also gets filled with transactional data?</p> <p>Thanks, MeshMan</p>
<p>Don't do that. ;-)</p> <p>If you have static rows, values that never change, in a table that has user data that is transactional or at least mutable, then I'd say you have at least a normalization issue in the schema.</p> <p>Reference data belongs in it's own table, usually. If the table itself contains only the reference data, then assigning the IDs from the application or using generated IDs from the DB becomes a matter of preference.</p> <p>I've often toyed with the idea of generating either a 'source code' Enum class from DB tables or filling DB tables with Enum class information at build/deployment time, but I've never 'gotten around to it'.</p>
<p>Maybe you could post an example to help us better understand, but if you have some rows that are designated as "system" entries, you could consider adding a column to the table called Order and then, when you create an entry that is designed to be the system entry, you can increment the Order column. </p> <p>For most other things, like lookup tables, you should be able to control the row IDs more explicitly and use them.</p>
28,620
<p>We've been using <a href="http://www.jboss.org/community/docs/DOC-10525" rel="nofollow noreferrer">jbossmq</a> and <a href="http://csil.sourceforge.net" rel="nofollow noreferrer">csil</a>. The implementation has been successful in production for 6 years, but I'm wondering if something better is available.</p> <p>One issue is jbossmq's thread per client model, and scheduled end of life. Another is csil's lack of support for JBossMessaging, which is the latest JMS implementation from JBoss.</p>
<p>IKVM for compiling .NET from Java looks interesting.</p> <p>For .NET messaging check out <a href="http://www.rabbitmq.com/" rel="nofollow noreferrer">RabbitMQ</a>.</p>
<p>I am author of <a href="http://jni4net.sf.net/" rel="nofollow noreferrer">jni4net</a>, open source intraprocess bridge between JVM and CLR. It's build on top of JNI and PInvoke. No C/C++ code needed. I hope it will help you.</p>
32,464
<p>Being new to Cocoa, and probably not knowing all of the potential classes available that already have this functionality neatly wrapped in an OO class, here's an algorithm inquiry. What's the best bet to count how many times a particular key occurs in an array of multiple <code>NSDictionary</code> instances?</p> <p>Essentially my data structure (in this case an <code>NSArray</code>) might contain several <code>NSDictionary</code> instances at any given time, each one having the same keys, potentially different values. Some values repeat. I'd like to be able to know how many times a particular key/value appears. Example:</p> <pre><code>{ foo =&gt; 1, bar =&gt; 2 } { foo =&gt; 1, bar =&gt; 3 } { foo =&gt; 2, bar =&gt; 1 } </code></pre> <p>In this case I'm interested that <code>foo=&gt;1</code> occured 2 times and <code>foo=&gt;2</code> occured 1 time. Is building an instance of <code>NSCountedSet</code> the best way to go about this? Perhaps a C linked-list?</p>
<pre><code>NSDictionary * dict1 = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:1], @"foo", [NSNumber numberWithInt:2], @"bar", nil]; NSDictionary * dict2 = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:1], @"foo", [NSNumber numberWithInt:3], @"bar", nil]; NSDictionary * dict3 = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:2], @"foo", [NSNumber numberWithInt:1], @"bar", nil]; NSArray * arrayOfDictionaries = [[NSArray alloc] initWithObjects: dict1, dict2, dict3, nil]; // count all keys in an array of dictionaries (arrayOfDictionaries): NSMutableDictionary * countKeys = [[NSMutableDictionary alloc] initWithCapacity:0]; NSCountedSet * counts = [[NSCountedSet alloc] initWithCapacity:0]; NSArray * keys; NSString * pairString; NSString * countKey; for (NSDictionary * dictionary in arrayOfDictionaries) { keys = [dictionary allKeys]; for (NSString * key in keys) { pairString = [NSString stringWithFormat:@"%@->%@", key, [dictionary valueForKey:key]]; if ([countKeys valueForKey:pairString] == nil) { [countKeys setValue:[NSString stringWithString:pairString] forKey:pairString]; } countKey = [countKeys valueForKey:pairString]; { [counts addObject:countKey]; } } } NSLog(@"%@", counts); [counts release]; [countKeys release]; [arrayOfDictionaries release]; [dict1 release]; [dict2 release]; [dict3 release];</code></pre>
<pre><code>NSCountedSet *keyCounts = [NSCountedSet set]; for (NSDictionary *dict in myDictionaries) [keyCounts unionSet:[NSSet setWithArray:[dict allKeys]]]; </code></pre>
39,611
<p>I'm jealous of the rails guys. They can do this:</p> <pre><code>&lt;%= javascript_include_tag "all_min" %&gt; </code></pre> <p>... and I'm stuck doing this:</p> <pre><code>&lt;script src="/public/javascript/jquery/jquery.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="/public/javascript/jquery/jquery.tablesorter.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="/public/javascript/jquery/jquery.tablehover.pack.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="/public/javascript/jquery/jquery.validate.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="/public/javascript/jquery/jquery.form.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="/public/javascript/jquery/application.js" type="text/javascript"&gt;&lt;/script&gt; </code></pre> <p>Are there any libraries to compress, gzip and combine multiple js files? How about CSS files?</p>
<p>You can use a <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.aspx" rel="nofollow noreferrer">ScriptManager</a>/<a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanagerproxy.aspx" rel="nofollow noreferrer">ScriptManagerProxy</a> control and define the scripts in the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.compositescript.aspx" rel="nofollow noreferrer">CompositeScript</a> section/property. See <a href="http://msdn.microsoft.com/en-us/library/cc488552.aspx" rel="nofollow noreferrer">MSDN reference</a>.</p> <pre><code>&lt;asp:ScriptManager runat="server"&gt; &lt;CompositeScript&gt; &lt;Scripts&gt; &lt;asp:ScriptReference Path="~/public/javascript/jquery/jquery.js" /&gt; &lt;asp:ScriptReference Path="~/public/javascript/jquery/jquery.tablesorter.js" /&gt; &lt;asp:ScriptReference Path="~/public/javascript/jquery/jquery.tablehover.pack.js" /&gt; &lt;asp:ScriptReference Path="~/public/javascript/jquery/jquery.validate.js" /&gt; &lt;asp:ScriptReference Path="~/public/javascript/jquery/jquery.form.js" /&gt; &lt;asp:ScriptReference Path="~/public/javascript/jquery/application.js" /&gt; &lt;/Scripts&gt; &lt;/CompositeScript&gt; &lt;/asp:ScriptManager&gt; </code></pre> <p>It doesn't necessarily clean up the markup any, but it does zip them together.</p>
<p>That is a helper method in rails.</p> <p>passing it :all will include the default protoype libaries.</p> <p>ASP.net MVC tried to copy rails but you can never get the internal asthetics right.</p> <p>My Advice:</p> <p>Instead of copying everything good from open source just use the real stuff i.e. rails</p>
38,493
<p>I just started with the WCF REST Starter Kit.</p> <p>I created a simple service that return an array of an object.</p> <p>Using the browser, everything works fine but when I use a WCF client, I get an ArgumentException.</p> <p>I'm not using IIS and here is the code:</p> <p><strong>The contract:</strong></p> <pre><code>[ServiceContract] public interface IGiftService { [WebGet(UriTemplate="gifts")] [OperationContract] List&lt;Gift&gt; GetGifts(); } public class GiftService : IGiftService { public List&lt;Gift&gt; GetGifts() { return new List&lt;Gift&gt;() { new Gift() { Name = "1", Price = 1.0 }, new Gift() { Name = "2", Price = 1.0 }, new Gift() { Name = "3", Price = 1.0 } }; } } [DataContract] public class Gift { [DataMember] public string Name { get; set; } [DataMember] public double Price { get; set; } } </code></pre> <p><strong>To start the service:</strong></p> <pre><code>WebServiceHost2 host = new WebServiceHost2( typeof(GiftService), true, new Uri("http://localhost:8099/tserverservice")); host.Open(); Console.WriteLine("Running"); Console.ReadLine(); host.Close(); </code></pre> <p><strong>To start the client:</strong></p> <pre><code>WebChannelFactory&lt;IGiftService&gt; factory = new WebChannelFactory&lt;IGiftService&gt;( new Uri("http://localhost:8099/tserverservice")); IGiftService service = factory.CreateChannel(); List&lt;Gift&gt; list = service.GetGifts(); Console.WriteLine("-&gt; " + list.Count); foreach (var item in list) { Console.WriteLine("-&gt; " + item.Name); } </code></pre> <p>The server and the client are in the same solution and I'm using the same interface in both (to describe the service contract).</p> <p>The exception says: "A property with the name 'UriTemplateMatchResults' already exists." and that is the stack trace:</p> <p><strong>Class firing the exception</strong> -> Microsoft.ServiceModel.Web.WrappedOperationSelector</p> <p><strong>Stack trace:</strong></p> <pre><code> at System.ServiceModel.Channels.MessageProperties.UpdateProperty(String name, Object value, Boolean mustNotExist) at System.ServiceModel.Channels.MessageProperties.Add(String name, Object property) at System.ServiceModel.Dispatcher.WebHttpDispatchOperationSelector.SelectOperation(Message&amp; message, Boolean&amp; uriMatched) at System.ServiceModel.Dispatcher.WebHttpDispatchOperationSelector.SelectOperation(Message&amp; message) at Microsoft.ServiceModel.Web.WrappedOperationSelector.SelectOperation(Message&amp; message) in C:\Program Files\WCF REST Starter Kit\Microsoft.ServiceModel.Web\WrappedOperationSelector.cs:line 42 at Microsoft.VisualStudio.Diagnostics.ServiceModelSink.ServiceMethodResolver.GetOperation() at Microsoft.VisualStudio.Diagnostics.ServiceModelSink.ServiceMethodResolver..ctor(ContractDescription contract, DispatchRuntime runtime, Message request, InstanceContext instanceContext) </code></pre> <p>What am I doing wrong?</p> <p><strong>UPDATE:</strong> I disabled the help page and the service is working now. Is it a bug?</p> <pre><code>host.EnableAutomaticHelpPage = false; </code></pre> <p>Thank you!</p> <p>André Carlucci</p>
<p>In his book "<a href="https://rads.stackoverflow.com/amzn/click/com/0120887975" rel="noreferrer" rel="nofollow noreferrer">SQL Programming Style</a>," Joe Celko suggests a number of conventions, for example that a collection (e.g. a table) should be named in the plural, while a scalar data element (e.g. a column) should be named in the singular.</p> <p>He cites <a href="http://en.wikipedia.org/wiki/ISO/IEC_11179" rel="noreferrer">ISO-11179-4</a> as a standard for metadata naming, which supports this guideline.</p>
<p><a href="http://www.ssw.com.au/ssw/standards/Default.aspx" rel="nofollow noreferrer">Here you can find a lot of Rules to better SQL /SQL Server.</a><br> Yes, it's the company that I am working for, but they are good! And these rules come from experience with client projects.</p> <p>Have a look and take what you like!</p>
49,670
<p>If you have a situation where a TCP connection is potentially too slow and a UDP 'connection' is potentially too unreliable what do you use? There are various standard reliable UDP protocols out there, what experiences do you have with them?</p> <p>Please discuss one protocol per reply and if someone else has already mentioned the one you use then consider voting them up and using a comment to elaborate if required.</p> <p><strong>I'm interested in the various options here, of which TCP is at one end of the scale and UDP is at the other. Various reliable UDP options are available and each brings some elements of TCP to UDP.</strong></p> <p>I know that often TCP is the correct choice but having a list of the alternatives is often useful in helping one come to that conclusion. Things like Enet, RUDP, etc that are built on UDP have various pros and cons, have you used them, what are your experiences?</p> <p>For the avoidance of doubt there is no more information, this is a hypothetical question and one that I hoped would elicit a list of responses that detailed the various options and alternatives available to someone who needs to make a decision.</p>
<p>It's difficult to answer this question without some additional information on the domain of the problem. For example, what volume of data are you using? How often? What is the nature of the data? (eg. is it unique, one off data? Or is it a stream of sample data? etc.) What platform are you developing for? (eg. desktop/server/embedded) To determine what you mean by "too slow", what network medium are you using? </p> <p>But in (very!) general terms I think you're going to have to try really hard to beat tcp for speed, unless you can make some hard assumptions about the data that you're trying to send.</p> <p>For example, if the data that you're trying to send is such that you can tolerate the loss of a single packet (eg. regularly sampled data where the sampling rate is many times higher than the bandwidth of the signal) then you can probably sacrifice some reliability of transmission by ensuring that you can detect data corruption (eg. through the use of a good crc)</p> <p>But if you cannot tolerate the loss of a single packet, then you're going to have to start introducing the types of techniques for reliability that tcp already has. And, without putting in a reasonable amount of work, you may find that you're starting to build those elements into a user-space solution with all of the inherent speed issues to go with it.</p>
<p>The best way to achieve reliability using UDP is to build the reliability in the application program itself( for example, by adding acknowledgment and retransmission mechanisms)</p>
13,308
<p>I'm working on a site (<a href="http://easy2speak.com" rel="nofollow noreferrer">http://easy2speak.com</a>) with about 10 flash SWFs on each page. Each of the SWFs are playing back a sound when clicked. Loading the sound, and playing it without any latency works fine, but in Flash player version 9 on all major browsers except IE, the sound suddenly drops out. It usually works for the first 10-20 clicks, then the SWFs will be totally silent until the next machine/browser restart. </p> <p>In Flash player v10 (exactly the same code) it works perfectly. It also works perfectly in Flash player v9 in Internet Explorer.</p> <p>Any ideas ?</p> <p>Would love to hear some brain-storming on how to get around this problem as well, as I start to suspect there is no easy fix I can do in code. </p> <p>By the way, the site has 1000+ sounds in MP3, so any solution can't involve embedding the sounds.</p>
<p>I would discourage from /FI (<a href="http://msdn.microsoft.com/en-us/library/8c5ztk84.aspx" rel="noreferrer">MSDN</a> says it's called /FI . Not sure whether i looked at the right page though), simply because people or yourself reading the files don't notice a header is magically included anyway. </p> <p>You can be sure this will cause much debugging time for someone that wants to figure out where specific macros come from, even though there are no <code>#include</code> lines at the top of the file.</p>
<p>Save this function for when something weird comes up - like if you want to include a header in a generated source file. Even then there are likely better ways.</p>
41,495
<p>Every time I start Visual Studio 2008, the first time I try to run the project I get the error CS0006 The metadata file ... could not be found. If I do a rebuild of the complete solution it works.</p> <p>Some information about the solution:</p> <ul> <li><p>I'm building in debug mode and Visual Studio complains about not finding dll:s in the release folder.</p></li> <li><p>The projects Visual Studio complains about are used by many other projects in the solution.</p></li> <li><p>I have changed the default output path of all projects to a ......\build\debug\ProjectName and ......\build\release\ProjectName respectively. (Just to get all build files in one directory)</p></li> <li><p>I have the same problem with a another solution. </p></li> <li><p>The solution was created from scratch.</p></li> <li><p>There are 9 projects in the solution. One WPF and 8 class libraries using dotnet 3.5.</p></li> </ul> <p>Any ideas on what is causing this problem?</p>
<p>i had the similar issue where "metadata could not be found". on the solution property, make sure that the "build" check box is marked in <em>Build/Configuration Manager</em> for each project.</p>
<p>Same thing happened. I have several solutions referencing the same library projects (.net 3.5). I noticed when one was built in debug/normal config, and another using some other compiler directive (sqlite/local mode), this would happen. Simply get both projects building with the same directives and you should be fine.</p>
42,652
<p>Recently, <a href="https://stackoverflow.com/users/5200/lee-baldwin">Lee Baldwin</a> showed how to write a <a href="https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function#141689">generic, variable argument memoize function</a>. I thought it would be better to return a simpler function where only one parameter is required. Here is my total bogus attempt:</p> <pre><code>local function memoize(f) local cache = {} if select('#', ...) == 1 then return function (x) if cache[x] then return cache[x] else local y = f(x) cache[x] = y return y end end else return function (...) local al = varg_tostring(...) if cache[al] then return cache[al] else local y = f(...) cache[al] = y return y end end end end </code></pre> <p>Obviously, <code>select('#', ...)</code> fails in this context and wouldn't really do what I want anyway. Is there any way to tell inside <strong>memoize</strong> how many arguments <strong>f</strong> expects? </p> <hr> <p>"No" is a fine answer if you know for sure. It's not a big deal to use two separate <strong>memoize</strong> functions.</p>
<p>I guess you could go into the debug info and determine this from the source-code, but basically it's a "no", sorry.</p>
<p>I'm pretty sure you can't do that in Lua.</p>
17,213
<p>I have a report in SSRS 2005 that's based on a query that's similar to this one: </p> <pre><code>SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND col2 LIKE '%XYZ%' </code></pre> <p>I need to be able to dynamically include the AND part of the WHERE clause in the query based on whether the user has checked a checkbox. Basically, this is a dynamic SQL statement and that's the problem. I tried several approaches to no avail. Is this possible? Does SSRS 2005 supports dynamic SQL? Thanks!</p>
<p>Charles almost had the correct answer.</p> <p>It should be:</p> <pre><code>SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND (@checked = 0 OR col2 LIKE '%XYZ%') </code></pre> <p>This is a classic "pattern" in SQL for conditional predicates. If <code>@checked = 0</code>, then it will return all rows matching the remainder of the predicate (<code>col1 = 'ABC'</code>). SQL Server won't even process the second half of the <code>OR</code>.</p> <p>If <code>@checked = 1</code> then it will evaluate the second part of the <code>OR</code> and return rows matching <code>col1 = 'ABC' AND col2 LIKE '%XYZ%'</code></p> <p>If you have multiple conditional predicates they can be chained together using this method (while the IF and CASE methods would quickly become unmanageable).</p> <p>For example:</p> <pre><code>SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND (@checked1 = 0 OR col2 LIKE '%XYZ%') AND (@checked2 = 0 OR col3 LIKE '%MNO%') </code></pre> <p>Don't use dynamic SQL, don't use IF or CASE.</p>
<p>You can also take another approach and use the Exec function:</p> <pre><code>DECLARE @CommonSelectText varchar(2000) DECLARE @CompleteSelectText varchar(2000) SELECT @CommonSelectText = 'SELECT * FROM MyTable (nolock) Where Col = ''ABC'' ' IF @checked = 1 SELECT @CompleteSelectText = @CommonSelectText + ' AND ColW LIKE ''%XYZ%'' ' ELSE SELECT @CompleteSelectText = @CommonSelectText EXEC (@CompleteSelectText) GO </code></pre> <p>Note the use of two apostrophes <code>'</code> to mark the quoted text.</p>
16,666
<p>I have transferred a Classic asp site running on windows server 2003 to windows server 2008 but suddenly the below code has stopped working.</p> <pre><code>Const connStr_FC08 = "Provider=SQLNCLI10;Server=DS-47500;Database=TestDB;Uid=TestLogin;Pwd=test;Network=dbmssocn;" Function connDB(OpenDB) DIM conn SET conn = Server.CreateObject("ADODB.Connection") conn.open = connStr_FC08 If OpenDB = "Y" Then conn.open connDB = conn End Function dim cn, cmd cn = connDB("Y") response.Write(cn.state) </code></pre> <p>This returns the below error</p> <pre><code>Microsoft VBScript runtime error '800a01a8' Object required: 'Provider=SQLNCLI10.1' </code></pre> <p>This happens on the below line</p> <pre><code>response.write(cn.state) </code></pre> <p>Thanks Chris</p>
<p>I see a few possible syntax issues with the code you posted:</p> <pre><code> ... conn.open = connStr_FC08 ... connDB = conn ... cn = connDB("Y") </code></pre> <p>Should it be updated to the following?</p> <pre><code> ... conn.ConnectionString = connStr_FC08 ... Set connDB = conn ... Set cn = connDB("Y") </code></pre>
<p>You have that SQL Provider installed right?</p> <p>You can put that function into a simple VBScript script to test without altering your pages any. </p>
38,894
<p>This is a bit of a weird one, and I could well be coding this completely wrong - hence why I've hit the same error twice in two days, in completely different parts of a script. The code I'm using is below:</p> <pre><code> public function findAll( $constraints = array() ) { // Select all records $SQL = 'SELECT * FROM ' . $this->tableName; // See if there's any constraints if( count( $constraints ) > 0 ) { $SQL .= ' WHERE '; foreach( $constraints as $field => $value ) { $SQL .= $field . ' = :' . $field . ' AND '; } } // Remove the final AND and prepare the statement $SQL = substr( $SQL, 0, -5 ); $PDOStatement = $this->PDO->prepare( $SQL ); // Loop through constraints and bind parameters foreach( $constraints as $field => $value ) { print 'Binding ' . $field . ' to ' . $value . ' <br />'; $PDOStatement->bindParam( $field, $value ); } $PDOStatement->execute(); var_dump($PDOStatement); while ( $results = $PDOStatement->fetch( PDO::FETCH_ASSOC ) ) { var_dump($results); } } </code></pre> <p>I'm pretty new to using PDO, but basically I'm attempting to pass an array of constraints e.g. <pre><code>array( 'active' => 1, 'name' => 'James' )</code></pre> and return all rows from the table <pre><code>WHERE active = 1 AND name = 'James'</code></pre></p> <p>If I use this array, the SQL executed from the first <pre><code>var_dump( )</code></pre> is <pre><code>SELECT * FROM {table} WHERE active = :active AND name = 'James'</code></pre> - exactly as I expect. The bound parameters prints 'Binding active to 1' and 'Binding name to James' - exactly as expected. The rows exist in the database, and yet the second <pre><code>var_dump()</code></pre> call for $results outputs nothing - i.e. no rows are returned.</p> <p>If I pass an array of a single constraint, e.g. <pre><code>array( 'active' => 1 )</code></pre>, this works perfectly fine. It appears to be whenever multiple constraints are passed that it stops working.</p>
<p>That's because <a href="http://docs.php.net/manual/en/pdostatement.bindparam.php" rel="noreferrer"><code>bindParam</code></a> works by binding to a variable, and you are re-using the variable (<code>$value</code>) for multiple values. Try with <a href="http://docs.php.net/manual/en/pdostatement.bindvalue.php" rel="noreferrer"><code>bindValue</code></a> instead.</p> <p>Or even better yet; Pass the values as an array to <a href="http://docs.php.net/manual/en/pdostatement.execute.php" rel="noreferrer"><code>execute</code></a> instead. This makes the statement stateless, which is generally a good thing in programming.</p>
<p>As mentioned, using <a href="http://docs.php.net/manual/en/pdostatement.bindvalue.php" rel="nofollow"><code>bindValue</code></a> instead of <a href="http://docs.php.net/manual/en/pdostatement.bindparam.php" rel="nofollow"><code>bindParam</code></a> will certainly accomplish this. However, after spending a considerable amount of time troubleshooting this issue recently, I discovered an alternate solution. Here is how to accomplish PDO variable binding in a foreach loop using bindParam:</p> <p>Replace the following line from the original post:</p> <pre><code>$PDOStatement-&gt;bindParam( $field, $value ); </code></pre> <p>...with this:</p> <pre><code>$PDOStatement-&gt;bindParam( $field, $constraints[$field] ); </code></pre> <p>Instead of binding <code>$value</code>, use <code>$array_name[$array_key]</code>. This works is because you are now binding to a unique variable instead of one that gets reused on each pass of the loop.</p> <p>The variable <code>$field</code> used as the placeholder apparently does not need to be a unique variable, however. I have not thoroughly researched this yet, but a variable used as a placeholder appears to be parsed immediately (instead of being assigned as a variable reference) even when bindParam is used.</p> <p>Also, as you would no longer need to access <code>$value</code> directly, you could also replace this:</p> <pre><code>foreach( $constraints as $field =&gt; $value ) { </code></pre> <p>... with this:</p> <pre><code>foreach (array_keys($constraints) as $field) { </code></pre> <p>This is optional, as it will work fine without this change. It looks cleaner in my opinion though, since it might get confusing later as to why <code>$value</code> is assigned but never used.</p>
17,684
<p>I'm looking for a CMS system to manage a simple and small website. The website will be made with pure HTML and some JavaScript (perhaps prototype library). The reason while I'm looking for a CMS system is, because the customer will have the ability to change the content later by him self, and of course he didn't have any experiences with HTML and JavaScript or programming any more. </p> <p>The CMS should be very easy to use, especially the management.</p>
<p>Personally I would recommend <a href="http://wordpress.org/" rel="nofollow noreferrer">WordPress</a>. Although it's 'marketed' as a blogging platform, it has very nice support for just "pages".</p> <ul> <li>It's free;</li> <li>It's commonly available on cPanel installations, or it's easy to set up on your own server;</li> <li>It has very slick editing facilities;</li> <li>There's a mass of themes and documentation available.</li> </ul>
<p>A good .Net one is Umbraco...</p>
43,755
<p>We're building an C# .NET app which will be running on computers sitting inside trucks. We need to talk to Digital IO ports on the truck computers which do not exist on our developer machines, so I need to write a dummy library which will be included in our dev builds, but will be replaced with our actual Digital IO library when we do releases. And I want this library substitution to be automated by the build process.</p> <p>Coming from a Java background, I can do this easily in maven using build profiles. Is there a similar way I can do it using MSbuild?? If not, whats the best way to handle this in C# microsoft land.</p>
<p>I recently developed something similar where I assumed an interface for communicating with some embedded computers that operated servos. To write the software that controlled these computers I <a href="http://code.google.com/p/moq/" rel="nofollow noreferrer">used Moq to mock</a> the interfaces I wrote, and then later <a href="http://structuremap.sourceforge.net/Default.htm" rel="nofollow noreferrer">plugged in real classes via StructureMap</a> that implemented those interfaces.</p> <p>I also used Moq to write the unit tests for the software controlling the machine using the same interfaces.</p>
<p>I would go for the IoC+Mock approach, but if u would like to do it with msbuild, take a look <a href="http://realfiction.net/?q=node/164" rel="nofollow noreferrer">here</a> for a great resource on conditions in msbuild</p>
33,577
<p>I am a fan of <a href="https://stackoverflow.com/questions/112277/best-intro-to-c-static-metaprogramming">static metaprogramming in C++</a>. I know Java now has generics. Does this mean that static metaprogramming (i.e., compile-time program execution) is possible in Java? If so, can anyone recommend any good resources where one can learn more about it?</p>
<p>No, this is not possible. Generics are not as powerful as templates. For instance, a template argument can be a user-defined type, a primitive type, or a value; but a generic template argument can only be <code>Object</code> or a subtype thereof.</p> <p>Edit: This is an old answer; since 2011 we have Java 7, which has <a href="https://stackoverflow.com/a/8387752/409102">Annotations that can be used for such trickery</a>.</p>
<p>No, generics in Java is purely a way to avoid casting of Object.</p>
13,746
<p>How can I extend a builtin class in python? I would like to add a method to the str class.<br /> I've done some searching but all I'm finding is older posts, I'm hoping someone knows of something newer.</p>
<p>Just subclass the type</p> <pre><code>&gt;&gt;&gt; class X(str): ... def my_method(self): ... return int(self) ... &gt;&gt;&gt; s = X("Hi Mom") &gt;&gt;&gt; s.lower() 'hi mom' &gt;&gt;&gt; s.my_method() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in my_method ValueError: invalid literal for int() with base 10: 'Hi Mom' &gt;&gt;&gt; z = X("271828") &gt;&gt;&gt; z.lower() '271828' &gt;&gt;&gt; z.my_method() 271828 </code></pre>
<p>Assuming that you can not change builtin classes. To simulate a &quot;class reopening&quot; like Ruby in Python3 where <code>__dict__</code> is an mappingproxy object and not dict object :</p> <pre><code>def open(cls): def update(extension): for k,v in extension.__dict__.items(): if k != '__dict__': setattr(cls,k,v) return cls return update class A(object): def hello(self): print('Hello!') A().hello() #=&gt; Hello! #reopen class A @open(A) class A(object): def hello(self): print('New hello!') def bye(self): print('Bye bye') A().hello() #=&gt; New hello! A().bye() #=&gt; Bye bye </code></pre> <p>In Python2 I could also write a decorator function 'open' as well:</p> <pre><code>def open(cls): def update(extension): namespace = dict(cls.__dict__) namespace.update(dict(extension.__dict__)) return type(cls.__name__,cls.__bases__,namespace) return update </code></pre>
45,907
<p>I'm working on an intranet with several subdomains. I have control over each subdomain, so security of cross-site requests is not a concern. I have PHP scripts with JSON responses I'd like to call from multiple subdomains without duplication. For GET requests, I can do this with AJAX and JSONP, but that doesn't work with POST requests. Some alternatives I see, none of which seem very good:</p> <ul> <li>POST to a copy on local subdomain with minimal response, then GET full response from central location with JSONP</li> <li>Both POST and GET to a copy on local subdomain with JSON</li> <li>Use mod_rewrite to use local URLs with a central script on back end with JSON</li> <li>Use symlinks to use local URLs with a central script on back end with JSON</li> </ul> <p>Am I missing something simpler? What would you do here?</p>
<p>just look at this <a href="https://developer.mozilla.org/En/HTTP_access_control" rel="nofollow noreferrer">https://developer.mozilla.org/En/HTTP_access_control</a> page. All what you need - add header to all you scripts that accept post request. Example:</p>
<p>I use REST approach in such cases. Search google for more information about REST.</p>
25,432
<p>File uploads through web pages using the standard HTML input always seems clunky to me. If the user tries to upload a large file, it can go on forever and they get no queue that the file is actually being uploaded.</p> <p>I have tried to do things like provide a gif graphic that is an animated graphic bar, but it doesn't give the user any indication of how much is uploaded. I have even tried to do a progress bar with AJAX, but those were always ugly and never seemed to work right.</p> <p>This has been an issue with many of my clients, and often I'm asked if there is a better way. Sometimes I'll just provide them an FTP site so they can upload it there, but that's not a practical solution either.</p> <p>What do you think the best way to handle HTTP file uploads from HTML is? What are some good ideas / examples you have seen around the internet?</p>
<p>There are a number of client side controls that one can use.</p> <p>You can </p> <ul> <li>Build your own ActiveX control. Windows/IE only</li> <li>Use Flash to queue up files and upload them one at a time to the server using the stanard file upload protocol. </li> <li>Use a signed java applet to upload.</li> <li>Write a browser plugin.</li> </ul> <p>Some random links from google:</p> <p><a href="http://www.element-it.com/MultiPowUpload.aspx" rel="nofollow noreferrer">http://www.element-it.com/MultiPowUpload.aspx</a></p> <p><a href="http://www.codeproject.com/KB/aspnet/FlashUpload.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/aspnet/FlashUpload.aspx</a></p> <p><a href="http://www.dmxzone.com/forum/go/?36564" rel="nofollow noreferrer">http://www.dmxzone.com/forum/go/?36564</a></p>
<p>If you running a mod_perl2 apache there is the <a href="http://search.cpan.org/~ceeshek/Apache2-UploadProgress-0.2/lib/Apache2/UploadProgress.pm" rel="nofollow noreferrer">Apache2::UploadProgress</a> module. This adds an id to the http upload request, you then query the server for the progress of that upload. Has built in support for creating an AJAX progress bar in a popup window or within the page doing the upload. If you want to build your own progress display you can get the info back as XML or JSON data. </p>
47,165
<p>This one is weird,</p> <p><a href="http://www.pickledegg.orchardhostings6.co.uk/bug/wp-test.php" rel="nofollow noreferrer">I have a page that consists of a html table in a div called 'rates-viewer'</a>. If you load this page in IE (6 or 7), you will notice that the contents of the table headers is misaligned over to the left.</p> <p>If you choose a country from the dropdown, it triggers an ajax call to a script. This script returns exactly the same html into the 'rates-viwer' div, to replace the original table.</p> <p><em>The weird thing is that when it does so, the table header content is correctly aligned.</em> </p> <p>Why does loading the same html into the same div, cause my table header content to be corrected like this?</p> <p>I assumed that my html differed slightly, I'm sure its the same.</p> <p>Can anyone plase help with this one please, its causing me to frown a lot :) I basically need the original html to be lined up correctly, but I'm intrigued as to why this is happening.</p> <p>The JS is a bit of jquery, and its in the wp-test.php source. My script that is called is rates-viewer-test.php, and the CSS is in main.css...</p>
<p>File -> Source Control -> Advanced -> Change Source Control and then unbind and/or disconnect all projects and the solution.</p> <p>This should remove all bindings from the solution and project files. (After this you can switch the SCC provider in Tools -> Options -> Source Control -> Plug-in Selection).</p> <p>The SCC specification prescribes that all SCC providers should implement this behavior. (I only tested it for VSS, TFS and AnkhSVN)</p>
<p><a href="http://blog.instance-factory.com/?p=565" rel="nofollow">Here you can find another tool</a> (including source code) to remove both SCC footprint from the solution and project files and the .vssscc and .vspscc files. In addition, it removes the output and other configurable directories.</p> <p>Hth</p> <p>Stefan</p>
46,809
<p>I have two tables, <code>movies</code> and <code>categories</code>, and I want to get an ordered list by <strong>categoryID</strong> first and then by <strong>Name</strong>.</p> <p>The movie table has three columns <strong>ID, Name and CategoryID</strong>. The category table has two columns <strong>ID and Name</strong>.</p> <p>I tried something like the following, but it didn't work.</p> <pre><code>var movies = _db.Movies.OrderBy( m =&gt; { m.CategoryID, m.Name }) </code></pre>
<p>This should work for you:</p> <pre><code>var movies = _db.Movies.OrderBy(c =&gt; c.Category).ThenBy(n =&gt; n.Name) </code></pre>
<p>If use generic repository</p> <pre><code>&gt; lstModule = _ModuleRepository.GetAll().OrderBy(x =&gt; new { x.Level, &gt; x.Rank}).ToList(); </code></pre> <p>else</p> <pre><code>&gt; _db.Module.Where(x=&gt; ......).OrderBy(x =&gt; new { x.Level, x.Rank}).ToList(); </code></pre>
38,251
<p>I have successfully connected to an Oracle database (10g) from C# (Visual Studio 2008) by downloading and installing the client administration tools and Visual Studio 2008 on my laptop.</p> <p>The installation footprint for Oracle Client tools was over 200Mb, and quite long winded.</p> <p>Does anyone know what the minimum workable footprint is? I am hoping that it's a single DLL and a register command, but I have the feeling I need to install an oracle home, and set various environment variables.</p> <p>I am using Oracle.DataAccess in my code.</p>
<p>You need an Oracle Client to connect to an Oracle database. The easiest way is to install the <a href="http://www.oracle.com/technology/software/tech/windows/odpnet/index.html" rel="noreferrer">Oracle Data Access Components</a>.</p> <p>To minimize the footprint, I suggest the following :</p> <ul> <li>Use the Microsoft provider for Oracle (System.Data.OracleClient), which ships with the framework.</li> <li>Download the <a href="http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html" rel="noreferrer">Oracle Instant Client Package</a> - Basic Lite : this is a zip file with (almost) the bare minimum. I recommend version 10.2.0.4, which is much smaller than version 11.1.0.6.0.</li> <li>Unzip the following files in a specific folder : <ul> <li>v10 : <ul> <li>oci.dll</li> <li>orannzsbb10.dll</li> <li>oraociicus10.dll</li> </ul></li> <li>v11 : <ul> <li>oci.dll</li> <li>orannzsbb11.dll</li> <li>oraociei11.dll</li> </ul></li> </ul></li> <li>On a x86 platform, add the CRT DLL for Visual Studio 2003 (msvcr71.dll) to this folder, as Oracle guys forgot to <a href="http://support.microsoft.com/kb/326922" rel="noreferrer">read this</a>...</li> <li>Add this folder to the PATH environment variable.</li> <li>Use the <a href="http://download.oracle.com/docs/cd/B19306_01/network.102/b14212/naming.htm#ABC524382SRI12" rel="noreferrer">Easy Connect Naming</a> method in your application to get rid of the infamous TNSNAMES.ORA configuration file. It looks like this : <code>sales-server:1521/sales.us.acme.com</code>.</li> </ul> <p>This amounts to about <strong>19Mb</strong> (v10).</p> <p>If you do not care about sharing this folder between several applications, an alternative would be to ship the above mentioned DLLs along with your application binaries, and skip the PATH setting step.</p> <p>If you absolutely need to use the Oracle provider (Oracle.DataAccess), you will need :</p> <ul> <li>ODP .NET 11.1.0.6.20 (the first version which allegedly works with Instant Client).</li> <li>Instant Client 11.1.0.6.0, obviously.</li> </ul> <p>Note that I haven't tested this latest configuration...</p>
<p>ODAC xcopy will get you away with about 45MB. <a href="http://www.oracle.com/technology/software/tech/windows/odpnet/index.html" rel="nofollow noreferrer">http://www.oracle.com/technology/software/tech/windows/odpnet/index.html</a></p>
9,604
<p>I'm pretty sure the answer to this is no. I know that I can write</p> <blockquote> <p>if lcase(strFoo) = lcase(request.querystring("x")) then...</p> </blockquote> <p>or use inStr, but I just want to check there isn't some undocumented setting buried in the registry or somewhere that makes the content of VBScript strings behave consistently with the rest of the scripting language!</p> <p>Thanks Dan</p>
<p>There is a <a href="http://msdn.microsoft.com/en-us/library/ya4w6fwy(VS.85).aspx" rel="noreferrer"><code>StrComp</code></a> function which allows performing a case-insensitive comparison of two strings by passing <code>vbTextCompare</code> as the third argument. The main documentation doesn't make that obvious, but it is discussed in this <a href="http://www.microsoft.com/technet/scriptcenter/resources/qanda/jun05/hey0622.mspx" rel="noreferrer" title="How Can I Compare Two String Values Regardless of Letter Case?">Hey, Scripting Guy</a> article.</p> <p>For example:</p> <pre><code>If StrComp(strFoo, Request.QueryString("x"), vbTextCompare) = 0 Then ... </code></pre> <p>However, in practice, I use <code>LCase</code> or <code>UCase</code> way more than <code>StrComp</code> for case-insensitive string comparisons because it's more obvious to me.</p>
<p>I doubt the existence of such an option since if there were something like that and you use it, you'll lose the ability to compare strings in a case sensitive manner.</p>
39,326
<p>Should I be writing Doc Comments for all of my java methods? </p>
<p>@Claudiu</p> <blockquote> <p>When I write code that others will use - Yes. Every method that somebody else can use (any public method) should have a javadoc at least stating its obvious purpose.</p> </blockquote> <p>@Daniel Spiewak</p> <blockquote> <p>I thoroughly document every public method in every API class. Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc. I also document every protected method in every API class, though to a lesser extent. This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.</p> <p>Finally, I will occasionally document private and package private methods for my own benefit. Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.</p> </blockquote> <p>@Paul de Vrieze</p> <blockquote> <p>For things, like trivial getters and setters, share the comment between then and describe the purpose of the property, not of the getter/setter</p> </blockquote> <pre><code>/** * Get the current value of the foo property. * The foo property controls the initial guess used by the bla algorithm in * {@link #bla} * @return The initial guess used by {@link #bla} */ int getFoo() { return foo; } </code></pre> <p>And yes, this is more work.</p> <p>@VonC</p> <p>When you break a huge complex method (because of <a href="https://stackoverflow.com/questions/105852/conditional-logging-with-minimal-cyclomatic-complexity">high cyclomatic complexity</a> reason) into:</p> <ul> <li>one public method calling</li> <li>several private methods which represent internal steps of the public one</li> </ul> <p>, it is very useful to javadoc the private methods as well, even though that documentation will not be visible in the javadoc API files.<br /> Still, it allows you to remember more easily the precise nature of the different steps of your complex algorithm.</p> <p>And remember: <strong><a href="https://stackoverflow.com/questions/61604">limit values or boundary conditions</a></strong> should be part of your javadoc as well.</p> <p>Plus, <em><strong>javadoc is way better than simple &quot;//comment&quot;</strong></em>:</p> <ul> <li>It is recognized by IDE and used to display a pop-up when you move your cursor on top of one of your - javadoc-ed - function. For instance, a <em>constant</em> - that is private static final variable -, should have a javadoc, especially when its value is not trivial. Case in point: <em><strong>regexp</strong></em> (its javadoc should includes the regexp in its non-escaped form, what is purpose is and a literal example matched by the regexp)</li> <li>It can be parsed by external tools (like <a href="http://xdoclet.sourceforge.net/xdoclet/index.html" rel="noreferrer">xdoclet</a>)</li> </ul> <p>@Domci</p> <blockquote> <p>For me, if somebody will see it or not doesn't matter - it's not likely I'll know what some obscure piece of code I wrote does after a couple of months. [...]<br /> In short, comment logic, not syntax, and do it only once, on a proper place.</p> </blockquote> <p>@Miguel Ping</p> <blockquote> <p>In order to comment something, you have to understand it first. When you trying to comment a function, you are actually thinking of what the method/function/class does, and this makes you be more specific and clear in your javadoc, which in turn makes you write more clear and concise code, which is good.</p> </blockquote>
<p>at a previous company, we used to use the jalopy code formatter with eclipse. That would add javadoc to all the methods including private.</p> <p>It made life difficult to document setters and getters. But what the heck. You have to do it -- you do it. That made me learn some macro functionality with XEmacs :-) You can automate it even further by writing a java parser and commenter like ANTLR creator did several years ago :-)</p> <p>currently, I document all public methods and anything more than 10 lines.</p>
25,917
<p>For my project I have to serialize and deserialize a random tree using Java and XStream. My teacher made the Tree/RandomTree algorithms, so I don't have to worry about that. What I don't know how to do is this: I am using FileInputStream to read/write the xml file that I serialized and deserialized, but when I deserialize, I do not know the method used to read the file. After I read the file I should be able to convert it from XML and then print it out as a string. Here's what I have so far. (I imported everything correctly, just didn't add it to my code segment).</p> <pre><code>FileInputStream fin; try { // Open an input stream fin = new FileInputStream (&quot;/Users/Pat/programs/randomtree.xml&quot;); //I don't know what to put below this, to read FileInpuStream object fin String dexml = (String)xstream.fromXML(fin); System.out.println(dexml); // Close our input stream fin.close(); System.out.println(dexml); // Close our input stream fin.close(); } // Catches any error conditions catch (IOException e) { System.err.println (&quot;Unable to read from file&quot;); System.exit(-1); } </code></pre> <hr /> <p><strong>Edit:</strong> I figured it out; I don't think I have to print it as a string, I just needed to make a benchmarking framework to time it and such, but thanks again!</p>
<p>Why not just build a proper app in PHP instead of going through the hassle? Recent PHP is <a href="http://us2.php.net/manual/en/language.types.object.php" rel="nofollow noreferrer">fully object-oriented</a> and lets you do some pretty decent stuff. There are even <a href="https://stackoverflow.com/questions/20709/which-php-framework-will-get-me-to-a-usable-ui-the-fastest">frameworks</a> that help you do this kind of stuff.</p>
<p>It's better that you learned good development practices in PHP than use code-generators. PHP might be a scripting language but it is quite potent, has a nice <a href="http://www.php.net/zend-engine-2.php" rel="nofollow noreferrer">OO</a> model, <a href="http://www.cakephp.org/" rel="nofollow noreferrer">plenty</a> of <a href="http://framework.zend.com/" rel="nofollow noreferrer">good</a> <a href="http://solarphp.com/" rel="nofollow noreferrer">frameworks</a> and other open-source packages.</p> <p>It's up to the developer to create well designed and factored code base, regardless of whether it's compiled at run-time or not.</p>
47,189
<p>I am looking for a simple C++ library for tokenizing and parsing RTF (Rich Text Format) files. I am planning to edit them with Qt's QTextEdit.</p> <p>More the Formatting preserved the better -- but actually I am planning to use Bold and Italics only.</p> <p>In perl I would use <a href="http://search.cpan.org/%7Esargie/RTF-Tokenizer-1.10/lib/RTF/Tokenizer.pm" rel="nofollow noreferrer">RTF::Tokenizer</a>.</p> <p>It would be nice if the module had some sort of interface for writing also, but I am able to brute force that with a template and some regular expressions.</p>
<p>I helped writing the RTF import export filter in KOffice. You can have a look at the code at <a href="https://cgit.kde.org/koffice.git/tree/filters/kword/rtf" rel="nofollow noreferrer">https://cgit.kde.org/koffice.git/tree/filters/kword/rtf</a>. The code is modular and it depends only on Qt.</p>
<p>You can ask the <code>#koffice</code> guys on <code>irc.freenode.org</code> over irc. Their program <code>kword</code> is able to open RTF files, and is indeed also written in Qt. I'm sure they would be glad to tell you about how they do it.</p>
37,573
<p>I'm using .NET Regular Expressions to strip HTML code.</p> <p>Using something like:</p> <pre><code>&lt;title&gt;(?&lt;Title&gt;[\w\W]+?)&lt;/title&gt;[\w\W]+?&lt;div class="article"&gt;(?&lt;Text&gt;[\w\W]+?)&lt;/div&gt; </code></pre> <p>This works for 99% of the time, but sometimes, when parsing...</p> <pre><code>Regex.IsMatch(HTML, Pattern) </code></pre> <p>The parser just blocks and it will continue on this line of code for several minutes or indefinitely.</p> <p>What's going on?</p>
<p>Your regex will work just fine when your HTML string actually contains HTML that fits the pattern. But when your HTML does not fit the pattern, e.g. if the last tag is missing, your regex will exhibit what I call "<a href="http://www.regular-expressions.info/catastrophic.html" rel="nofollow noreferrer">catastrophic backtracking</a>". Click that link and scroll down to the "Quickly Matching a Complete HTML File" section. It describes your problem exactly. [\w\W]+? is a complicated way of saying .+? with RegexOptions.SingleLine.</p>
<p>You're asking your regex to do a lot there. After every character, it has to look ahead to see if the next bit of text can be matched with the next part of the pattern.</p> <p>Regex is a pattern matching tool. Whilst you can use it for simple parsing, you'd be better off using a specific parser (such as the HTML Agility pack, as mentioned my Marc).</p>
41,944
<p>I have a solution with other 70 projects into it. My question is : How can I know where the project is used? I do not want to open all those 70 projects to verify the References one by one. How can I see which project use one project in particular?</p> <p><strong>Edit</strong> I do not want to do 1 by 1 search in XML or in the Reference in VS. I would like a quick way to do it.</p>
<p>There's a pretty cool codeplex project that creates dependecy visualizations that I've used before. Although, with 70 projects, you probably won't be able to read it very well unless you only have a few dependencies per project.</p> <p>Anyway, it's still worth checking out-- you could probably even repurpose some of the source code to just output the depenecies to a list.</p> <p>It at <a href="http://www.codeplex.com/dependencyvisualizer" rel="nofollow noreferrer">Dependecy Visualizer Codeplex Project</a></p>
<p>The project files are in XML, so writing something to parse them should be no big deal. If you just want to find which projects reference particular other projects, "grep" would probably work well enough.</p>
19,371
<p>Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code?</p> <p>I have a simple Google AppEngine project's source hosted on Google Code and would love if everytime I committed to Subversion, that AppEngine would reflect the latest commit. I don't mind if things are broken on the live site since the project is for personal use mainly and for learning.</p> <p>Anyone have any thoughts on how to tie into the subversion commit for the Code repository and/or how to kickoff the deployment to AppEngine? Ideally the solution would not require anything manual from me nor any type of server/listener software on my machine.</p>
<p>Google Code Project Hosting now supports <a href="http://code.google.com/p/support/wiki/PostCommitWebHooks" rel="nofollow noreferrer">Post-Commit Web Hooks</a>, which ping a project-owner-specified URL after every commit. This would eliminate the need to regularly poll your Google Code repository.</p>
<p>Very interesting, but not yet possible, AFAIK. I have been looking for that option in Google Code with no success.</p> <p>The only solution I can figure out is to install something in your machine that checks for changes in your SVN repository.</p> <p>I'll be happy to hear about other approaches.</p>
29,822
<p>From what I've seen the tag is ignored when hosting a WCF service in IIS. I understand that when self-hosting this is required but is this harmful or even used when operating under IIS?</p> <p>ex.</p> <pre><code>&lt;system.serviceModel&gt; &lt;service blah blah blah&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://localhost/blah" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;/system.serviceModel&gt; </code></pre> <p>From what I've seen you can take a config file describing a service from one machine and use that on a completely different machine and it works fine. It looks as if IIS completely ignores this section.</p> <p>Thanks, kyle</p>
<p>As you have guessed, the baseAddresses element is completely ignored when hosting in IIS. The service's base address is determined by the web site &amp; virtual directory into which your wcf service is placed.</p> <p>Even when self-hosting, baseAddresses is not required. It is merely a convenience that avoids you having to enter a full address for each endpoint. If it is present, the endpoints can have relative addresses (relative to the base address, that is).</p>
<p>base address required for selfhosting. IIS/WAS hosts ignores the base address.</p>
8,013
<p>I teach a sort of "lite" C++ programming course to novices ("lite" meaning no pointers, no classes, just plain old C, plus references and STL string and vectors). Students have no previous experience in programming, so I believe that using an interactive debugger would help them understand program flow, variables, and recursion.</p> <p>The course is taught in Linux. Teaching them to use gdb is just overkill (they will not use nor understand most features). I just need something simple but easy to use: to see at which line the program is now, what is in the stack (local variables, previous calls, etc.). I look something similar to old Turbo Pascal or Turbo C++ Borland's debugger, or Visual Studio debugger.</p> <p>Thank you,</p>
<p><a href="http://www.gnu.org/software/ddd/" rel="noreferrer">ddd</a> is a graphical front-end to gdb that is pretty nice. One of the down sides is a classic X interface, but I seem to recall it being pretty intuitive.</p>
<p>You may want to check out Eclipse CDT. It provides a C/C++ IDE that runs on multiple platforms (e.g. Windows, Linux, Mac OS X, etc.). Debugging with Eclipse CDT is comparable to using other tools such as Visual Studio.</p> <p>You can check out the <a href="http://download.eclipse.org/tools/cdt/docs/tutorials/debug_tutorial/cdt_w_debug.htm" rel="noreferrer">Eclipse CDT Debug tutorial</a> that also includes a number of screenshots.</p>
10,494
<p>Under what circumstances will the Win32 API function OleGetClipboard() fail and return <code>CLIPBRD_E_CANT_OPEN</code>?</p> <p>More background: I am assisting with a Firefox bug fix. Details here:</p> <p><a href="https://bugzilla.mozilla.org/show_bug.cgi?id=444800#c19" rel="nofollow noreferrer" title="cannot retrieve image data from clipboard in lossless format">bug 444800 - cannot retrieve image data from clipboard in lossless format</a></p> <p>In the automated test that I helped write, we see that OleGetClipboard() sometimes fails and returns <code>CLIPBRD_E_CANT_OPEN</code>. That is unexpected, and the Firefox code to pull image data off the Windows clipboard depends on that call succeeding.</p>
<p>The documentation says that <code>OleGetClipboard</code> can fail with this error code if <code>OpenClipboard</code> fails. In turn, if you read that documentation, it says:</p> <p>"<strong>OpenClipboard</strong> fails if another window has the clipboard open."</p> <p>It's an exclusive resource: only one window can have the clipboard open at a time. Basically, if you can't do it, wait a little while and try again.</p>
<p>Is your test running over Terminal Services? See <a href="https://stackoverflow.com/questions/68666/clipbrdecantopen-error-when-setting-the-clipboard-from-net">CLIPBRD_E_CANT_OPEN error when setting the Clipboard from .NET</a>.</p>
16,894
<p>How to enable and perform a "full text" search on a table in SQL Server 2005? <br /></p> <p>I did not quite understand the solution in: <a href="https://stackoverflow.com/questions/206142/how-do-i-use-full-text-search-accross-multiple-tables-mssql-2005">How do I use full text search across multiple tables, SQL Server 2005</a></p>
<p><a href="https://stackoverflow.com/questions/202440/how-hard-is-it-to-incorporate-full-text-search-with-sql-server#202474">How hard is it to incorporate full text search with SQL Server?</a></p>
<p>You can also have a look at <a href="http://msdn.microsoft.com/en-us/library/ms142583.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms142583.aspx</a></p>
48,763
<p>If you are using php5 and mysql5, is there a substantial advantage to using stored procs over prepared statements? ( i read somewhere you may not get substantial performance gains from mysql5 stored proc)</p>
<p>They are not really the same thing - with stored procedures, your database logic resides inside the database. Prepared statements basically avoid re-parsing queries if they are called multiple times - the performance benefit can vary greatly.</p> <p>The choice to use one or the other is really dependent on your specific situation. I don't really use stored procs anymore as I like having all of my logic in one place. </p>
<p>Not familiar with php, but in general stored procedures are already "compiled" so may produce marginally faster performance over an sql statement.</p> <p>Though my preference usually to stick with SQL from code management/deployment and unit testing perspective. </p>
23,888
<p>I've followed the ADAM Step by Step Guide from Microsoft and setup an ADAM instance on my local machine. I'm attempting to authenticate using the "Mary Baker" account, but every time I get a COM exception on the <code>if (entry.Guid != null)</code> line below. The exception states that there's an unknown user name or bad password.</p> <p>However, I can use the ldp utility to connect to ADAM and successfully perform a simple bind - so I know that the user name both exists, and I have the correct password.</p> <p>Additionally, I have set the msDS-UserAccountDisabled property on the user to false, and added the user to both the Administrators and Readers roles. </p> <p>Any thoughts?</p> <pre><code> path = "LDAP://localhost:50000/O=Microsoft,c=US"; userId = "CN=Mary Baker,OU=ADAM users,"; password = "Mary@101"; DirectoryEntry entry = new DirectoryEntry(path, userId, password, AuthenticationTypes.None); if (entry.Guid != null) LoadWelcomeScreen(); </code></pre> <p>Thanks.</p>
<p>ADAM stores the unique identifier for a user in the <code>displayName</code> attribute of the <code>user</code> class. They need to be unique in the ADAM instance for the user to authenticate. If two users both had their <code>displayName</code> attribute set to 'jsmith' then neither user could authenticate in ADAM.</p> <p>Use the ldp utility to query the <code>displayName</code> for Mary Baker. It could be something like 'mbaker'. Use that value as the userId in the given code.</p>
<p>I haven't used ADAM or System.DirectoryServices, but I do have experience with LDAP and AD; hopefully the following is applicable.</p> <p>I've never seen a user ID given in that format before. (It looks like some sort of relative DN, as indicated by the trailing comma?) Have you tried specifying the user ID as a full DN (as required by standard LDAP) or as a bare username (if ADAM supports that)?</p> <p>When diagnosing network protocol problems like this (seeing if the my program is doing what I think I'm telling it to do and seeing how what it's doing compares to what a functioning program is doing), I've found it helpful to run <a href="http://www.wireshark.org" rel="nofollow noreferrer">Wireshark</a> for both the non-functioning and the functioning operation to see how they differ. If you've never used Wireshark, it hopefully won't be too hard to get started:</p> <ol> <li>Download, install, and start the software.</li> <li>Under Capture, click Options.</li> <li>Set Interface to either localhost / loopback or to your Ethernet interface. (I don't think that loopback works as expected on Windows ; you'll probably want to pick your Ethernet interface and update your LDAP URL in your C# code to use your hostname rather than localhost.)</li> <li>Under Capture Filter, enter "tcp port 50000" (no quotes).</li> <li>Click Start, run your connect operation, then go under the Capture menu and click Stop.</li> </ol> <p>Wireshark can analyze the protocol for you, so you don't have to be <em>too</em> familiar with the protocol details yourself, although the more you know, the easier it is to interpret all of the details. You can fire up a couple of instances of Wireshark to easily compare two different captures (your code and LDP).</p>
39,010
<p>I need to change color of TextBox whenever its required field validator is fired on Clicking the Submit button</p>
<p>What you can do is register a Javascript function that will iterate through the global Page_Validators array after submission and you can set the background appropriately. The nice thing about this is that you can use it on all of your controls on the page. The function looks like this:</p> <pre><code>function fnOnUpdateValidators() { for (var i = 0; i &lt; Page_Validators.length; i++) { var val = Page_Validators[i]; var ctrl = document.getElementById(val.controltovalidate); if (ctrl != null &amp;&amp; ctrl.style != null) { if (!val.isvalid) ctrl.style.background = '#FFAAAA'; else ctrl.style.backgroundColor = ''; } } } </code></pre> <p>The final step is to register the script with the OnSubmit event:</p> <p>VB.NET:</p> <pre><code>Page.ClientScript.RegisterOnSubmitStatement(Me.GetType, "val", "fnOnUpdateValidators();") </code></pre> <p>C#:</p> <pre><code>Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "fnOnUpdateValidators();"); </code></pre> <p>You'll maintain the proper IsValid status in all of your code behind and it can work with all of your controls.</p> <p><em>Note: I found this solution from the <a href="http://codinglifestyle.wordpress.com/2009/09/16/change-background-color-of-invalid-controls-asp-net-validator/" rel="noreferrer">following blog</a>. I just wanted to document it here in the event the source blog goes down.</em></p>
<p>Here's some self-contained HTML/JS that does the trick:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function mkclr(cntl,clr) { document.getElementById(cntl).style.backgroundColor = clr; }; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; &lt;input type="textbox" id="tb1"&gt;&lt;/input&gt; &lt;input type="submit" value="Go" onClick="javascript:mkclr('tb1','red');"&gt; &lt;/input&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
23,923
<p>Please, provide code examples in a language of your choice.</p> <p><strong>Update</strong>: No constraints set on external storage.</p> <p>Example: Integers are received/sent via network. There is a sufficient space on local disk for intermediate results.</p>
<p><a href="http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html" rel="noreferrer">Sorting a million 32-bit integers in 2MB of RAM using Python by Guido van Rossum</a></p>
<p>As people above mention type int of 32bit 4 MB.</p> <p>To fit as much "Number" as possible into as little of space as possible using the types int, short and char in C++. You could be slick(but have odd dirty code) by doing several types of casting to stuff things everywhere.</p> <p>Here it is off the edge of my seat.</p> <p>anything that is less than 2^8(0 - 255) gets stored as a char (1 byte data type)</p> <p>anything that is less than 2^16(256 - 65535) and > 2^8 gets stored as a short ( 2 byte data type)</p> <p>The rest of the values would be put into int. ( 4 byte data type)</p> <p>You would want to specify where the char section starts and ends, where the short section starts and ends, and where the int section starts and ends.</p>
16,242
<p>I have configured Tomcat to use LDAP / AD.</p> <p>How can I get more details about the logged in user; the userid is returned by <code>request.getRemoteUser()</code> but not the full name that I need.</p> <p>How do I get the actual "<code>displayName</code>" (full name) from AD ?</p> <p>I am using ldap/activedirectory/tomcat 5.5</p>
<p>I suppose the configuration of tomcat with LDAP/AD is about logins (e.g. the Realm). Therefor Natalia is correct: You'll have to query your LDAP-Server for more info. The comment field is too short for this comment, so I've opted for another answer, stating the same.</p> <p>The reason for this is, that the Realm interface provides a Principal, that just contains the username and the possibility to query, if the current user is in a given role (it doesn't even provide all the roles that a principal is in). This is sufficient for the purposes of getting access restrictions based on URLs into web.xml. It does not aim at being your central point of contact with everything that is stored in your user database.</p> <p>If you don't use the user-id but just want it substituted by the full user name, you can easily write your own LDAP Realm by looking at the tomcat installation, creating a new Realm implementation and adding a jar with this implementation to TOMCAT_HOME/lib (for Tomcat 6.0). Of course you need to reference this implementation from your TOMCAT_HOME/conf/server.xml instead of the standard tomcat implementation.</p>
<p>You will need to directly query your LDAP directory to get further information on the user.</p>
46,854
<p>I have an array of hashes, and I want the unique values out of it. Calling <code>Array.uniq</code> doesn't give me what I expect.</p> <pre><code>a = [{:a =&gt; 1},{:a =&gt; 2}, {:a =&gt; 1}] a.uniq # =&gt; [{:a =&gt; 1}, {:a =&gt; 2}, {:a =&gt; 1}] </code></pre> <p>Where I expected:</p> <pre><code>[{:a =&gt; 1}, {:a =&gt; 2}] </code></pre> <p>In searching around on the net, I didn't come up with a solution that I was happy with. Folks recommended redefining <code>Hash.eql?</code> and <code>Hash.hash</code>, since that is what <code>Array.uniq</code> is querying.</p> <p>Edit: Where I ran into this in the real world, the hashes were slightly more complex. They were the result of parsed JSON that had multiple fields, some of which the values were hashes as well. I had an array of those results that I wanted to filter out the unique values.</p> <p>I don't like the redefine <code>Hash.eql?</code> and <code>Hash.hash</code> solution, because I would either have to redefine <code>Hash</code> globally, or redefine it for each entry in my array. Changing the definition of <code>Hash</code> for each entry would be cumbersome, especially since there may be nested hashes inside of each entry.</p> <p>Changing <code>Hash</code> globally has some potential, especially if it were done temporarily. I'd want to build another class or helper function that wrapped saving off the old definitions, and restoring them, but I think this adds more complexity than is really needed.</p> <p>Using <code>inject</code> seems like a good alternative to redefining <code>Hash</code>.</p>
<p>I can get what I want by calling <code>inject</code></p> <pre><code>a = [{:a =&gt; 1},{:a =&gt; 2}, {:a =&gt; 1}] a.inject([]) { |result,h| result &lt;&lt; h unless result.include?(h); result } </code></pre> <p>This will return:</p> <pre><code>[{:a=&gt;1}, {:a=&gt;2}] </code></pre>
<p>The answer you give is similar to the one discussed <a href="http://mikeburnscoder.wordpress.com/2008/01/18/uniquify-an-array-of-hashes-in-ruby/" rel="nofollow noreferrer">here</a>. It overrides the <code>hash</code> and <code>eql?</code> methods on the hashes that are to appear in the array which then makes <code>uniq</code> behave correctly.</p>
21,851
<p>Is there a way to take substrings of a string with .bat/.cmd files?</p> <p>For example given the string "hello.txt" is there a way to strip the .txt?</p> <p>EDIT: Also is there a more general way to do this, not under the assumption that it is a file name or file path?</p>
<p>If this is a file passed as a parameter, you can use %~n1, like this:</p> <pre><code>test.bat ---------- echo %~n1 %~n2 c:\&gt; test.bat myfile.txt my.long.file.bat myfile my.long.file </code></pre> <p>If you know the length of the string you can use the substring operator:</p> <pre><code>echo %variable:0,4% =&gt; "test.txt" =&gt; "test" </code></pre> <p>And to get everything EXCEPT the last 4 characters:</p> <pre><code>echo %variable:~0,-4% =&gt; "file...name.txt" =&gt; "file...name" </code></pre> <ul> <li><a href="http://www.batchfiles.co.nr/" rel="nofollow noreferrer">BatchFiles Website (kind advanced)</a></li> <li><a href="http://forums.afterdawn.com/thread_view.cfm/514228" rel="nofollow noreferrer">Decent forum post</a></li> <li><a href="http://groups.google.com/group/alt.msdos.batch.nt/msg/923423bf3143fcdd?pli=1" rel="nofollow noreferrer">Another Good Post</a></li> </ul>
<p>For an arbitrary string, I don't think so.</p> <p>For this very example, <code>%~n1</code> will resolve to a name without extension.</p>
21,804
<p>Are there any automatic, online or off, tools for testing xhtml/css for compliance with screen readers and other visual guidelines of the <a href="http://www.access-board.gov/sec508/guide/1194.22.htm" rel="nofollow noreferrer">Americans with Disabilities Act (ADA)</a>?</p>
<p>Mike Cohn in his <a href="https://rads.stackoverflow.com/amzn/click/com/0131479415" rel="noreferrer" rel="nofollow noreferrer">Agile Estimating and Planning</a> consider FPs to be great but difficult to get right. He (obviously) recommends to use story points-based estimation instead. I tend to agree with this as with each new project I see the benefits of Agile approach more and more.</p> <hr> <p><em>1) Is it a reasonably precise way to do estimates? (I'm not unreasonable here, but just want to know compared to other estimation methods)</em></p> <p>As far as estimation precision goes the functional points are very good. In my experience they are great but expensive in terms of effort involved if you want do it properly. Not that many projects could afford an elaboration phase to get the FP-based estimates right.</p> <p><em>2) And is the effort required worth the benefit you get out of it?</em></p> <p>FPs are great because they are officially recognised by ISO which gives your estimations a great deal of credibility. If you work on a big project for a big client it might be useful to invest in official-looking detailed estimations. But if the level of uncertainty is big to start with (like other vendors integration, legacy system, loose requirements etc.) you will not get anywhere near precision anyway so usually you have to just accept this and re-iterate the estimations later. If it is the case a cheaper way of doing the estimates (user stories and story points) are better. </p> <p><em>3) Which type of Function Points do you use?</em></p> <p>If I understand this part of your question correctly we used to do estimations based on the Feature Points but gradually moved away from these an almost all projects expect for the ones with heavy emphasis on the internal functionality.</p> <p><em>4) Do you use any tools for doing this?</em></p> <p>Excel is great with all the formulas you could use. Using Google Spreadsheets instead of Excel helps if you want to do that collaboratively.</p> <p>There is also a great tool built-in to the <a href="http://www.sparxsystems.com.au/" rel="noreferrer">Sparx</a> Enterprise Architect which allows you to do the estimates based on the Use Cases which could be used for FP estimations as well.</p>
<ol> <li>No because any particular requirement can have an arbitrary amount of effort based on how precise (or imprecise) the author of the requirement is, and the level of experience of the function point assessor.</li> <li>No because administration of imprecise derivations of abstract functionality yield no reliable estimate.</li> <li>None if I can help it.</li> <li>Tools? For function points? How about Excel? Or Word? Or Notepad? Or Edlin?</li> </ol>
14,363
<p>We've talked about <b>personal</b> password management <a href="https://stackoverflow.com/questions/11362/what-is-your-favorite-password-storage-tool">here</a> but how do you guys manage your passwords at a company wide level?</p>
<p>We have managed to plan our company applications so they are mainly web based and open source or in-house developed. This then allowed us to use LDAP to hook into active directory for logging into our intranet. From there we modified the logins into various products we use (MediaWiki, Wordpress, SugarCRM etc.) so that if the user is authenticated in the intranet, they are automatically logged into these other products as well.</p> <p>This has taken some time setting up the process and creating a script to set all the appropriate user details in each system when someone joins the company, however now we have a situation where everyone only has to remember one password, removing the need for managing a growing list of passwords.</p> <p>Obviously this may not be viable in many companies, but now that we have it setup it was worth the effort.</p>
<p>We had a look at a product that had these features:</p> <ul> <li>Can give access privleges to password using roles.</li> <li>Handles delegation.</li> <li>Logs access to passwords.</li> <li>Can Randomize passwords.</li> <li>Can automatically re-randomize a password X days after access to it.</li> </ul> <p>Unfortunately, I can't couldn't it's name when I posted this... It was "Secret Server"</p>
22,406
<p>When doing <a href="http://en.wikipedia.org/wiki/Test_driven_development" rel="nofollow noreferrer">TDD</a>, how to tell "that's enough tests for this class / feature"?</p> <p>I.e. when could you tell that you completed testing all edge cases?</p>
<p>With Test Driven Development, you’ll write a test before you write the code it tests. Once you’re written the code and the test passes, then it’s time to write another test. If you follow TDD correctly, you’ve written enough tests once you’re code does all that is required.</p> <p>As for edge cases, let's take an example such as validating a parameter in a method. Before you add the parameter to you code, you create tests which verify the code will handle each case correctly. Then you can add the parameter and associated logic, and ensure the tests pass. If you think up more edge cases, then more tests can be added.</p> <p>By taking it one step at a time, you won't have to worry about edge cases when you've finished writing your code, because you'll have already written the tests for them all. Of course, there's always human error, and you may miss something... When that situation occurs, it's time to add another test and then fix the code.</p>
<p>You could always use a test coverage tool like EMMA (<a href="http://emma.sourceforge.net/" rel="nofollow noreferrer">http://emma.sourceforge.net/</a>) or its Eclipse plugin EclEmma (<a href="http://www.eclemma.org/" rel="nofollow noreferrer">http://www.eclemma.org/</a>) or the like. Some developers believe that 100% test coverage is a worthy goal; others disagree.</p>
16,441
<p>I would like to do full-text searching of data in my Ruby on Rails application. What options exist?</p>
<p>There are several options available and each have different strengths and weaknesses. If you would like to add full-text searching, it would be prudent to investigate each a little bit and try them out to see how well it works for you in your environment.</p> <p>MySQL has built-in support for full-text searching. It has online support meaning that when new records are added to the database, they are automatically indexed and will be available in the search results. The <a href="http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html" rel="nofollow noreferrer">documentation</a> has more details.</p> <p><a href="http://code.google.com/p/acts-as-tsearch/" rel="nofollow noreferrer"><code>acts_as_tsearch</code></a> offers a wrapper for similar built-in functionality for recent versions of <a href="http://www.postgresql.org/docs/8.3/static/textsearch.html" rel="nofollow noreferrer">PostgreSQL</a></p> <p>For other databases you will have to use other software.</p> <p><a href="http://lucene.apache.org/" rel="nofollow noreferrer">Lucene</a> is a popular search provider written in Java. You can use Lucene through its search server <a href="http://lucene.apache.org/solr/" rel="nofollow noreferrer">Solr</a> with Rails using <a href="http://acts-as-solr.rubyforge.org/" rel="nofollow noreferrer"><code>acts_as_solr</code></a>.</p> <p>If you don't want to use Java, there is a port of Lucene to Ruby called <a href="http://ferret.davebalmain.com/trac/wiki" rel="nofollow noreferrer">Ferret</a>. Support for Rails is added using the <a href="http://projects.jkraemer.net/acts_as_ferret/wiki" rel="nofollow noreferrer"><code>acts_as_ferret</code></a> plugin.</p> <p><a href="http://xapian.org/" rel="nofollow noreferrer">Xapian</a> is another good option and is supported in Rails using the <a href="http://github.com/frabcus/acts_as_xapian/wikis" rel="nofollow noreferrer"><code>acts_as_xapian</code></a> plugin.</p> <p>Finally, my preferred choice is <a href="http://www.sphinxsearch.com/" rel="nofollow noreferrer">Sphinx</a> using the <a href="http://blog.evanweaver.com/files/doc/fauna/ultrasphinx/files/README.html" rel="nofollow noreferrer">Ultrasphinx</a> plugin. It is extremely fast and has many options on how to index and search your databases, but is no longer being actively maintained.</p> <p>Another plugin for Sphinx is <a href="http://ts.freelancing-gods.com/" rel="nofollow noreferrer">Thinking Sphinx</a> which has a lot of positive <a href="http://www.williambharding.com/blog/rails/rails-thinking-sphinx-plugin-full-text-searching-thats-cooler-than-a-polar-bears-toenails/" rel="nofollow noreferrer">feedback</a>. It is a little easier to get started using Thinking Sphinx than Ultrasphinx. I would suggest investigating both plugins to determine which fits better with your project.</p>
<p>I've been compiling a <a href="https://stackoverflow.com/questions/73527/whats-the-best-option-for-searching-in-ruby-on-rails">list of the various Ruby on Rails search options in this other question</a>. I'm not sure how, or if to combine our questions.</p>
6,990
<p>I'm trying to use the Grid from WPFToolkit, but I'm getting the error:</p> <pre><code>DisplayDataMapping.xaml (9,89): errorMC1000: Unknown build error, 'Could not load type 'System.Windows.Controls.Primitives.MultiSelector' from assembly 'PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Line 9 Position 89.' </code></pre> <p>Here is the xaml: <pre> &lt;UserControl x:Class="DisplayDataMapping" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"&gt; &lt;StackPanel Margin="10"&gt; &lt;Border CornerRadius="5" BorderThickness="1" Padding="5" BorderBrush="WhiteSmoke"&gt; &lt;toolkit:DataGrid x:Name="dataGridPostings" Background="Transparent" AlternatingRowBackground="LightSteelBlue" RowBackground="White" GridLinesVisibility="None" HorizontalGridLinesBrush="SlateGray"&gt; &lt;/toolkit:DataGrid&gt; &lt;/Border&gt; &lt;/StackPanel&gt; &lt;/UserControl&gt; </pre></p>
<p>The WPF Toolkit is dependent on .NET Framework 3.5 SP1 (just in case you don't know already).</p>
<p>Try to install VS08 SP1</p>
29,859
<p>All the member variables and member functions in my class ClassA are static. </p> <p>If a user is trying (by mistake) to create an object of this class, he receives a warning: "ClassA, local variable never referenced", because all the functions are static, so this object is never referenced. So, I want to prevent the user from trying to create an object of this class. </p> <p>Would it be enough to create a private default (no variables) constructor? Or do I have to also create private copy constructor and private assignment operator (to prevent using the default constructors)? And if I do have to create them too, maybe it would be better just to create some dummy pure virtual function instead, and this will prevent the user from creating an object?</p> <p>Thank you</p>
<p>Creating a private default constructor should be sufficient. Both of the other default constructs (copy constructor and assignment) rely on having an instance to work correctly. If there is no default constructor then there is no way to create an instance, hence no way to actually get to the copy construction part. </p> <p>It would likely save you a few headaches though to define all 3 as private and not implemented. </p>
<p>The best way to prevent creation of non-heap objects is to make destructor private. Then there is no way compiler can destruct the object when it goes out of scope and it will complain. This will not prevent anyone from doing new however.</p>
46,048
<p>How do you shade alternating rows in a SQL Server Reporting Services report?</p> <hr> <p><strong>Edit:</strong> There are a bunch of good answers listed below--from <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#44378">quick</a> and <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#345935">simple</a> to <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#83832">complex and comprehensive</a>. Alas, I can choose only one...</p>
<p>Go to the table row's BackgroundColor property and choose "Expression..."</p> <p>Use this expression: </p> <pre><code>= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent") </code></pre> <p>This trick can be applied to many areas of the report.</p> <p>And in .NET 3.5+ You could use:</p> <pre><code>= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent") </code></pre> <p>Not looking for rep--I just researched this question myself and thought I'd share.</p>
<p>Just because none of the answers above seemed to work in my matrix, I'm posting this here:</p> <p><a href="http://reportingservicestnt.blogspot.com/2011/09/alternate-colors-in-matrixpivot-table.html" rel="nofollow">http://reportingservicestnt.blogspot.com/2011/09/alternate-colors-in-matrixpivot-table.html</a></p>
6,613
<p>Can I set timeouts for JSP pages in tomcat either on a per page or server level?</p>
<p>For server level, you can try this.<br> you have to change <code>catalina.bat</code> / <code>catalina.sh</code> file<br></p> <pre><code>jvm OPTIONS : -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000 </code></pre>
<p>For server level, you can try this.<br> you have to change <code>catalina.bat</code> / <code>catalina.sh</code> file<br></p> <pre><code>jvm OPTIONS : -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000 </code></pre>
24,798
<p>I am currently trying to print a gear with the possibility to connect it to the shaft of a DC motor. The following picture best describes what the shaft of the motor looks like by showing the hole printed in the gear:</p> <p><a href="https://i.stack.imgur.com/UNHn5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UNHn5.png" alt="enter image description here" /></a></p> <p>So far this works well for a short amount of time, however since the gear is connected to another gear that is from time to time exerting quite some resistance already after a few revolutions the shaft starts to wear out the material that is holding it and it turns without powering the gear, i.e. the printed part is not strong enough to withstand the torque of the motor.</p> <p>I am wondering what the best way forward would be here. I see multiple options:</p> <ul> <li>Design a different connection to the shaft, however I don't know of any</li> <li>Switch to a different material, I am currently using PLA, but I could also go for ABS or PETG if any of them would provide advantages. For PLA vs ABS I found some conflicting information which one is &quot;harder&quot;</li> <li>Play with the parameters of the print. At the moment I am only using 3 wall layers, I wonder if increasing the number of wall layers would improve rigidity.</li> </ul> <p>Are there other ideas? What could you recommend me to improve this connection?</p>
<blockquote> <p>Design a different connection to the shaft, however I don't know of any</p> </blockquote> <p>Use a shaft/flange coupler to be fastened to your shaft and to your printed part.</p> <hr /> <p>Without knowing the length of the shaft, you could connect a flange/coupler to design this into your gear. This is a good solution if you have to transmit larger torques. See e.g. <a href="https://www.thingiverse.com/thing:3296969" rel="noreferrer">this pulley</a> that incorporates that concept.</p> <p>Shaft flange couplers can be connected to your printed part and to the flat part of the shaft.</p> <p>Metal flange couplers are available in many sizes:</p> <p><a href="https://i.stack.imgur.com/TPne9.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/TPne9.jpg" alt="enter image description here" /></a></p> <p>A recess in the printed part houses the flange:</p> <p><a href="https://i.stack.imgur.com/pka5O.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/pka5O.jpg" alt="enter image description here" /></a></p> <p>When assembled you can mount the pulley/gear onto the shaft, provided you have enough length on the shaft.</p> <p><a href="https://i.stack.imgur.com/PNt6V.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/PNt6V.jpg" alt="enter image description here" /></a></p>
<p>A good option would be to use a (set-)screw to press against the flat of the motor shaft, similar to how pulleys are mounted on stepper motors.</p>
1,733
<p>I accidentally moved a very important and large folder from the root project into a sub-folder. Now when I try to move the folder back, it gives me an error message "Cannot create a file when that file already exists." How do I move things back?</p> <p>Additional Information: I am also under SVN and now it wants to start a new log tree. I just go to win explorer with Tortoise SVN and click commit. If I just copy and paste the file back to the original folder, SVN wants to delete it on commit. Wow, I can't believe this little thing is creating a huge mess. </p> <p>Additional: Well, I deleted the original folder and copy and pasted the new one in and now the commit system isn't working because it's telling me that the folder isn't there (I deleted it so it isn't there). </p>
<p>Are you using any source control plugins like AnkhSVN.</p> <p>By the sound of it, you've moved the folder which has created it at the new location, and updated the solution file as such, but for some reason, left a copy of the original folder at the original location on the filesystem.</p> <p>If thats the case you probably need to manually remove it (take a backup first) outside of VS in windows explorer, the you can move it back.</p>
<p>But does the folder, or a file with the same name, exist on the root folder? </p> <p>If so, I would try to delete it first. Make sure you have the button "Show All Files", on 'Solution Explorer' pressed, in order to visualize all of your tree on VS2008.</p>
32,134
<p>Has anyone got any suggestions for unit testing a Managed Application Add-In for Office? I'm using NUnit but I had the same issues with MSTest.</p> <p>The problem is that there is a .NET assembly loaded inside the Office application (in my case, Word) and I need a reference to that instance of the .NET assembly. I can't just instantiate the object because it wouldn't then have an instance of Word to do things to.</p> <p>Now, I can use the Application.COMAddIns("Name of addin").Object interface to get a reference, but that gets me a COM object that is returned through the RequestComAddInAutomationService. My solution so far is that for that object to have proxy methods for every method in the real .NET object that I want to test (all set under conditional-compilation so they disappear in the released version).</p> <p>The COM object (a VB.NET class) actually has a reference to the instance of the real add-in, but I tried just returning that to NUnit and I got a nice p/Invoke error:</p> <p>System.Runtime.Remoting.RemotingException : This remoting proxy has no channel sink which means either the server has no registered server channels that are listening, or this application has no suitable client channel to talk to the server. at System.Runtime.Remoting.Proxies.RemotingProxy.InternalInvoke(IMethodCallMessage reqMcmMsg, Boolean useDispatchMessage, Int32 callType) at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(IMessage reqMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData, Int32 type) </p> <p>I tried making the main add-in COM visible and the error changes:</p> <p>System.InvalidOperationException : Operation is not valid due to the current state of the object. at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData&amp; msgData) </p> <p>While I have a work-around, it's messy and puts lots of test code in the real project instead of the test project - which isn't really the way NUnit is meant to work.</p>
<p>This is how I resolved it.</p> <ol> <li><p>Just about everything in my add-in runs from the Click method of a button in the UI. I have changed all those Click methods to consist only of a simple, parameterless call.</p></li> <li><p>I then created a new file (Partial Class) called EntryPoint that had lots of very short Friend Subs, each of which was usually one or two calls to parameterised worker functions, so that all the Click methods just called into this file. So, for example, there's a function that opens a standard document and calls a "save as" into our DMS. The function takes a parameter of which document to open, and there are a couple of dozen standard documents that we use.</p></li> </ol> <p>So I have </p> <pre><code>Private Sub btnMemo_Click(ByVal Ctrl As Microsoft.Office.Core.CommandBarButton, ByRef CancelDefault As Boolean) Handles btnMemo.Click DocMemo() End Sub </code></pre> <p>in the ThisAddin and then</p> <pre><code>Friend Sub DocMemo() OpenDocByNumber("Prec", 8862, 1) End Sub </code></pre> <p>in my new EntryPoints file.</p> <ol start="3"> <li><p>I add a new AddInUtilities file which has</p> <p>Public Interface IAddInUtilities</p></li> </ol> <p><code>#If DEBUG Then</code></p> <pre><code>Sub DocMemo() </code></pre> <p><code>#End If</code></p> <pre><code>End Interface Public Class AddInUtilities Implements IAddInUtilities Private Addin as ThisAddIn </code></pre> <p><code>#If DEBUG Then</code></p> <pre><code>Public Sub DocMemo() Implements IAddInUtilities.DocMemo Addin.DocMemo() End Sub </code></pre> <p><code>#End If</code></p> <pre><code> Friend Sub New(ByRef theAddin as ThisAddIn) Addin=theAddin End Sub End Class </code></pre> <ol start="4"> <li><p>I go to the ThisAddIn file and add in</p> <p>Private utilities As AddInUtilities</p> <p>Protected Overrides Function RequestComAddInAutomationService() As Object If utilities Is Nothing Then utilities = New AddInUtilities(Me) End If Return utilities End Function</p></li> </ol> <p>And now it's possible to test the DocMemo() function in EntryPoints using NUnit, something like this:</p> <pre><code>&lt;TestFixture()&gt; Public Class Numbering Private appWord As Word.Application Private objMacros As Object &lt;TestFixtureSetUp()&gt; Public Sub LaunchWord() appWord = New Word.Application appWord.Visible = True Dim AddIn As COMAddIn = Nothing Dim AddInUtilities As IAddInUtilities For Each tempAddin As COMAddIn In appWord.COMAddIns If tempAddin.Description = "CobbettsMacrosVsto" Then AddIn = tempAddin End If Next AddInUtilities = AddIn.Object objMacros = AddInUtilities.TestObject End Sub &lt;Test()&gt; Public Sub DocMemo() objMacros.DocMemo() End Sub &lt;TestFixtureTearDown()&gt; Public Sub TearDown() appWord.Quit(False) End Sub End Class </code></pre> <p>The only thing you can't then unit test are the actual Click events, because you're calling into EntryPoints in a different way, ie through the RequestComAddInAutomationService interface rather than through the event handlers.</p> <p>But it works!</p>
<p>Consider the various mocking frameworks <a href="http://www.nmock.org/" rel="nofollow noreferrer">NMock</a>, <a href="http://ayende.com/projects/rhino-mocks.aspx" rel="nofollow noreferrer">RhinoMocks</a>, etc. to fake the behavior of Office in your tests. </p>
15,392
<p>How do I link an external .jar into my Xcode java project? That is, have it in the classpath during compilation and execution. I'm using Xcode 3.0 and this seems to have changed since 2.4.</p>
<p>In Xcode 3.1.2 <br> Checking in file <b>build.xml</b> we see: <br></p> <p><code>&lt;!-- lib directory should contain any pre-built jar files needed to build the project AppleJavaExtensions.jar is included to allow the built jars to run cross-platform if you depend on Apple eAWT or eIO classes. See http://developer.apple.com/samplecode/AppleJavaExtensions/index.html for more information --&gt; &lt;fileset id="lib.jars" dir="${lib}"&gt; &lt;include name="**/*.jar"/&gt; &lt;/fileset&gt;</code></p> <p>okay so, copy the external jar by hand into projectName/lib and compile. (Maybe clean first)</p> <p><b>Edit:</b> I had to copy the jar by hand, Xcode would not put it in the right place </p>
<p>I don't have a Mac to hand, but what if you drop the jar file into your ~/Library/Java/extensions (IIRC) folder?</p> <p>Edit: I presume that you are using Mac OS X specific Java libraries, hence your use of Xcode? Otherwise I would recommend Eclipse. Actually I'd be willing to bet that Eclipse can use the Mac OS X specific Java APIs as well...</p>
19,524
<p>What is the best way to get a log of commits on a branch since the time it was branched from the current branch? My solution so far is:</p> <pre><code>git log $(git merge-base HEAD branch)..branch </code></pre> <p>The documentation for <a href="http://git-scm.com/docs/git-diff" rel="noreferrer">git-diff</a> indicates that <code>git diff A...B</code> is equivalent to <code>git diff $(git-merge-base A B) B</code>. On the other hand, the documentation for <a href="http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html" rel="noreferrer">git-rev-parse</a> indicates that <code>r1...r2</code> is defined as <code>r1 r2 --not $(git merge-base --all r1 r2)</code>.</p> <p>Why are these different? Note that <code>git diff HEAD...branch</code> gives me the diffs I want, but the corresponding git log command gives me more than what I want.</p> <p>In pictures, suppose this:</p> <pre> x---y---z---branch / ---a---b---c---d---e---HEAD </pre> <p>I would like to get a log containing commits x, y, z.</p> <ul> <li><code>git diff HEAD...branch</code> gives these commits</li> <li>however, <code>git log HEAD...branch</code> gives x, y, z, c, d, e.</li> </ul>
<p>In the context of a revision list, <code>A...B</code> is how <code>git-rev-parse</code> defines it. git-log takes a revision list. <code>git-diff</code> does not take a list of revisions - it takes one or two revisions, and has defined the <code>A...B</code> syntax to mean how it's defined in the <code>git-diff</code> manpage. If <code>git-diff</code> did not explicitly define <code>A...B</code>, then that syntax would be invalid. Note that the <code>git-rev-parse</code> manpage describes <code>A...B</code> in the "Specifying Ranges" section, and everything in that section is only valid in situations where a revision range is valid (i.e. when a revision list is desired).</p> <p>To get a log containing just x, y, and z, try <code>git log HEAD..branch</code> (two dots, not three). This is identical to <code>git log branch --not HEAD</code>, and means all commits on branch that aren't on HEAD.</p>
<p>With Git 2.30 (Q1 2021), &quot;git diff A...B(man)&quot; learned &quot;git diff --merge-base A B(man), which is a longer short-hand to say the same thing.</p> <p>Thus you can do this using <code>git diff --merge-base &lt;branch&gt; HEAD</code>. This should be equivalent to <code>git diff &lt;branch&gt;...HEAD</code> but without the confusion of having to use range-notation in a diff.</p>
7,708
<p>In the unmanaged development world, you could observe the DWORD return value of a method by typing '@eax' into the watch window of the debugger.</p> <p>Does anyone know of an equivalent shortcut in managed code?</p> <p>Related point: I have learned that VS2008 SP1 supports <b>$exception</b> as a magic word in the watch window. Are there any other shortcuts that you know of?</p>
<p>The watch window tricks like @eax are called [Psuedovariables]. They are actually <a href="http://msdn.microsoft.com/en-us/library/ms164891(VS.80).aspx" rel="nofollow noreferrer">documented.</a> I wrote a <a href="http://blogs.msdn.com/stevejs/archive/2005/10/18/482300.aspx#comments" rel="nofollow noreferrer">blog post</a> about this and some other VS debugging items a few years ago. Format specifiers are typically highly useful.</p> <p>For your specific question there is no psuedo variable for eax in managed code. There is however a register window which will actually have EAX and the other registers in it. It is questionable that this will be useful in many situations as I don't believe there is any way to cast the address to a managed type. You can however look at the layout in the memory window </p>
<p>@EAX in managed code is a little tricky to implement since CIL has higher-order primitives for function returns (which happen semantically on the virtual execution stack).</p> <p>That said, if your function is returning a value type and that type's size is less than or equal to 32-bits, then the @EAX will most likely still give you that value. (You may need to switch on mixed-mode debugging in order to see registers, I don't remember off the top of my head.) This of course falls apart for reference types, large value types, and inlined functions.</p> <p>In short, I wish this was built into the debugger too!</p>
49,096
<p>I want to read an specific xml node and its value for example</p> <pre><code>&lt;customers&gt; &lt;name&gt;John&lt;/name&gt; &lt;lastname&gt;fetcher&lt;/lastname&gt; &lt;/customer&gt; </code></pre> <p>and my code behind should be some thing like this (I don't know how it should be though):</p> <pre><code>Response.Write(xml.Node[&quot;name&quot;].Value) </code></pre> <p>As I said it is just an example because I don't know how to do it.</p>
<p>The most basic answer:<br> Assuming "xml" is an XMLDocument, XMLNodeList, XMLNode, etc... </p> <pre><code>Response.Write(xml.SelectSingleNode("//name").innerText) </code></pre>
<p>haven't tried testing it but should point you in the right direction anyway</p> <pre><code> 'Create the XML Document Dim l_xmld As XmlDocument 'Create the XML Node Dim l_node As XmlNode l_xmld = New XmlDocument 'Load the Xml file l_xmld.LoadXml("XML Filename as String") 'get the attributes l_node = l_xmld.SelectSingleNode("/customers/name") Response.Write(l_node.InnerText) </code></pre>
47,012
<p>We have a Java program run as <strong>root</strong> on Unix, that therefore can read for example the content of the folders <code>/home/user1</code> and <code>/home/user2</code>. However, if the Unix user "user1" is logged in in our application, he should not be able to access "/home/user2" data. We would like to use directly the Unix rights and not recreate all the permissions in our application ! So, could we...</p> <ol> <li>try to change the UID of our program depending on the user logged in ? Sounds difficult, and each file access is in different threads so the UID would be different on each thread of our program... </li> <li>use JNI to read permissions of "<code>/home/user2</code>"...And then determine if user1 has sufficient permissions on "<code>/home/user2</code>" ? (how ?).</li> </ol>
<p><strong>Use SecurityManager!</strong></p> <ol> <li>Put current unix user id into ThreadLocal</li> <li>Create your own SecurityManager that checks unix user permissions on checkRead() and checkWrite()</li> <li>System.setSecurityManager(new MySecurityManager())</li> <li>Enjoy</li> </ol> <p><strong>Update</strong></p> <p>There is no, of course, standard library to read unix file permissions. It's not WORA. </p> <p>But I have tried briefly to find a ready to use library, and found this one: <a href="http://jan.newmarch.name/java/posix/" rel="nofollow noreferrer">http://jan.newmarch.name/java/posix/</a> It uses JNI, but you don't need to write your own JNI code, which is a big relief. :) I'm sure there must also be others.</p> <p>Class Stat from there gives you all required access information: <a href="http://jan.newmarch.name/java/posix/posix.Stat.html" rel="nofollow noreferrer">http://jan.newmarch.name/java/posix/posix.Stat.html</a></p> <p><strong>Update 2</strong></p> <p>As folks mentioned, this approach fails to check for "non-standard" unix security features, such as ACL or Posix Capabilities (may be; not sure if they apply to files). But if the goal of being totally in sync with host OS security is set, then we even more need to use SecurityManager, because it's a JVM-wide protection mechanism! Yes, we can start a child SUID-process to verify the permissions (and keep it running, talking to it via pipe running while the user is logged in), <strong>but we need to do so from SecurityManager</strong>!</p>
<p>if you only want the app to be allowed to read files by user1 i strongly suggest the app runs as user1. </p>
33,160
<p>I'm currently working on putting together a fairly simple ORM tool to serve as a framework for various web projects for a client. Most of the projects are internal and will not require massive amounts of concurrency and all will go against SQL Server. I've suggested that they go with ORM tools like SubSonic, NHibernate, and a number of other open source projects out there, but for maintainability and flexibility reasons they want to create something custom. So my question is this: What are some features that I should make sure to include in this ORM tool? BTW, I'll be using MyGeneration to do the code generation templates.</p>
<p>For the love of all that's holy (and the women and the children), do everything possible to convince them not to go with a custom O/RM solution. Why are people wanting to re-invent the wheel when there are perfectly-good, open-source wheels already in existence?!?!</p>
<p>No-one has mentioned it yet; but go with <a href="http://www.llblgen.com/" rel="nofollow noreferrer">LLBLGen</a>. You may customise the template as you like, and you may also, obviously, write your own custom code in the generated classes. Buy it. You will never look back, and you will be saying "Thank you silky!" when it consistently works beautifully. (I didn't write it, but I love it). If it doesn't work out for you, you may also say "Damn you silky!". But that's unlikely, however I do offer it as an option.</p> <p>The only bad thing I noticed about LLBLGen has been the support for switching between Databases/servers on the fly. It doesn't support a feature that I'd like; namely the ability to detect that a given entity you retrieved doesn't "exist" in a new database that you've switched to. But this is a rare case.</p> <p>I suggest LLBLGen, because I was in the process of writing my own OR/M when I came across it. Never looked back.</p>
7,316
<p>I always forget to write subject in email, so I want make the subject field compulsory. Can you help me please?</p>
<pre><code>Private Sub Application_ItemSend(ByVal Item As Object, ByRef Cancel As Boolean) If Item.Subject = "" Then Item.Subject = InputBox("Please do not always forget the subject!") End If If Item.Subject = "" Then MsgBox "Won't send this without a subject." Cancel = True End If End Sub </code></pre>
<pre><code>Do While Item.Subject = "" Item.Subject = InputBox("..") Loop </code></pre>
48,891
<p>Scenario:</p> <p>I'm currently writing a layer to abstract 3 similar webservices into one useable class. Each webservice exposes a set of objects that share commonality. I have created a set of intermediary objects which exploit the commonality. However in my layer I need to convert between the web service objects and my objects.</p> <p>I've used reflection to create the appropriate type at run time before I make the call to the web service like so:</p> <pre><code> public static object[] CreateProperties(Type type, IProperty[] properties) { //Empty so return null if (properties==null || properties.Length == 0) return null; //Check the type is allowed CheckPropertyTypes("CreateProperties(Type,IProperty[])",type); //Convert the array of intermediary IProperty objects into // the passed service type e.g. Service1.Property object[] result = new object[properties.Length]; for (int i = 0; i &lt; properties.Length; i++) { IProperty fromProp = properties[i]; object toProp = ReflectionUtility.CreateInstance(type, null); ServiceUtils.CopyProperties(fromProp, toProp); result[i] = toProp; } return result; } </code></pre> <p>Here's my calling code, from one of my service implementations:</p> <pre><code>Property[] props = (Property[])ObjectFactory.CreateProperties(typeof(Property), properties); _service.SetProperties(folderItem.Path, props); </code></pre> <p>So each service exposes a different "Property" object which I hide behind my own implementation of my IProperty interface.</p> <p>The reflection code works in unit tests producing an array of objects whose elements are of the appropriate type. But the calling code fails:</p> <blockquote> <p>System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'MyProject.Property[]</p> </blockquote> <p>Any ideas?</p> <p>I was under the impression that any cast from Object will work as long as the contained object is convertable?</p>
<p>Alternative answer: generics.</p> <pre><code>public static T[] CreateProperties&lt;T&gt;(IProperty[] properties) where T : class, new() { //Empty so return null if (properties==null || properties.Length == 0) return null; //Check the type is allowed CheckPropertyTypes("CreateProperties(Type,IProperty[])",typeof(T)); //Convert the array of intermediary IProperty objects into // the passed service type e.g. Service1.Property T[] result = new T[properties.Length]; for (int i = 0; i &lt; properties.Length; i++) { T[i] = new T(); ServiceUtils.CopyProperties(properties[i], t[i]); } return result; } </code></pre> <p>Then your calling code becomes:</p> <pre><code>Property[] props = ObjectFactory.CreateProperties&lt;Property&gt;(properties); _service.SetProperties(folderItem.Path, props); </code></pre> <p>Much cleaner :)</p>
<p>That's correct, but that doesn't mean that you can cast containers of type Object to containers of other types. An Object[] is not the same thing as an Object (though you, strangely, could cast Object[] to Object).</p>
26,109
<p>I'm sorting out a series of SQL scripts for my company written in Oracle PL/SQL. I came across an essential script with a strangely placed slash near the bottom. It is checked into CVS this way. Is this a pure syntax error or does it have some function I'm not aware of. The slightly obfuscated script:</p> <pre><code>set serveroutput on size 2000; --PL/SQL block to link ISSN in serial base on a company's ISSN text file declare cursor ItemCursor is select issn is2 from web.obfuscated1 where issn is not null union select eissn is2 from web.obfuscated1 where eissn is not null; cursor ItemCursor1(aIS varchar2) is select obfuscated1_uid from web.obfuscated1 where group_num is null and issn in ( select distinct issn from web.obfuscated1 where issn = aIS or eissn = aIS union select distinct eissn from web.obfuscated1 where issn = aIS or eissn = aIS ) union select obfuscated1_uid from web.obfuscated1 where eissn in ( select distinct issn from web.obfuscated1 where issn = aIS or eissn = aIS union select distinct eissn from web.obfuscated1 where issn = aIS or eissn = aIS ); cursor ItemCursor2(aIS9 varchar2) is select obfuscated1_uid from web.obfuscated1 where issn in ( select distinct issn from web.obfuscated1 where issn = aIS9 or eissn = aIS9 union select distinct eissn from web.obfuscated1 where issn = aIS9 or eissn = aIS9 ) and group_num is null; agroup number(8); processCount number(8); ------------------------------------------------------ -- MAIN BLOCK ----------------------------------- ------------------------------------------------- begin processCount := 0; agroup := null; for itemRec in ItemCursor loop agroup := null; begin select group_num into agroup from web.obfuscated1 where issn in ( select distinct issn from web.obfuscated1 where issn = itemRec.is2 or eissn = itemRec.is2 union select distinct eissn from web.obfuscated1 where issn = itemRec.is2 or eissn = itemRec.is2 ) and group_num is not null and issn is not null and eissn is not null and rownum &lt;= 1; exception when no_data_found then agroup := null; when others then agroup := null; end; if agroup is not null then for itemRec2 in ItemCursor2(itemRec.is2) loop update web.obfuscated1 set group_num = agroup where obfuscated1_uid = itemRec2.obfuscated1_uid; commit; end loop; else processCount := processCount + 1; for itemRec1 in ItemCursor1(itemRec.is2) loop update web.obfuscated1 set group_num = processCount where obfuscated1_uid = itemRec1.obfuscated1_uid; commit; end loop; commit; end if; end loop; dbms_output.put_line('Total record read: ' || processCount); exception when others then dbms_output.put_line('ORA' || sqlcode); dbms_output.put_line(substr(sqlerrm, 1, 255)); dbms_output.put_line('ORA- Error during processing ' ); end; / exit; </code></pre>
<p>The slash has <a href="http://download.oracle.com/docs/cd/B28359_01/server.111/b31189/ch12004.htm#SQPUG162" rel="noreferrer">a meaning</a>:</p> <blockquote> <p>Executes the most recently executed SQL command or PL/SQL block which is stored in the SQL buffer. You can enter a slash (/) at the command prompt or at a line number prompt of a multi-line command. The slash command functions similarly to RUN, but does not list the command.</p> </blockquote>
<p>It is not an error. It executes the script. </p> <p>It is useful when you concatenate various scripts together in one file and want each separate task to execute before the next one.</p> <p>ie Create function / Create stored procedure that uses the function </p> <p>Without the slash the stored procedure may get created with errors or may not get created.</p>
23,489
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c">Can’t operator == be applied to generic types in C#?</a> </p> </blockquote> <p>I've got the following generic class and the compiler complains that "<code>Operator '!=' cannot be applied to operands of type 'TValue' and 'TValue'</code>" (see <a href="http://msdn.microsoft.com/en-us/library/a63h61ky.aspx" rel="nofollow noreferrer">CS0019</a>):</p> <pre><code>public class Example&lt;TValue&gt; { private TValue _value; public TValue Value { get { return _value; } set { if (_value != value) // &lt;&lt;-- ERROR { _value= value; OnPropertyChanged("Value"); } } } } </code></pre> <p>If I constrain <code>TValue</code> to <code>class</code>, I could use <code>Object.Equals()</code>. Since I need this for boths structs and classes I'd be very happy if I could avoid that though. </p> <p>So the question is, how can I compare two elements of the same but unconstrained generic type for equality?</p>
<p>Did you try something like this?</p> <pre><code>public class Example&lt;TValue&gt; { private TValue _value; public TValue Value { get { return _value; } set { if (!object.Equals(_value, value)) { _value = value; OnPropertyChanged("Value"); } } } } </code></pre>
<p>I think the <code>!=</code> operator cannot be applied here because there are cases where it can't be used. For instance, <code>!=</code> can't be used for comparing structs, unless the compare operators (<code>==</code> <code>!=</code>) are overloaded.</p> <p>Of course, you can compare language structs, like <code>int != int</code>, but I'm not sure how this is implemented.</p> <p>So, because TValue can be a <em>custom</em> struct, it cannot use the <code>!=</code> operator.</p>
43,702
<p>Can I use LoadLibrary method for to import a data of type struct?? excuse me for my English. thanks.</p>
<p>Let me assume some things that are left out in the question:</p> <ol> <li>You have a dynamic library called <strong>flubber.dll</strong></li> <li>The library exports the function <code>bool GetFlubber(Flubber* flubber)</code>.</li> <li>The function and the type <code>Flubber</code> (which just happens to be a <code>struct</code>!) are declared in a header file called <strong>flubber.h</strong>.</li> </ol> <p>If those 3 conditions are met, then you can use <code>LoadLibrary</code> on <strong>flubber.dll</strong>, followed by <code>GetProcAddress</code> with <code>GetFlubber</code> as proc name, and finally you can declare a <code>Flubber</code> instance locally and pass it to <code>GetFlubber</code> via the retrieved proc address.</p>
<p>As other responses have suggested it's hard to tell what's being asked here, but I'll throw in a response for another interpretation of the question. I'm not sure if it's "officially supported", but you can have a DLL export a global variable and then dynamically access it via GetProcAddress.</p> <p>For instance, if a library called foo.dll contains a global of type FOO named g_MyGlobal, then it can export the variable in foo.def. Client code can then call:</p> <pre><code>MyPointer = GetProcAddress(..., "g_MyGlobal"); </code></pre> <p>and get a "FOO *" pointer to the global.</p> <p>...but with that said, if you find yourself needing to do this for something other than private testing purposes, you might want to re-think your design. It would probably be much safer and cleaner to hide this global behind an exported function in the DLL.</p>
43,673
<p>I'm trying to read a file to produce a DOM Document, but the file has whitespace and newlines and I'm trying to ignore them, but I couldn't:</p> <pre><code>DocumentBuilderFactory docfactory=DocumentBuilderFactory.newInstance(); docfactory.setIgnoringElementContentWhitespace(true); </code></pre> <p>I see in Javadoc that setIgnoringElementContentWhitespace method operates only when the validating flag is enabled, but I haven't the DTD or XML Schema for the document.</p> <p>What can I do?</p> <p>Update</p> <p>I don't like the idea of introduce mySelf &lt; !ELEMENT... declarations and i have tried the solution proposed in the <a href="http://forums.sun.com/thread.jspa?messageID=2054303#2699961" rel="noreferrer">forum</a> pointed by Tomalak, but it doesn't work, i have used java 1.6 in an linux environment. I think if no more is proposed i will make a few methods to ignore whitespace text nodes</p>
<p>‘IgnoringElementContentWhitespace’ is not about removing <em>all</em> pure-whitespace text nodes, only whitespace nodes whose parents are described in the schema as having ELEMENT content — that is to say, they only contain other elements and never text.</p> <p>If you don't have a schema (DTD or XSD) in use, element content defaults to MIXED, so this parameter will never have any effect. (Unless the parser provides a non-standard DOM extension to treat all unknown elements as containing ELEMENT content, which as far as I know the ones available for Java do not.)</p> <p>You could hack the document on the way into the parser to include the schema information, for example by adding an internal subset to the &lt; !DOCTYPE ... [...] > declaration containing &lt; !ELEMENT ... > declarations, then use the IgnoringElementContentWhitespace parameter.</p> <p>Or, possibly easier, you could just strip out the whitespace nodes, either in a post-process, or as they come in using an LSParserFilter.</p>
<p>Try this:</p> <pre><code>private static Document prepareXML(String param) throws ParserConfigurationException, SAXException, IOException { param = param.replaceAll("&gt;\\s+&lt;", "&gt;&lt;").trim(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource in = new InputSource(new StringReader(param)); return builder.parse(in); } </code></pre>
28,383
<p>I want to keep logs of some things that people do in my app, in some cases so that it can be undone if needed.</p> <p>Is it best to store such logs in a file or a database? I'm completely at a loss as to what the pros and cons are except that it's another table to setup.</p> <p>Is there a third (or fourth etc) option that I'm not aware of that I should look into and learn about?</p>
<p>You will almost certainly want to use a database for flexible, record based access and to take advantage of the database's ability to handle concurrent data access. If you need to track information that may need to be undone, having it in a structured format is a benefit, as is having the ability to update a row indicating when and by whom a given transaction has been undone. </p> <p>You likely only want to write to a file if very high performance is an issue, or if you have very unstructured or large amounts of data per record that might be unweidly to store in a database. Note that Unless your application has a very large number of transactions database speed is unlikely to be an issue. Also note that if you are working with a file you'll need to handle concurrent access (read / write / locking) very carefully which is likely not something you want to have to deal with.</p>
<p>I'd use a database simply for maintainability - also multiple edits on a file may cause some getting missed out.</p>
5,653
<p>I'm looking for a 3D printer for applications in the dental field, for printing digital dental models (not for itra-oral use parts).</p> <p>Resolution and finish are the main requirements that we consider necessary.</p> <p>Any suggestion?</p>
<p>If resolution is your upmost concern then resin 3d printers are the way to go. They use a liquid resin that does not harden until a UV laser is shined through them. Apparently they get ultra high resolution and smooth finishes right out of the box. The downside is they are generally more expensive machines and the resin material itself is also a higher cost. but if you are in the dental field then money is not a problem. Look into resin 3d printers.</p> <p>otherwise if you want to try FDM printers then try looking into .1mm brass nozzles which will increase resolution but vastly increase print time. Not sure what material would be best. ABS has toxic smelling fumes, but is the same as LEGOS and is able to be easily smoothed (if necessary) with Acetone fumes. PLA might work well at .1mm nozzle resolution though and is a starch/dextrin based non-toxic biodegradable filament.</p>
<p>As mentionned by Andrew, resins should do the trick : most commons processes are SLA and DLP (DLP is faster but more expensive).</p> <ul> <li>If you aren't looking for precisions (or looking for low budget), FDM machines should do the trick. </li> <li>If you need metal, I think Solidscape or micro SLM should both work.</li> </ul> <p>You should specify what are your exigences, it's not the same to do an ultra-high precision metal part and to have a $300 maximum-budget machine.</p>
372
<p>Okay, I've seen but haven't programmed in C# before. You can assume I'm competent in C++, and advanced in C (for what good that'll do me). I understand inheritance, polymorphism, etc so OO concepts aren't going to be a huge problem.</p> <p>Let's say I've been given a task to prototype a quick and dirty program that won't be much different than what I could do in access in a short time.</p> <ul> <li>It'll have a DB with 5-6 tables (mostly small, a few with have several thousand rows but only 4 or so columns, etc)</li> <li>I'll need to have forms generated dynamically from one of the DBs</li> <li>The results of the forms will be stored in another table</li> <li>The DB isn't multiuser</li> </ul> <p>Basically your run of the mill access app... except without access. I'm sure I can muddle my way through and create horrendously bad code, but I'm equally sure lots of people here can give me a push in the right direction (tutorials, wizards, info, differences and killers moving from C/C++ to C#, etc).</p> <p>Is there a simple DB I can plug in to get started aside from mdb, or is that the best choice for this particular nail? I'm aiming for a quick and dependency-less install.</p> <p>Thanks!</p> <p>-Adam</p>
<p>It sounds like for this app, you could use <a href="http://www.asp.net/dynamicdata/" rel="nofollow noreferrer">Microsoft Dynamic Data</a> or <a href="http://www.castleproject.org/activerecord/index.html" rel="nofollow noreferrer">Castle Active Record</a>, and have the application working a few minutes after you finished the database. These tools connect to a database and generate forms for inputing data. Take a look at them.</p> <p>Access is probably your best choice for database. MS Sql 2005/2008 Express would also work well, but that would require an install.</p>
<p>If you already have MS Access installed, then yes the mdb is probably your quickest way to get started.</p> <p>Also you will want to just started with a quick ADO.NET tutorial. There are hundreds of these (well almost hundreds, I haven't counted).</p>
10,178
<p>The most common way of changing a cursor in Flash apps seems to be based on simply <strong>hiding the native OS cursor</strong> and <strong>displaying a graphic</strong> (drawn by the Flash Player) inside the Flash rectangle where the (hidden) cursor would be. This is what <a href="http://livedocs.adobe.com/flex/3/langref/mx/managers/CursorManager.html" rel="nofollow noreferrer"><code>mx.managers.CursorManager</code></a> does, for example. The reason why I find this approach unacceptable is that Flash Player isn't nearly fast enough at updating the cursor graphic, leading to some very <strong>visible lag</strong> in the cursor movement, which I find to be a pretty fundamental usability problem and annoyance, making the whole app seem slower than it really is.</p> <p>On the other hand, I've noticed that the <strong>CSS <a href="http://www.w3schools.com/CSS/tryit.asp?filename=trycss_cursor" rel="nofollow noreferrer"><code>cursor</code></a> property</strong> implementation in browsers works like it should -- i.e. there's no visible lag in the cursor movement when using it to implement a custom mouse cursor.</p> <p>So my question is: <em>is there any way to use the CSS <code>cursor</code> property (or any other method that doesn't involve lagging, slow cursor movement) to change the cursor on top of a Flash rectangle?</em></p> <p>I've already tried to change the <code>cursor</code> style property for a Flash element (or a <code>Div</code> wrapper around the Flash element) via JavaScript, but didn't seem to get it to work. Has anyone successfully done something like this?</p>
<p>Native cursors are available in Flash Player 10.2 beta. So you should give it a try! See: <a href="http://www.bytearray.org/?p=2373" rel="nofollow">http://www.bytearray.org/?p=2373</a></p>
<p>I understand your complaints, I too have been frustrated with how laggy the display-update can be. Thinking about the solution to use CSS to set a cursor-style in the browser though is an interesting approach... It smells, but off the top you may be able to implement control over the CSS cursor attribute from Actionscript using ExternalInterface. That way you could presumably communicate back to the HTML container calling some Javascript to modify the HTML page CSS at runtime. Not 100% sure that will work, but it may be worth a try if you are desperate. Otherwise it's probably advisable to stick with CursorManager.</p>
37,423
<p>On a web page I want to dynamically render very basic flow diagrams, i.e. a few boxes joined by lines. Ideally the user could then click on one of these boxes (<code>DIVs</code>?) and be taken to a different page. Resorting to Flash seems like an overkill. Is anyone aware of any client-side (i.e. <code>server agnostic</code>) Javascript or <code>CSS library/technique</code> that may help achieve this?</p>
<p>Does the rendering have to be client side?</p> <p>If yes, you could try Processing:</p> <p><a href="http://ejohn.org/blog/processingjs/" rel="nofollow noreferrer">http://ejohn.org/blog/processingjs/</a></p> <p>If you can do it server side, then Graphviz is a good choice.</p> <p><a href="http://www.graphviz.org/" rel="nofollow noreferrer">http://www.graphviz.org/</a></p>
<p>This kind of flowchart can be accomplished using CSS, resorting to JavaScript graphing libraries (canvas) might be overkill. You may wish to checkout how some Genealogy sites do this to get a family tree.</p>
4,729
<p>Short version: I want to trigger the Form_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property:</p> <pre><code>tasksForm.Visible = false; tasksForm.Show(); </code></pre> <p>Long version: I have a WinForms application with two forms: main and tasks. The main form is always displayed. The user can either click a button to open the tasks form, or click some buttons that just run a task directly without opening the tasks form.</p> <p>When a user asks to run a task directly, I'd like to just call some public methods on the tasks form without showing it. Unfortunately, the task logic depends on stuff that happens in the Form_Load() event. The only way I can find to trigger Form_Load() is to call Show(). The best I've been able to do is to show the form in the minimized state:</p> <pre><code>tasksForm.WindowState = FormWindowState.Minimized; tasksForm.Show(); </code></pre> <p>I suppose the cleanest solution would be to pull the tasks logic out of the tasks form and into a controller class. Then I can use that class from the main form and from the tasks form, and only load the tasks form when I need it visible for the user. However, if it's an easy thing to load the form without displaying it, that would be a smaller change.</p>
<p>I totally agree with Rich B, you need to look at where you are placing your application logic rather than trying to cludge the WinForms mechanisms. All of those operations and data that your Tasks form is exposing should really be in a separate class say some kind of Application Controller or something held by your main form and then used by your tasks form to read and display data when needed but doesn't need a form to be instantiated to exist. </p> <p>It probably seems a pain to rework it, but you'll be improving the structure of the app and making it more maintainable etc.</p>
<p>If you make the method public, then you could access it directly.... however, there could be some unexpected side effects when you call it. But making it public and calling it directly will not draw the screen or open the form.</p>
9,249
<p>I write a lot of dynamically generated content (developing under PHP) and I use jQuery to add extra flexibility and functionality to my projects.</p> <p>Thing is that it's rather hard to add JavaScript in an unobtrusive manner. Here's an example:</p> <p>You have to generate a random number of <code>div</code> elements each with different functionality triggered <code>onClick</code>. I can use the <code>onclick</code> attribute on my <code>div</code> elements to call a JS function with a parameter but that is just a bad solution. Also I could generate some jQuery code along with each div in my PHP <code>for</code> loop, but then again this won't be entirely unobtrusive.</p> <p>So what's the solution in situations like this?</p>
<p>You need to add something to the divs that defines what type of behaviour they have, then use jQuery to select those divs and add the behaviour. One option is to use the class attribute, although arguably this should be used for presentation rather than behaviour. An alternative would be the rel attribute, but I usually find that you also want to specify different CSS for each behaviour, so class is probably ok in this instance.</p> <p>So for instance, lets assume you want odd and even behaviour:</p> <pre><code>&lt;div class="odd"&gt;...&lt;/div&gt; &lt;div class="even"&gt;...&lt;/div&gt; &lt;div class="odd"&gt;...&lt;/div&gt; &lt;div class="even"&gt;...&lt;/div&gt; </code></pre> <p>Then in jQuery:</p> <pre><code>$(document).load(function() { $('.odd').click(function(el) { // do stuff }); $('.even').click(function(el) { // dostuff }); }); </code></pre> <p>jQuery has a very powerful selector engine that can find based on any CSS based selector, and also support some XPath and its own selectors. Get to know them! <a href="http://docs.jquery.com/Selectors" rel="nofollow noreferrer">http://docs.jquery.com/Selectors</a></p>
<p>It's a bit hard to tell from your question, but perhaps you can use different jQuery selectors to set up different click behaviours? For example, say you have the following:</p> <pre><code>&lt;div class="section-1"&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="section-2"&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Perhaps you could do the following in jQuery:</p> <pre><code>$('.section-1 div').onclick(...one set of functionality...); $('.section-2 div').onclick(...another set of functionality...); </code></pre> <p>Basically, decide based on context what needs to happen. You could also select all of the divs and test for some parent or child element to determine what functionality they get.</p> <p>I'd have to know more about the specifics of your situation to give more focused advice, but maybe this will get you started.</p>
15,373
<p>Given a function:</p> <pre><code>function x(arg) { return 30; } </code></pre> <p>You can call it two ways:</p> <pre><code>result = x(4); result = new x(4); </code></pre> <p>The first returns 30, the second returns an object.</p> <p>How can you detect which way the function was called <strong>inside the function itself</strong>?</p> <p>Whatever your solution is, it must work with the following invocation as well:</p> <pre><code>var Z = new x(); Z.lolol = x; Z.lolol(); </code></pre> <p>All the solutions currently think the <code>Z.lolol()</code> is calling it as a constructor.</p>
<p><strong>NOTE: This is now possible in ES2015 and later. See <a href="https://stackoverflow.com/a/31060154/96100">Daniel Weiner's answer</a>.</strong></p> <p>I don't think what you want is possible [prior to ES2015]. There simply isn't enough information available within the function to make a reliable inference.</p> <p>Looking at the ECMAScript 3rd edition spec, the steps taken when <code>new x()</code> is called are essentially:</p> <ul> <li>Create a new object</li> <li>Assign its internal [[Prototype]] property to the prototype property of <code>x</code></li> <li>Call <code>x</code> as normal, passing it the new object as <code>this</code></li> <li>If the call to <code>x</code> returned an object, return it, otherwise return the new object</li> </ul> <p>Nothing useful about how the function was called is made available to the executing code, so the only thing it's possible to test inside <code>x</code> is the <code>this</code> value, which is what all the answers here are doing. As you've observed, a new instance of* <code>x</code> when calling <code>x</code> as a constructor is indistinguishable from a pre-existing instance of <code>x</code> passed as <code>this</code> when calling <code>x</code> as a function, <strong>unless</strong> you assign a property to every new object created by <code>x</code> as it is constructed:</p> <pre><code>function x(y) { var isConstructor = false; if (this instanceof x // &lt;- You could use arguments.callee instead of x here, // except in in EcmaScript 5 strict mode. &amp;&amp; !this.__previouslyConstructedByX) { isConstructor = true; this.__previouslyConstructedByX = true; } alert(isConstructor); } </code></pre> <p>Obviously this is not ideal, since you now have an extra useless property on every object constructed by <code>x</code> that could be overwritten, but I think it's the best you can do.</p> <p><strong>(*)</strong> "instance of" is an inaccurate term but is close enough, and more concise than "object that has been created by calling <code>x</code> as a constructor"</p>
<p>Use <code>this instanceof arguments.callee</code> (optionally replacing <code>arguments.callee</code> with the function it's in, which improves performance) to check if something is called as a constructor. <strong>Do not</strong> use <code>this.constructor</code> as that can be easily changed.</p>
48,002
<p>From C#, I want to do the equivalent of the following:</p> <pre><code>arp -a |findstr 192.168.1.254 </code></pre> <p>Alternatively, the answer could call the <a href="http://msdn.microsoft.com/en-us/library/aa366358.aspx" rel="noreferrer">SendARP</a> function and get the results.</p> <p>This will allow my application to do some other processing that requires the MAC address.</p>
<p>SendARP P/Invoke goes like this:</p> <pre><code>[DllImport("iphlpapi.dll", ExactSpelling=true)] public static extern int SendARP( int destIp, int srcIP, byte[] macAddr, ref uint physicalAddrLen ); </code></pre> <p><a href="http://www.pinvoke.net/default.aspx/iphlpapi/SendARP.html" rel="noreferrer">PInvoke.NET</a> has this example:</p> <pre><code>IPAddress dst = IPAddress.Parse("192.168.2.1"); // the destination IP address byte[] macAddr = new byte[6]; uint macAddrLen = (uint)macAddr.Length; if (SendARP(BitConverter.ToInt32(dst.GetAddressBytes(), 0), 0, macAddr, ref macAddrLen) != 0) throw new InvalidOperationException("SendARP failed."); string[] str = new string[(int)macAddrLen]; for (int i=0; i&lt;macAddrLen; i++) str[i] = macAddr[i].ToString("x2"); Console.WriteLine(string.Join(":", str)); </code></pre>
<p>Hook into the WMI subsystem. Some VBScript code to get going in the right direction is <a href="http://www.microsoft.com/technet/scriptcenter/resources/qanda/jun05/hey0614.mspx" rel="nofollow noreferrer">here</a></p>
22,771
<p>I am searching for a host for a new commercial website. Among other things, I'd like to know what the various OS - Webserver combinations have in terms of vulnerabilities. What are the vulnerabilities of Windows 2003 + Apache?</p>
<p>You could look here: <a href="http://httpd.apache.org/security/vulnerabilities_20.html" rel="nofollow noreferrer">http://httpd.apache.org/security/vulnerabilities_20.html</a></p> <p>As for the windows side, it's windows. There are going to be vulnerabilities. Just stay up to date with service packs and patches, and you'll be fine.</p>
<p>As suggested <a href="https://stackoverflow.com/questions/87393/what-are-the-major-vulnerabilities-of-windows-2003-iis">here</a>, I could check out the <a href="http://www.kb.cert.org/vuls/" rel="nofollow noreferrer">CERT Database</a>.</p>
11,291
<p>I've got a stock Debian Etch system, using Exim4. The domains are mostly local but there are some that are remote. To handle the delivery of remote mail I use the Debian configuration file:</p> <pre><code> /etc/exim4/hubbed_hosts </code></pre> <p>This file lists the domain names, and remote MX machines to deliver to. For example:</p> <pre><code> example.org: mx.example.com example.com: mx2.example.com </code></pre> <p>Looking at the exim4 configuration file I see that this used as follows:</p> <pre><code>hubbed_hosts: debug_print = "R: hubbed_hosts for $domain" driver = manualroute domains = "${if exists{CONFDIR/hubbed_hosts}\ {partial-lsearch;CONFDIR/hubbed_hosts}\ fail}" route_data = ${lookup{$domain}partial-lsearch{CONFDIR/hubbed_hosts}} transport = remote_smtp </code></pre> <p>The issue I have is that <em>some</em> of the hosts I'm using need to have their mail delivered to a non-standard port. Unfortunately the Debian hubbed_hosts file doesn't work if I try to change it to include a port:</p> <pre><code>example.org: mx1.example.org:2525 example.com: 1.2.3.4.2525 </code></pre> <p>Is it possible to dynamically allow the port to be specified?</p>
<p>I was hoping for something a little more dynamic - and this solution works:</p> <pre><code> port = ${if exists{/etc/exim4/ports.list}\ {${lookup{$domain}lsearch{/etc/exim4/ports.list}\ {$value}{25}}}{25}} </code></pre> <p>Then a simple file may have a list of ports on a per-domain basis:</p> <pre><code> example.org: 2525 example.com: 26 </code></pre>
<p>make a new transport that specifies the port</p> <pre><code>remote_hub_2525: driver = smtp port = 2525 </code></pre> <p>and then create a router for the domains needing non-standard delivery</p> <pre><code>non_standard_hub: driver = manualroute domains = example.org : example.com transport = remote_hub_2525 no_more </code></pre>
18,701
<p>I have a .NET Web app which consumes a Java-based Web service. One of the objects, named Optional, contains search criteria fields. The schema is the following:</p> <pre><code>&lt;xsd:complexType name="Optional"&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="FromAmount" nillable="true" type="xsd:float" minOccurs="0" /&gt; &lt;xsd:element name="ToAmount" nillable="true" type="xsd:float" minOccurs="0" /&gt; &lt;xsd:element name="FromDate" nillable="true" type="xsd:dateTime" minOccurs="0" /&gt; &lt;xsd:element name="ToDate" nillable="true" type="xsd:dateTime" minOccurs="0" /&gt; &lt;xsd:element name="FromCheckNumber" nillable="true" type="xsd:long" minOccurs="0" /&gt; &lt;xsd:element name="ToCheckNumber" nillable="true" type="xsd:long" minOccurs="0" /&gt; &lt;/xsd:sequence&gt; &lt;/xsd:complexType&gt; </code></pre> <p>The problem that I am running into is that the child elements will not serialize even when a value is assigned to them in the Web app. If I remove the minOccurs attribute, then all is well.</p> <p>How do I get these elements to be optional, but to serialize when a value is assigned to them?</p> <p>Thanks in advance for your help.</p>
<p>in .NET WS for non-nullable types (in .NET) that are marked optional in the schema have an additional specified property generated for them that control if the element appears. Very annoyingly, the setter for the value does not set the additional specified flag, so you need do this.</p> <pre><code>x.ToAmmount = 24.0f; x.ToAmmountSpecified = true; // etc for the rest of the poperties </code></pre>
<p>This schema does not define any xml document type. It just provides a declaration for a compex type named "Optional", but there is no reference to this type from anywhere.</p> <p>The xml document being defined must have at least a top element. this top element needs to be defined somewhere (at a global scope). There is no such definition in the provided schema.</p> <p>A minimal example of an xml schema, which is similar to the provided one, but does define an xml document is the following:</p> <pre>&lt;?xml version="1.0" encoding="utf-8"?> &lt;xsd:schema elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema" > &lt;xsd:element name="Optional" type="Optional"/> &lt;xsd:complexType name="Optional"> &lt;xsd:sequence> &lt;xsd:element name="FromAmount" nillable="true" type="xsd:float" minOccurs="0" /> &lt;xsd:element name="ToAmount" nillable="true" type="xsd:float" minOccurs="0" /> &lt;xsd:element name="FromDate" nillable="true" type="xsd:dateTime" minOccurs="0" /> &lt;xsd:element name="ToDate" nillable="true" type="xsd:dateTime" minOccurs="0" /> &lt;xsd:element name="FromCheckNumber" nillable="true" type="xsd:long" minOccurs="0" /> &lt;xsd:element name="ToCheckNumber" nillable="true" type="xsd:long" minOccurs="0" /> &lt;/xsd:sequence> &lt;/xsd:complexType> &lt;/xsd:schema></pre> <p>and the simplest xml document that can be successfully validated against this schema is just</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;<code>&lt;Optional/&gt;</code></p> <p>(since all of the children of the top element are defined as optional).</p> <p>Hope this helped.</p> <p>Cheers,</p> <p>Dimitre Novatchev</p>
38,272
<p>I have an MFC application compiled with /clr and I'm trying to implement a final handler for otherwise un-caught managed exceptions. For native exceptions, overriding <code>CWinApp::ProcessWndProcException</code> works.</p> <p>The two events suggested in Jeff's <a href="http://www.codeproject.com/KB/exception/ExceptionHandling.aspx" rel="nofollow noreferrer">CodeProject article</a>,<code>Application.ThreadException</code> and <code>AppDomain.CurrentDomain.UnhandledException</code>, are not raised.</p> <p>Can anyone suggest a way to provide a final managed exception handler for a mixed executable?</p> <hr> <p>Update:</p> <p>It appears that these exception handlers are only triggered downstream of <code>Application.Run</code> or similar (there's a worker thread flavor, can't remember the name.) If you want to truly globally catch a managed exception you do need to install an SEH filter. You're not going to get a <code>System.Exception</code> and if you want a callstack you're going to have to roll your own walker.</p> <p>In an MSDN forum question on this topic it was suggested to override a sufficiently low-level point of the main MFC thread in a <code>try ... catch (Exception^)</code>. For instance, <code>CWinApp::Run</code>. This may be a good solution but I haven't looked at any perf or stability implications. You'll get a chance to log with a call stack before you bail and you can avoid the default windows unahndled exception behavior.</p>
<p>Taking a look around the internets, you'll find that you need to install a filter to get the unmanaged exceptions passing the filters on their way to your AppDomain. From <a href="http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12/30/clr-and-unhandled-exception-filters.aspx" rel="nofollow noreferrer">CLR and Unhandled Exception Filters</a>:</p> <blockquote> <p>The CLR relies on the SEH unhandled exception filter mechanism to catch unhandled exceptions.</p> </blockquote>
<p>Using those two exception handlers should work. Are you sure you've added them in a place where they're going to be called and properly set (ie, in your application's <em>managed</em> entry point -- you did put one in, right?)</p>
3,019
<p>I frequently find myself writing code like this:</p> <pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 3, 5 }; foreach (int i in list) { Console.Write("{0}\t", i.ToString()); } Console.WriteLine(); </code></pre> <p>Better would be something like this:</p> <pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 3, 5 }; Console.WriteLine("{0}\t", list); </code></pre> <p>I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block? </p>
<p>Do this:</p> <pre><code>list.ForEach(i =&gt; Console.Write("{0}\t", i)); </code></pre> <hr> <p>EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :)</p>
<pre><code>public static void WriteLine(this List&lt;int&gt; theList) { foreach (int i in list) { Console.Write("{0}\t", t.ToString()); } Console.WriteLine(); } </code></pre> <p>Then, later...</p> <pre><code>list.WriteLine(); </code></pre>
7,626
<p>What happens when I do the following?</p> <pre><code>(define ((func x) y) (if (zero? y) ((func x) 1) 12)) </code></pre> <p>I understand that I can do this:</p> <pre><code>(define curried (func 5)) </code></pre> <p>And now I can use curried. What I'm curious about is in the definition of the function. Does the line</p> <pre><code>((func x) 1) </code></pre> <p>create a new lambda with x as the argument, and then invoke it on 1? Or is it smarter than that and it just re-uses the existing one. (For example, if I do <code>(curried 0)</code>, the <code>((func x) 1)</code> line would be equivalent to <code>(curried 1)</code> - does PLAI Scheme do this?)</p>
<p>In the Scheme standard it is specified that</p> <pre><code>(define (f x) 42) is short for (define f (lambda (x) 42)) . </code></pre> <p>The natural (non-standard) generalization implies:</p> <pre><code>(define ((f x) y) (list x y)) is short for (define (f x) (lambda (y) (list x y))) which is short for (define f (lambda (x) (lambda (y) (list x y)))) </code></pre> <p>To test it, let's try the example in DrScheme</p> <p>Welcome to DrScheme, version 4.1.3.3-svn5dec2008 [3m]. Language: Module; memory limit: 384 megabytes.</p> <blockquote> <p>(define ((f x) y) (list x y)) (f 1)</p> <h1></h1> <p>((f 1) 2) (1 2)</p> </blockquote> <p>If we name the temporary value, it might be easier to see what happens:</p> <blockquote> <p>(define h (f 1)) (h 2) (1 2) (h 3) (1 3)</p> </blockquote> <p>Since "PLAI Scheme" is implemented in DrScheme, I believe it inherits this shortcut notation.</p>
<p>soegaard's answer is correct - this is the traditional expansion. However, drscheme is smart!</p> <p>The following code I've found to be equivalent in running time:</p> <p>Original source:</p> <pre><code>(define ((substitute lv value) e) (cond [(LogicVar? e) (type-case LogicVar e [lv-any (id) (if (symbol=? id (lv-any-id lv)) value e)] [lv-cons (f r) (lv-cons ((substitute lv value) f) ((substitute lv value) r))])] [(cons? e) (cons ((substitute lv value) (car e)) ((substitute lv value) (cdr e)))] [else e])) </code></pre> <p>Attempt at optimization:</p> <pre><code>(define (substitute lv value) (local ([define inner (lambda (e) (cond [(LogicVar? e) (type-case LogicVar e [lv-any (id) (if (symbol=? id (lv-any-id lv)) value e)] [lv-cons (f r) (lv-cons (inner f) (inner r))])] [(cons? e) (cons (inner (car e)) (inner (cdr e)))] [else e]))]) inner)) </code></pre> <p>Code which heavily uses this function (multiple times, not just once) runs at 1800 ms for both versions. More interestingly, this version (my visualization of what was happening):</p> <pre><code>(define (substitute lv value) (local ([define inner (lambda (e) (cond [(LogicVar? e) (type-case LogicVar e [lv-any (id) (if (symbol=? id (lv-any-id lv)) value e)] [lv-cons (f r) (lv-cons ((substitute lv value) f) ((substitute lv value) r))])] [(cons? e) (cons ((substitute lv value) (car e)) ((substitute lv value) (cdr e)))] [else e]))]) inner)) </code></pre> <p>Runs at 2000 ms. So there is definitely a slow-down if the calls to substitute within substitute were each creating a lambda, but it appears this is not the case with the shortcut notation.</p>
46,592
<p>I am printing a small cylinder, but when the object is finished, it's smaller than the measures I used when create the model.</p> <p>I used thincerkad to make a simple model, the measures are:</p> <ul> <li>width: 90 mm</li> <li>height: 2 mm</li> </ul> <p>After the print was done, the actual dimensions were:</p> <ul> <li>width: 70 mm</li> <li>height: 2 mm</li> </ul> <h3>Pictures</h3> <p>First attempt</p> <p><a href="https://i.stack.imgur.com/ESch8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ESch8.jpg" alt="one"></a></p> <p>The smaller object that's in the drawn circle was the first one printed, the dimensions I used were:</p> <ul> <li>width: 110 mm</li> <li>height: 2 mm</li> </ul> <p>Then I printed it again, and the result was:</p> <p><a href="https://i.stack.imgur.com/TAAPI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TAAPI.jpg" alt="Two"></a></p>
<p>Let's do the math, you printed something of size 9&nbsp;cm and got a size of 7&nbsp;cm. This implies that the scale equals <span class="math-container">$\frac{7}{9}=0.778$</span>. In order to print it at the correct size, you should have printed the object at scale <span class="math-container">$\frac{1}{0.778}=1.286$</span>; so 28.6&nbsp;% bigger, i.e. <span class="math-container">$1.286\times9=11.6$</span>&nbsp;cm. You printed at 11&nbsp;cm, so the print should become smaller than the pencil drawn circle on the paper. This is actually what you see in the image you supplied.</p> <p>This can imply 2 things, you either scale the prints incorrectly to export to stl (but that is unlikely because the Z height is correct), or the steps per mm are incorrectly set in the firmware of your printer. The rotation of the steppers (usually 200 steps) need to be translated into linear movement; this depends on the used pulleys mounted on the steppers (typically used pulleys are: 16 or 20 teeth for belt driven X and Y axes).</p> <p>Calibrating the steps per mm of the extruder is answered in <a href="/a/6484/">this answer</a>. For the X and Y axis this works the same. If you have a Marlin based printer firmware, send G-code <a href="https://reprap.org/wiki/G-code#M503:_Print_settings" rel="nofollow noreferrer"><code>M503</code></a> to the printer over a terminal interface as e.g. OctoPrint, Pronterface (as part from Printrun: 3D printing host suite), Repetier-Host have, you can obtain the current values from the reply; these are listed under M92.</p> <p>That value for X and Y needs to be multiplied by 1.286 (as an example) to get the correct dimensions. You do this by sending G-code <a href="https://reprap.org/wiki/G-code#M92:_Set_axis_steps_per_unit" rel="nofollow noreferrer"><code>M92</code></a> like <code>M92 X100.00 Y100.00</code> (see <a href="/a/10318">this answer</a> that explains which values you should use based on pulleys you use, either 80 or 100) to the printer, to keep these values they need to be stored in memory using G-code <a href="https://reprap.org/wiki/G-code#M500:_Store_parameters_in_non-volatile_storage" rel="nofollow noreferrer"><code>M500</code></a> (note that the values 100.00 should be replaced by the values you get by multiplying the return values for X and Y from <code>M503</code> by the 1.286 multiplication factor, only if the error is systematically increasing with print dimensions, otherwise stick to the calculated values from e.g. the Prusa belt calculator). </p> <p>Without the proper steps per mm, you will not be able to use the full potential of the bed. An alternative as scaling your prints by the appropriate scaling factor will only help if your scaled print is smaller than the bed size divided by that scaling factor, so no use of the full bed. Rather fix the firmware to fit the actual mechanical layout.</p>
<p>Are you using the stock firmware of your printer? Sounds like to me that you have 16 tooth pulleys and your firmware is set to 20 tooth i.e. 80 steps per mm</p> <p>The calculation behind the steps per mm is <span class="math-container">$\frac{\text{Steps per Revolution} \times Microsteps}{Teeth \times Pitch}$</span>. The reason for this is that one revolution of the pulley will move the belt the number of teeth times the pitch of the belt. Now take the total number of steps, Steps per Revolution times microsteps, and divide by the distance moved giving the steps per mm.</p> <p>In <span class="math-container">$\underline{most}$</span> hobby 3D printers you have:</p> <ul> <li>1.8 degrees steppers which equals <span class="math-container">$\frac{360}{1.8}=200$</span> steps per revolution , Less common is 0.9 degrees steppers <span class="math-container">$\frac{360}{0.9}=400$</span></li> <li>GT2 is the most common belts now which have a pitch of 2mm</li> <li>The two most common pulleys are 16 tooth and 20 tooth, </li> <li>Depending on what stepper drivers and or configuration you have <ul> <li>A4988 <span class="math-container">$\to$</span> 16 microsteps</li> <li>DRV8825 <span class="math-container">$\to$</span> 32 microsteps</li> <li>Trinamic <span class="math-container">$\to$</span> 16-256 mircosteps</li> </ul></li> </ul> <p>In your situation I believe you have a 1.8 degree stepper with 16 microsteps, a gt2 belt, and a 16 tooth pulley. Which means your XY steps per mm should be <span class="math-container">$\frac{200 \times 16}{16 \times 2} = 100$</span>. While your firmware is expecting 20 tooth pulleys, yielding <span class="math-container">$\frac{200 \times 16}{20 \times 2} = 80$</span>. This would result in your prints being <span class="math-container">$\frac{100-80}{100} = 20\%$</span> smaller, which explains your results with the circles.</p> <p>Generalizing, the steppers, microsteps, and pitch don't matter. To go between 16 tooth pulleys to 20 tooth, multiply by <span class="math-container">$0.8=\frac{16}{20}$</span>. From 20 tooth to 16 tooth, multiply by <span class="math-container">$1.25=\frac{20}{16}$</span>.</p>
1,364
<p>In my engine I have a need to be able to detect DXT1 textures that have texels with 0 alpha (e.g. a cutout for a window frame). This is easy for textures I compress myself, but I'm not sure about textures that are already compressed.</p> <p>Is there an easy way to tell from the header whether a DDS image contains alpha?</p>
<p>As far as I know, there's no way to tell from the header. There's a DDPF_ALPHAPIXELS flag, but I don't think that will get set based on what's in the pixel data. You'd need to parse the DXT1 blocks, and look for colours that have 0 alpha in them (making sure to check that the colour is actually used in the block, too, I suppose).</p>
<p>I agree with the accepted answer. Your job may be made a bit easier by using the "squish" library to decompress the blocks for you.</p> <p><a href="http://www.sjbrown.co.uk/?code=squish" rel="nofollow noreferrer">http://www.sjbrown.co.uk/?code=squish</a></p>
3,991
<p>Currently when I build my site I have to manually open validate it at the 3wbc site (means when opera pops up, press ctr+alt+shft+u) for every page. Is it possible to automatically validate every page whenever I build my pages?</p> <p>P.s.: This page doesn't validate ;)</p>
<p>You can download and install your own copy of the validator - <a href="http://validator.w3.org/source/" rel="nofollow noreferrer">http://validator.w3.org/source/</a> - and invoke it locally instead of trekking out to w3.org for each page. Still, this requires piggybacking over a web server through plain HTTP or the API. For a simpler solution you may prefer to download the SP library - <a href="http://www.jclark.com/sp/index.htm" rel="nofollow noreferrer">http://www.jclark.com/sp/index.htm</a> or <a href="http://openjade.sourceforge.net/" rel="nofollow noreferrer">http://openjade.sourceforge.net/</a> - on which the W3 validator is based, then invoke the command 'nsgmls' from the command line.</p> <p>There are of course also many desktop HTML validators that can process a batch of HTML pages at once, which may not be automated, but would certainly be much easier than manually checking each page. For example <a href="http://arealvalidator.com/" rel="nofollow noreferrer">http://arealvalidator.com/</a> (Windows), <a href="http://www.webthing.com/software/validator-lite/install.html" rel="nofollow noreferrer">http://www.webthing.com/software/validator-lite/install.html</a> (Unix).</p>
<p>If you've got the HTML files in source control like SVN or Git, you can use a pre-commit hook script to run client-side validators on them. Or if you're feeling adventurous, you could use that method to ping another script on the server that validates the live pages...</p>
27,229
<p>I need to search all cpp/h files in svn working copy for "foo", excluding svn's special folders completely. What is the <strong>exact</strong> command for GNU grep?</p>
<p>I use <a href="http://petdance.com/ack/" rel="nofollow noreferrer">ack</a> for this purpose, it's like grep but automatically knows how to exclude source control directories (among other useful things).</p>
<p>This is a RTFM. I typed 'man grep' and '/exclude' and got:</p> <p>--exclude=GLOB Skip files whose base name matches GLOB (using wildcard matching). A file-name glob can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally.</p> <p>--exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude).</p> <p>--exclude-dir=DIR Exclude directories matching the pattern DIR from recursive searches.</p>
25,519
<p>I am creating an application for a Windows Mobile computer. The catch is that the device (<a href="http://www.motorola.com/business/v/index.jsp?vgnextoid=d4397b103d175110VgnVCM1000008406b00aRCRD" rel="nofollow noreferrer">Motorola MC17</a>) does not have a touch screen or universal keys - there are only six programmable hardware keys. <a href="http://en.wikipedia.org/wiki/Fitts%27s_law" rel="nofollow noreferrer">Fitt's law</a> is not applicable here, most Microsoft guidelines are also moot. For now I'm mimicking Nokia's S60 keyboard layout as close as possible, since it's the most popular phone platform among my target audience.</p> <p><img src="https://i.stack.imgur.com/jsDo2.jpg" alt="Motorola MC17"/></p> <p>Are there any guidelines for creating a simple, discoverable user interface on such a constrained device? What fonts and colours should I use to make my UI readable? How do I measure if the items on-screen are big enough? What conventions should I follow?</p>
<p>Last time I checked, you could use the <a href="http://developers.sugarcrm.com/tutorials/Customizing_Sugar/4/" rel="nofollow noreferrer">module builder</a> to extend the interface. From 5.0 (or maybe 4.x) on, Sugar added all those APIs, which should enable you to extend SugarCRM without hacking it in and losing it with the next upgrade.</p> <p>Hope that helps!</p>
<p>Basically, the Account name should be a related field in your new invoices module (base the module creation on something like QUOTES that has similar fields. Once you create the module (so simple you can almost guess your way through it in the ADMIN section) and the fields you like (using Studio) just add the RELATED field Account Name and the sub-panel will be established in your ACCOUNTS module and the invoice will magically populate, especially if you re-install them using the import feature from a CSV file (spreadsheet).</p>
5,856
<p>I'm about to start a project for a customer who wants CMS-like functionality. They want users to be able to log in, modify a profile, and a basic forum. They also wish to be able to submit things to a front page.</p> <p>Is there a framework or barebones CMS that I could expand on or tailor to my needs? I don't need anything as feature-rich or fancy as Drupal or Joomla. I would actually prefer a framework as opposed to a pre-packaged CMS.</p> <p>I am confident I could code all this from scratch, but would prefer not to, as something like a framework would significantly cut down on my time spent coding, and more on design and layout.</p> <p>Edit: I should have been more specific. I'm looking for a Content Management System that will be run on a Debian server. So no .net preferably.</p> <hr> <p>I think i may end up going with Drupal, and only adding modules that I need. Turbogears looks a bit daunting, and i'm still not quite sure what it does after it's 20 minute intro video...</p> <p>TinyCMS doesn't look like it's been touched since... 2000?!?</p>
<p><a href="http://tinycms.sourceforge.net/" rel="nofollow noreferrer">tinyCMS</a> is about as barebones as you can get. (<strong>edit</strong>: fixed link, I had gotten a little click happy and linked to the wrong thing)</p> <p>@modesty, I would definitely NOT use SharePoint, as it is anything <strong>but</strong> barebones. It is a fairly expensive product (especially when compared to the many free alternatives), and it has quite the learning curve to do anything interesting.</p>
<p>Might want to check out <a href="http://drupal.org/" rel="nofollow noreferrer">Drupal</a>. </p> <p>Here are the details of the <a href="http://drupal.org/node/176052" rel="nofollow noreferrer">technology stack</a> that it uses. </p> <p>I have never used it so I can't vouch for the quality etc but definitely worth a look.</p>
2,616
<p>I am just starting to learn javascript, so I don't have the skills to figure out what I assume is a trivial problem.</p> <p>I'm working with a Wordpress blog that serves as a FAQ for our community and I am trying to pull together some tools to make managing the comments easier. <a href="https://stackoverflow.com/users/4465/levik">Internet Duct Tape's Greasemonkey tools, like Comment Ninja</a>, are helpful for most of it, but I want to be able to get a list of all the IP addresses that we're getting comments from in order to track trends and so forth.</p> <p>I just want to be able to select a bunch of text on the comments page and click a bookmarklet (<a href="https://stackoverflow.com/users/8119/jacob">http://bookmarklets.com</a>) in Firefox that pops up a window listing all the IP addresses found in the selection.</p> <p><strong>Update:</strong></p> <p>I kind of combined a the answers from <a href="https://stackoverflow.com/users/4465/levik">levik</a> and <a href="https://stackoverflow.com/users/8119/jacob">Jacob</a> to come up with this:</p> <pre><code>javascript:ipAddresses=document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g).join("&lt;br&gt;");newWindow=window.open('', 'IP Addresses in Selection', 'innerWidth=200,innerHeight=300,scrollbars');newWindow.document.write(ipAddresses) </code></pre> <p>The difference is that instead of an <em>alert</em> message, as in levik's answer, I open a new window similar to Jacob's answer. The <em>alert</em> doesn't provide scroll bars which can be a problem for pages with many IP addresses. However, I needed the list to be vertical, unlike Jacob's solution, so I used the hint from levik's to make a <em><br></em> for the join instead of levik's <em>\n</em>. </p> <p>Thanks for all the help, guys.</p>
<p>In Firefox, you could do something like this:</p> <pre><code>javascript:alert( document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g) .join("\n")) </code></pre> <p>How this works:</p> <ul> <li>Gets the selection text from the browser ("document.getSelection()" in FF, in IE it would be "document.selection.createRange().text")</li> <li>Applies a regular expression to march the IP addresses (as suggested by Muerr) - this results in an array of strings.</li> <li>Joins this array into one string separated by return characters</li> <li>Alerts that string</li> </ul> <p>The way you get the selection is a little different on IE, but the principle is the same. To get it to be cross-browser, you'd need to check which method is available. You could also do more complicated output (like create a floating DIV and insert all the IPs into it).</p>
<p><a href="http://javascript.about.com/library/blip.htm" rel="nofollow noreferrer">Here</a> is a good article on obtaining the IP address of your visitors. You could display this in addition to their comment if you wanted or include it as a label or field in your page so you can reference it later.</p>
9,852
<p>I'm in the process of building the <a href="http://www.thingiverse.com/thing:1001065" rel="nofollow noreferrer">D-Bot core XY</a> printer, and I was hoping to know if the Z-axis 'zero' is near the hot end or near the bottom of the printer furthest away from the hotend? In this printer the Z-platform moves up and down and the nozzle stays at the same height.</p>
<p>Generally, Z-axis zero is when the hot end and the build plate are close to each other. Some printers keep the hot end up at the top, and bring the build plate up to reach it. Other printers keep the build plate at the bottom, and lower the hot end down to reach it. As such, "Z axis zero" doesn't specify top or bottom of the physical printer, it just specifies that the hot end is right up against the build plate, ready to print its first layer. In the printer you describe, where the hot end remains at the top, that's where Z zero is.</p> <p>In terms of the model being printed, Z axis zero is always the bottom of the model, the first layer to be deposited on the build plate. The numbers increase from there, either lifting the hot end up, or pushing the build plate down, depending on the design of the printer.</p>
<p>Yes, Z-Zero is typically at the "top" of the printer, closest to the nozzle(s). X and Y zeros are also typically in the lower-left corner of the buildplate.</p> <p>However, the XY zeros are re-interpreted in slicing software to produce cleaner G-Code as it's sometimes difficult to read G-Code in negative coordinates. For this functionality, slicing engines utilize the machine build space length and width.</p> <p>So if you encounter a situation where your machine "over travels" in either -X or -Y direction during startup, verify that the length and width of your build space is correct in your slicing engine.</p>
456
<p>I'm having a problem using CSS's <code>display:inline</code> property with the <code>list-style-image:</code> property on <code>&lt;li&gt;</code> tags. Basically, I want to output the following:</p> <pre><code>* Link 1 * Link 2 </code></pre> <p>where <code>*</code> represents an image.</p> <p>I'm doing this with the following bit of HTML:</p> <pre><code>&lt;ol class="widgets"&gt; &lt;li class="l1"&gt;Link 1&lt;/li&gt; &lt;li class="l2"&gt;Link 2&lt;/li&gt; &lt;/ol&gt; </code></pre> <p>which is styled with the following bit of CSS:</p> <pre><code>ol.widgets { list-style-type:none; } ol.widgets li { display:inline; margin-left:10px; } ol.widgets li.l1 { list-style-image:url(image1.gif); } ol.widgets li.l2 { list-style-image:url(image2.gif); } </code></pre> <p>The problem is that when the list items are displayed inline, the images associated with the list items do not appear. They <em>do</em> appear if I take out the <code>display:inline</code> property on the <code>&lt;li&gt;</code> tag.</p> <p>Is there a way to make the images appear even when the list items are displayed inline, or is that just impossible?</p>
<p>Try using <code>float: left</code> (or <code>right</code>) instead of <code>display: inline</code>. Inline display replaces list-item display, which is what adds the bullet points.</p>
<p>I would suggest not to use <code>list-style-image</code>, as it behaves quite differently in different browsers, especially the image position</p> <p>instead, you can use something like this</p> <pre><code>ol.widgets, ol.widgets li { list-style: none; } ol.widgets li { padding-left: 20px; backgroud: transparent ("image") no-repeat x y; } </code></pre> <p>it works in all browsers and would give you the identical result in different browsers.</p>
46,152
<p>Recently I noticed my application appears to be eating memory that never gets released. After profiling with CLRProfiler I've found that the Castle Windsor container I'm using is holding onto objects. These objects are declared with the lifestyle="transient" attribute in the config xml.</p> <p>I've found if I put an explicit call to <code>IWindsorContainer.Release(hangingObject)</code>, that it will drop its references.</p> <p>This is causing a problem though, I wasn't expecting that with a transient lifestyle object CastleWindsor would keep a reference and effectively create a leak. It's going to be a rather mundane and error prone task going around inserting explicit Release calls in all the appropriate places.</p> <p>Have you seen this problem, and do you have any suggestions for how to get around it?</p>
<p>I think the answers here are missing a vital point - that this behavior is configurable out of the box via release policies - check out the documentation on the castle project site <a href="http://www.castleproject.org/container/documentation/trunk/advanced/releasepolicy.html" rel="nofollow noreferrer">here</a>.</p> <p>In many scenarios especially where your container exists for the lifetime of the hosting application, and where transient components really don't need to be tracked (because you're handling disposal in your calling code or component that's been injected with the service) then you can just set the release policy to the <code>NoTrackingReleasePolicy</code> implementation and be done with it.</p> <p>Prior to Castle v 1.0 I believe Component Burden will be implemented/introduced - which will help alleviate some of these issues as well around disposal of injected dependencies etc.</p> <p><strong>Edit:</strong></p> <p>Check out the following posts for more discussion of component burden.</p> <p><a href="http://elegantcode.com/2008/12/14/the-component-burden/" rel="nofollow noreferrer">The Component Burden - Davy Brions</a></p> <p>Also component burden is implemented in the <a href="http://ayende.com/Blog/archive/2009/05/05/castle-windsor-2.0-rtm-released.aspx" rel="nofollow noreferrer">official 2.0 release</a> of the Windsor Container.</p>
<p>You can set a lifestyle of singleton or transient though on objects in the container. Singleton objects I understand should last the life of the application, but I don't understand the usefulness of this behvaviour being the same for transient ones!</p> <p>Custom lifestyles can be created by implementing <code>ILifestyleManager</code>. Maybe it's possible to implement this suitably to create a <code>ReallyTransient</code> lifestyle type!</p>
16,102
<p>I know RIM has their own IDE (<a href="http://na.blackberry.com/eng/developers/downloads/jde.jsp" rel="nofollow noreferrer">BlackBerry JDE</a>) for building BlackBerry apps, but does anyone know how to configure <a href="http://www.jetbrains.com/idea/index.html" rel="nofollow noreferrer">IntelliJ IDEA</a> to build/debug BlackBerry apps?</p>
<p>RE: Chris' question about what is different... Blackberry applications can be standard MIDP apps or CLDC apps that make use of the Blackberry specific APIs. Most developers tend to take the latter approach, and then using Blackberry's tools is required - especially if you are using some of their secured APIs and have to sign your deployment files for them to run on the devices.</p> <p>A potential answer to the original question would be to use the <a href="http://bb-ant-tools.sourceforge.net/" rel="nofollow noreferrer">Blackberry ANT tools</a> to create an ANT script for building the application and reference that from IntelliJ IDEA. Of course, that's only half the battle and to run/debug the application you'll need to connect the debugger to IDEA as noted by Alexander above. Alternatively, you could code in IDEA and run/debug in the JDE, but that seems less than ideal, to say the least.</p> <p>I use Eclipse with the Blackberry plugin. Also not ideal, since you are forced to use an old (and buggy) version of Eclipse, but at least I'm in one IDE and can step through code running in a simulator.</p> <p>Blackberry JDE integration would be a great IntelliJ plugin project.</p>
<p>Not sure if this will help but here are instructions for <a href="http://www.blackberryforums.com/developer-forum/138210-setup-up-eclipse-blackberry-development.html" rel="nofollow noreferrer">setting up Eclipse</a> for blackberry development.</p> <p>Maybe you can use that information to figure out what changes to need to make in IDEA.</p>
7,594
<p>Is there any way to make Visual Studio word-wrap at 80 characters? I'm using VS2008.</p> <p><a href="https://stackoverflow.com/questions/84209/vertical-line-after-a-certain-amount-characters-in-visual-studio">This post is loosely related.</a></p>
<p>Tools >> Options >> Text Editor >> All Languages >> General >> Select Word Wrap. </p> <p>I dont know if you can select a specific number of columns?</p>
<p>See also <a href="https://stackoverflow.com/a/315531/193017">this answer</a> in order to switch the mode conveniently.</p> <p>Citation:</p> <blockquote> <p>I use this feature often enough that I add a custom button to the command bar.</p> <p>Click on the Add or Remove -&gt; Customize <br>Click on the Commands tab <br>Select Edit|Advanced from the list <br>Find Toggle Word Wrap and drag it onto your bar</p> </blockquote>
29,271
<p>We have a situation where a C# application is working with SQL CE 3.5 . To allow for a legacy program to use some of its features we have produced a C++ dll which uses interop to extract the info that it needs from the C# program. For this to work, the C#-program needs to access the database. Its not a very complex scenario.</p> <p>When trying to deploy with a private install some problems occur though. <strong>There is no problem with the C# program, it can access the database and work with it without any problems.</strong></p> <p><strong>But when trying to access functions in the C#-program through the C++ interop which forces the C#-program to access the database, we get a crash with the exception saying that "...the Provider: System.Data.SqlServerCe.3.5 is not installed".</strong></p> <p>This is obviously because we cannot add a App.config file to the executing program.</p> <p>How can we get around this? Is there another way to fix this? Any other forms of SQL CE 3.5 install methods are out of the question. So we must get this to work.</p> <p>Regards,</p> <p>P</p> <p><strong>Edit:</strong></p> <p>I'm not working against SQL CE directly, but through Linq2SQL. I have tried to add config files to all my dll's, it does not help. It seems to only matter if the executable file have got a app.config.</p> <p>The exception thrown says - The provider System.Data.SqlServerCe.3.5 is not installed.</p> <p>And the latest function to be called according to the stack trace is System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Initialize(...).</p> <p><strong>Edit 2</strong></p> <p>I have added all the files necessery for the deployment to work. As I wrote above, it works if I use the program dll (which uses Linq 2 Sql) through a .net executable with a app.config file that specifies where to look for the SQL CE 3.5 dll. Deployment will <em>not</em> work with only the files, an app.config file is necessary.</p> <p>The problem is that we have to use the dll file through a C++ executable which have no means of telling .net where to look for the Sql Ce 3.5 dll.</p>
<p>add the following files to your application folder:</p> <ul> <li>sqlceca35.dll</li> <li>sqlcecompact35.dll</li> <li>sqlceer35E.dll</li> <li>sqlceme35.dll</li> <li>sqlceoledb35.dll</li> <li>sqlceqp35.dll</li> <li>sqlcese35.dll</li> <li>System.Data.SqlServerCe.dll</li> </ul> <p>then it will work.</p> <p>that is necessary if you have not explicitely installed sql server ce 3.5 on the target machine (which is case for most deployments i think).</p>
<p>You can add a foo.dll.config file and make sure it lives alongside the DLL. You just need to make sure that you have code in your DLL to determine where it lives on disk, and read the configuration from the same location.</p> <p>Good luck!</p>
29,695