instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Are there any tools to transform SVG (XML) data to Canvas friendly input?</p>
<p>No I don't think so. SVG is actually rather different to Canvas. SVG is a vector graphics description language, whereas Canvases are programmatically "drawn" by sets of instructions. Also, Canvas isn't actually vector based at all.</p> <p>Take a look at the <a href="http://www.raphaeljs.com/" rel="nofollow noreferrer">Raphael Javascript Library</a>. Its API will draw SVG/Canvas/VML depending on the capabilities of the browser.</p>
<p>Take a look at XSLT.</p>
25,017
<p>I know this maybe a very basic question but I'm having a bit of a mind blank at the moment. Should I be unit testing this class.</p> <pre><code>public class MapinfoWindowHandle : IWin32Window { IntPtr handle; public MapinfoWindowHandle(IntPtr mapinfoHandle) { this.handle = mapinfoHandle; } #region IWin32Window Members IntPtr IWin32Window.Handle { get { return this.handle; } } #endregion } </code></pre> <p>If I should be what should I be testing for? <bR> I use it like this:</p> <pre><code>IntPtr handle = new IntPtr(100); myform.show(new MapinfoWindowHandle(handle)); </code></pre>
<p>The only thing that I can see is making sure you get out the handle that you put in via your constructor. I know that it's obvious that you implemented it this way, but a test would assure you that it stays this way. I would test this only because you are injecting it via the constructor. If it was just { get; set; } I probably wouldn't.</p> <pre><code> [TestMethod] public void ConstructorTest() { IntPtr handle = new IntPtr(100); MapinfoWindowHandle winHandle = new MapinfoWindowHandle(handle); Assert.AreEqual( handle, ((IWin32Window)winHandle).Handle ); } </code></pre>
<p>The pragmatist in me says no, because the class does "nothing", so there is "nothing" to test. But sure you could still test it, just for documentation purposes, and as a contract for future developers.</p>
45,809
<p>Which is the best way to store a 2D array in c# in order to optimize performance when performing lots of arithmetic on the elements in the array?</p> <p>We have large (approx 1.5G) arrays, which for example we want to multiply with each other element by element. Performance is critical. The context in which this is done is in c#. Is there any smart way of storing the arrays and iterating over them? Could we write these parts in unmanaged C++ and will this really increase performance? The arrays need to be accessible to the rest of the c# program. </p> <p>Currently (in c) the array is stored as a single long vector. We perform calculations on each element in the array and overwrite the old value. The calculations are usually unique for each element in the vector.</p> <p>Timing experiments show that storing and iterating over the data as an array in C# is slower than storing it as a 2D array. I would like to know if there is an even better way of handling the data. The specific arithmetics performed are not relevant for the question.</p>
<p>For best array performance, make sure you're using a single dimension array with lower index of 0.</p> <p>To access the elements of the array as fast as possible, you can use unsafe pointers like so:</p> <pre><code>int[] array = Enumerable.Range(0, 1000).ToArray(); int count = 0; unsafe { fixed (int* pArray = array) { for (int i = 0; i &lt; array.Length; i++) { count += *(pArray + i); } } } </code></pre> <p><strong>EDIT</strong> Drat! Didn't notice you said 2D array. This trick won't work with a multi-dimensional array so I'm not sure how much help it will be. Although you could turn any array into a single-dimension array by doing some arithmetic on the array index. Just depends on if you care about the performance hit in indexing the array or in iterating over the array.</p>
<p>Do you iterate the matrix by row or by colum or both? Do you always access nearby elements or do you do random accesses on the matrix.</p> <p>If there is some locality in your accesses but you're not accessing it sequential (typical in matrix multiplication for example) then you can get a <em>huge</em> performance difference by storing your matrix in a more cache-friendly way.</p> <p>A pretty easy way to do that is to write a little access function to turn your row/colum indices into an index and work on a one dimensional matrix, the cache-friendy way.</p> <p>The function should group nearby coordinates into nearby indices. The morton-order can be used if you work on power of two sizes. For non-power sizes you can often bring just the lowest 4 bits into morton order and use normal index-arithmetic for the upper bits. You'll still get a significant speed-up, even if the coordinate to index conversion looks seems to be a costly operation.</p> <p><a href="http://en.wikipedia.org/wiki/Z-order_(curve)" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Z-order_(curve)</a> &lt;-- sorry, can't link that SO does not like URL's with a dash in it. You have to cut'n'paste.</p> <p>A speed up of factor 10 and more are realistic btw. It depends on the algorithm you ron over your matrices though.</p>
13,620
<p>I've searched for this a little but I have not gotten a particularly straight answer. In C (and I guess C++), how do you determine what comes after the % when using <code>printf</code>?. For example:</p> <pre><code>double radius = 1.0; double area = 0.0; area = calculateArea( radius ); printf( "%10.1f %10.2\n", radius, area ); </code></pre> <p>I took this example straight from a book that I have on the C language. This does not make sense to me at all. Where do you come up with <code>10.1f</code> and <code>10.2f</code>? Could someone please explain this?</p>
<p><a href="http://en.wikipedia.org/wiki/Printf#printf_format_placeholders" rel="noreferrer">http://en.wikipedia.org/wiki/Printf#printf_format_placeholders</a> is Wikipedia's reference for format placeholders in printf. <a href="http://www.cplusplus.com/reference/clibrary/cstdio/printf.html" rel="noreferrer">http://www.cplusplus.com/reference/clibrary/cstdio/printf.html</a> is also helpful</p> <p>Basically in a simple form it's %[width].[precision][type]. Width allows you to make sure that the variable which is being printed is at least a certain length (useful for tables etc). Precision allows you to specify the precision a number is printed to (eg. decimal places etc) and the informs C/C++ what the variable you've given it is (character, integer, double etc).</p> <p>Hope this helps</p> <p><strong>UPDATE:</strong></p> <p>To clarify using your examples:</p> <pre><code>printf( "%10.1f %10.2\n", radius, area ); </code></pre> <p>%10.1f (referring to the first argument: radius) means make it 10 characters long (ie. pad with spaces), and print it as a float with one decimal place.</p> <p>%10.2 (referring to the second argument: area) means make it 10 character long (as above) and print with two decimal places.</p>
<p>One issue that hasn't been raised by others is whether <strong>double</strong> is the same as a <strong>float</strong>. On some systems a different format specifier was needed for a double compared to a float. Not least because the parameters passed could be of different sizes. <PRE> %f - float %lf - double %g - double </PRE></p>
3,860
<p>MySQL offers many ways (on Windows) to connect to it, those are:</p> <ul> <li>Shared memory</li> <li>Named pipes</li> <li>TCP/IP</li> </ul> <p>My question is, if MySQL will be run on the same machine of the web server, then which method is best for security and performance?</p> <p>P.S. This is a one web server scenario, no web farm.</p> <p>Thanks</p>
<p>In terms of performance if both are running on the same machine then shared memory is the better option as it wont run into issues with firewall software that may be on the machine or installed at a later date.</p> <p>However if in the future you need to seperate the web server and database due to upsizing, you will need to make changes to support this.</p> <p>Therefore in the long run the better option is to go with TCP/IP as this will allow the servers to be seperated with the minimum of heartache.</p>
<p>TCP/IP in all cases.</p>
34,206
<p>I am new to 3D printing but have been in CNC Machining for a few years. I have a part I am trying to print that is a cylinder 1.000 in. in diameter and has a .200 in overhang starting at 1.300 in. In other words I am printing a 1.300 in. cylinder that is 1.500 in. tall that at 1.300 in. its diameter increases by .200 in. </p> <p>When I first printed the part the overhang had sunk or fallen out. Not by much and is still usable but made a crappy finish. What would I need to do in order to have the overhang not drop as the base layer extended outward .200 in. at 1.300 in.?</p> <p>I tried slowing the feed rate but that was worse. I also lowered the temp to 195&nbsp;°C.</p> <p>I am using a Monoprice Select Mini running at 200&nbsp;°C and a 1.0 Speed (Not really sure what that feed rate is in terms of mm/s). Based on what I've seen so far I would increase the speed and keep the temp at 200&nbsp;°C.</p> <p><a href="https://i.stack.imgur.com/hif1O.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hif1O.jpg" alt="enter image description here"></a></p> <p>Any suggestions, I hope I have explained my problem well enough.</p>
<p>The world of 3D Printers usually uses the metric system, especially in nozzle sizes. 0.2 inches are therefore better referred to as 5 mm, which is a considerable amount: that's 11 to 13 perimeters from a 0.4 mm nozzle, depending on extrusion width (0.46 and 0.4 mm respectively). Furthermore, the bore of the item isn't supported either, it is bridging.</p> <p>To print overhangs and bridging without sagging, one should activate the generation of support material in the slicer.</p> <p>Generally speaking, PLA (judging from the print temperature) doesn't need to be printed with a raft and would be better served with a <code>brim</code> for bed adhesion, unless you have a perforated bed. If you have to print in the shown orientation, then you should activate support generation in your slicer.</p> <p>For this part, however, there is a better solution: it is of very simple geometry and it doesn't have to be printed as shown but equally could be printed "upside-down" by being rotated around the X-Axis by 180° in the slicer. This has two benefits: it removes all unsupported overhangs an avoids support structure, making the wasted material pretty much nonexistent.</p> <p>I strongly recommend taking a look at my <a href="https://3dprinting.stackexchange.com/questions/6726/what-special-considerations-must-be-taken-when-designing-parts-for-3d-printing/6830#6830">3D Design Primer</a> and the excellent question on <a href="https://3dprinting.stackexchange.com/questions/10636/how-to-decide-print-orientation">How to decide print orientation?</a> and then delve into further reading: </p> <ul> <li><a href="https://3dprinting.stackexchange.com/questions/250/how-to-print-an-overhanging-arc">How to print an overhanging arc</a></li> <li><a href="https://3dprinting.stackexchange.com/questions/686/how-can-i-improve-the-overhang-angles-my-printer-can-successfully-print">How can I improve the overhang angles my printer can successfully print?</a></li> <li><a href="https://3dprinting.stackexchange.com/questions/5529/is-there-any-setting-that-could-allow-me-to-print-this-overhang-without-support">Is there any setting that could allow me to print this overhang without support?</a></li> </ul>
<p>It appears that your part could be printable upside down. If possible, I'd highly recommend this, as it mostly avoids supports all together.</p>
1,483
<p>A requirement for an ASP.Net 2.0 project I'm working on limits a certain field to a max of 10 words (not characters). I'm currently using a CustomValidator control with the following ServerValidate method:</p> <pre><code>Protected Sub TenWordsTextBoxValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TenWordsTextBoxValidator.ServerValidate '' 10 words args.IsValid = args.Value.Split(" ").Length &lt;= 10 End Sub </code></pre> <p>Does anyone have a more thorough/accurate method of getting a word count?</p>
<p>You can use one of the builtin validators with a regex that counts the words.</p> <p>I'm a little rusty with regex so go easy on me:</p> <pre><code>(\b.*\b){0,10} </code></pre>
<p>I voted for mharen's answer, and commented on it as well, but since the comments are hidden by default let me explain it again:</p> <p>The reason you would want to use the regex validator rather than the custom validator is that the regex validator will also automatically validate the regex client-side using javascript, if it's available. If they pass validation it's no big deal, but every time someone fails the client-side validation you save your server from doing a postback.</p>
7,583
<pre><code>&lt;div id="myDiv"&gt; &lt;a&gt;...&lt;/a&gt; &lt;a&gt;...&lt;/a&gt; &lt;a&gt;...&lt;/a&gt; &lt;a&gt;...&lt;/a&gt; &lt;a&gt;...&lt;/a&gt; &lt;a&gt;...&lt;/a&gt; &lt;/div&gt; </code></pre> <p>If you wanted to select the 2nd, 3rd and 4th <code>a</code> tags in the above example, how would you do that? The only thing I can think of is:</p> <pre><code>$("#myDiv a:eq(1), #myDiv a:eq(2), #myDiv a:eq(3)") </code></pre> <p>But that doesn't look to be very efficient or pretty. I guess you could also select ALL the <code>a</code>s and then do run <code>.each</code> over them, but that could get very inefficient if there were a lot more <code>a</code>s.</p>
<p>jQuery <a href="http://docs.jquery.com/Traversing/slice" rel="noreferrer">slice()</a> function taking indexes of the first and the last needed elements selects a subset of the matched elements. Note what it doesn't include last element itself. </p> <p>In your particular case you should use</p> <pre><code>$("#myDiv a").slice(1, 4) </code></pre>
<p>You should be able to do this by extracting a slice of the array thus. It's the line</p> <pre><code>$("div[id='myDiv'] &gt; a").slice(1,4).css("background","yellow"); </code></pre> <p>that you're interested in. It will affect the 2nd, 3rd and 4th elements.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="jquery-1.2.6.pack.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ $("a").click(function(event){ $("div[id='myDiv'] &gt; a").slice(1,4).css("background","yellow"); event.preventDefault(); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="myDiv"&gt; &lt;a&gt;1&lt;/a&gt; &lt;a&gt;2&lt;/a&gt; &lt;a&gt;3&lt;/a&gt; &lt;a&gt;4&lt;/a&gt; &lt;a&gt;5&lt;/a&gt; &lt;a&gt;6&lt;/a&gt; &lt;/div&gt; &lt;hr&gt; &lt;a href="" &gt;Click here&lt;/a&gt; &lt;hr&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
22,497
<p>Should Singleton objects that don't use instance/reference counters be considered memory leaks in C++?</p> <p>Without a counter that calls for explicit deletion of the singleton instance when the count is zero, how does the object get deleted? Is it cleaned up by the OS when the application is terminated? What if that Singleton had allocated memory on the heap?</p> <p>In a nutshell, do I have to call a Singelton's destructor or can I rely on it getting cleaned up when the application terminates?</p>
<p>You can rely on it being cleaned up by the operating system. </p> <p>That said, if you are in a garbage collected language with finalizers rather than destructors you may want to have a graceful shutdown procedure that can cleanly shutdown your singletons directly so they can free any critical resources in case there are using system resources that won't be correctly cleaned up by merely ending the application. This is because finalizers run on a sort of 'best effort' basis in most languages. On the other hand there a very very few resources that need this sort of reliability. file handles, memory, etc. all go back to the OS cleanly regardless.</p> <p>If you are using a singleton that is lazily allocated (i.e. with a triple-check lock idiom) in a language like c++ with real destructors rather than finalizers, then you cannot rely on its destructor being invoked during program shutdown. If you are using a single static instance then the destructor will run after main completes at some point.</p> <p>Regardless, when the process ends, all memory returns to the operating system.</p>
<p>Any heap memory allocated by your process and not freed (deleted) will be reclaimed by the OS. If you're using the most common implementation of the singleton, which uses static variables, this would be cleaned up upon your application's termination as well.</p> <p>*This does not mean that you should go around new-ing pointers and never cleaning them up though.</p>
34,489
<p>If I make two iPhone applications, how can/should I share custom data (not contacts and stuff like that) among them?</p> <p>Thanks!</p>
<p>There are two different ways you might go about this.</p> <p>1) The data you need to share is non-persistent. In other words you need to launch one application with a piece of data that it can do something with. In this case you would register a special URL scheme per application.</p> <p>You can find out more information about URL schemes via Craig Hockenberry in his <a href="http://furbo.org/2008/10/01/redacted/" rel="noreferrer">[redacted] blog post</a>.</p> <p>2) The data you need to share is persistent. In other words you need something like a data file that both applications can read and write too. As far as I know there isn't a safe way to do this other than storing your data on a remote server. If you need the data accessible without a data connection then you would need to figure out a way to sync data between the individual apps and the remote server.</p>
<p>Dan Grisby's <a href="http://www.mobileorchard.com/podcast-warm-clothed-and-fed-developer-run-iphone-businesses/" rel="nofollow noreferrer">most recent mobile orchard podcast</a> hypothesizes that you might also use custom named clipboards to share information between apps. I realize this is an older post, but I thought I would point this out because it's high on google results. :)</p> <p>(Documentation also suggests that <code>NSUserDefaults</code> might be useful here, but I've <a href="http://arstechnica.com/apple/news/2009/03/iphone-dev-suite-preferences-fail-to-deliver-on-iphone.ars" rel="nofollow noreferrer">read elsewhere</a> that that's actually not the case.)</p>
27,168
<p>I am trying to add the line</p> <blockquote> <p>G4 P4000 G1 F4000 E-50</p> </blockquote> <p>to pause and retract the print in order for the printed line to dry (printing in mid air vertically). Does the above code work or should i skip lines or does it not matter at all?</p> <blockquote> <p>G4 P4000<br> G1 F4000 E-50</p> </blockquote> <p>Would the following line do the exact same thing?</p> <blockquote> <p>G4 P5000 E-50</p> </blockquote>
<p>Yes, G-code is read line by line. G-code is a numerical control programming language. It basically instructs the machine sequentially line by line to do a specific task. The printer than executes the lines one by one until it reaches the end.</p> <p>If you instruct the printer to wait (<code>G4</code> dwell), it will do the wait/dwell first and than will execute the next command to retract the filament. As such, your examples will not work if you want to retract the filament during the pause, you reversed the process if you want to achieve that.</p> <p>To add a pause (simple) for e.g. filament changing, you should instruct the head to go to a certain position, extract the filament, and now insert the pause/dwell command. Give yourself enough time to insert and prime the nozzle and go back to the last location to continue printing. </p> <p>You could insert something like (e.g. in between layer change, before <code>G1 Zx.xx</code>):</p> <pre><code>... G1 X0 Y0 F2000 ; Relocate the print head G1 F4000 E-50 ; Retract filament G4 P40000 ; Wait for 40 seconds G92 E50 ; The new filament should continue at this value ... G1 Zx.xx </code></pre> <p>Depending on what happens after <code>G1 Zx.xx</code>, you may need to set the head back to the location prior to where it was before <code>G1 X0 Y0 F2000</code>.</p> <p>Do note that there are pausing scripts/plugins available for e.g. Ultimaker Cura, and there is also a filament changing command <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause" rel="nofollow noreferrer"><code>M600</code></a> that can be enabled for certain firmware (if this is your ultimate goal).</p> <p>Using a post processing plugin of Ultimaker Cura, a pausing script looks like:</p> <pre> ... G0 X137.692 Y105 ;TIME_ELAPSED:707.873599 ;TYPE:CUSTOM;added code by post processing ;script: PauseAtHeight.py ;current z: 5 ;current height: 5.0 M83 G1 F300 Z6 G1 F9000 X190 Y190 G1 F300 Z15 M104 S0; standby temperature M0;Do the actual pause M109 S200; resume temperature G1 F300 Z6 G1 F9000 X133.423 Y105 G1 F9000 M82 G92 E911.50045 ;LAYER:24 G0 X137.692 Y105 Z5 ... </pre> <p>Note that <code>G0</code> and <code>G1</code> are <em>"move to"</em> location instructions (albeit through a different way, fast move and linear move respectively). If you look closely, you see that after the pause, the printer returns to the X-Y position where it left prior to the pause (<code>X137.692 Y105</code>).</p> <hr> <p><em>Side note:<br> Some firmware flavors allow <a href="https://reprap.org/wiki/G-code#Buffering" rel="nofollow noreferrer">buffering</a>, but each statement is executed sequentially.</em></p>
<p>This needs to be on two lines like in your second example:</p> <blockquote> <p>G4 P4000<br> G1 F4000 E-50</p> </blockquote> <p>See the RepRap Gcode Wiki for more info. <a href="https://reprap.org/wiki/G-code" rel="nofollow noreferrer">https://reprap.org/wiki/G-code</a></p> <p>EDIT: if you actually want to retract and THEN pause, reverse it:</p> <blockquote> <p>G1 F4000 E-50<br> G4 P4000<br></p> </blockquote>
1,089
<p>When I do a file search on eclipse it includes the <code>.svn</code> directories by default. I tried excluding them from the build path but they still appear on file search results.</p>
<p>Spaceman is right. With Helios, choose <code>Project -&gt; Properties -&gt; Resource -&gt; Resource Filters</code> and then add an <code>exclude</code> filter for type "Folder" with name <code>.svn</code>.</p>
<p>Click on the drop-down triangle in the top-right corner of the Navigator and choose "Filters..".</p> <p>By default Eclipse only offers you "<em>.class" and ".</em>".</p> <p>If you choose ".*" you'll hide .svn files. Obviously all other .something files will also be hidden.</p>
6,334
<p><strong>(Scroll down to bottom of post to find solution.)</strong></p> <p>Got a asp.net page which contains a Datalist. Inside this datalist, there is a template containing a dropdownlist and each time the datalist is filled with an item, a ItemCreatedCommand is called. The itemCreatedCommand is responsible for databinding the dropdownlist. </p> <p>I think the problem lies here, that I'm using ItemCreatedCommand to populate it - but the strange things is that if I choose the color "green", the page will autopostback, and I will see that the dropdown is still on the color green, but when trying to use it's SelectedIndex, I always get 0...</p> <pre><code>protected void DataListProducts_ItemCreatedCommand(object source, DataListItemEventArgs e) var itemId = (String)DataListProducts.DataKeys[e.Item.ItemIndex]; var item = itemBLL.GetFullItem(itemId); var DropDownListColor = (DropDownList)e.Item.FindControl("DropDownListColor"); //Also tried with : //if(!isPostBack) { DropDownListColor.DataSource = item.ColorList; DropDownList.Color.Databind(); // } End !isPostBack) Label1.test = DropDownListColor.SelectedIndex.toString(); // &lt;- THIS IS ALWAYS 0! *grr* </code></pre> <p>I've narrowed down the code a bit for viewing, but still you can see what I'm trying to do :) The reason for why I'm doing this, and not declaring the datasource for the colors directly i aspx-page, is that I need to run a test if(showColors), but I do not want to clutter up the html-page with code that I feel should be in the code behind-file. </p> <p>EDIT: After trying to alter SelectedIndexChange - I'm having a "logical" confusion in my head now - how am I to alter elements inside the datalist? Since, as far as I know - I do not have any way to check which of the items in the datalist this particular dropdownlist belongs to... Or? I'm going to try out a few ways and see what I end up with ;) But do please post your thoughts on this question :) </p> <p><strong>SOLUTION:</strong> </p> <p>Either bubble the event to ItemCommand, or Handle the event, get the senders parent(which is a datalistItem and manipulate elements in there. </p> <pre><code> protected void DropDownListColor_SelectedIndexChanged(object sender, EventArgs e) { DropDownList dropDownListColor = (DropDownList)sender; DataListItem dataListItem = (DataListItem)dropDownListColor.Parent; var item = items[dataListItem.ItemIndex]; var color = item.ItemColor[dropDownListColor.SelectedIndex]; var LabelPrice = (Label)dataListItem.FindControl("LabelPrice"); LabelPrice.Text = color.Price; } </code></pre>
<p>When the DataList is data-bound, the AutoPostBack has not been handled yet, i.e. the values in the ItemCreated event are still the original values.</p> <p>You need to handle the SelectedIndexChange event of the dropdown control.</p>
<p>Regarding your 2nd question:</p> <p>I suggest you remove the AutoPostBack from the dropdown, add an "Update" button, and update the data in the button Click event.</p> <p>The button can hold Command and CommandArgument values, so it's easy to associate with a database record.</p>
40,306
<p>(Note: I realize this is close to <a href="https://stackoverflow.com/questions/186392/how-do-you-document-your-database-structure">How do you document your database structure?</a> , but I don't think it's identical.)</p> <p>I've started work at a place with a database with literally hundreds of tables and views, all with cryptic names with very few vowels, and no documentation. They also don't allow gratuitous changes to the database schema, nor can I touch any database except the test one on my own machine (which gets blown away and recreated regularly), so I can't add comments that would help anybody.</p> <p>I tried using &quot;Toad&quot; to create an ER diagram, but after leaving it running for 48 hours straight it still hadn't produced anything visible and I needed my computer back. I was talking to some other recent hires and we all suggested that whenever we've puzzled out what a particular table or what some of its columns means, we should update it in the developers wiki.</p> <p>So what's a good way to do this? Just list tables/views and their columns and fill them in as we go? The basic tools I've got to hand are Toad, Oracle's &quot;SQL Developer&quot;, MS Office, and Visio.</p>
<p>In my experience, ER (or UML) diagrams aren't the most useful artifact - with a large number of tables, diagrams (especially reverse engineered ones) are often a big convoluted mess that nobody learns anything from.</p> <p>For my money, some good human-readable documentation (perhaps supplemented with diagrams of smaller portions of the system) will give you the most mileage. This will include, for each table:</p> <ul> <li>Descriptions of what the table means and how it's functionally used (in the UI, etc.)</li> <li>Descriptions of what each attribute means, if it isn't obvious</li> <li>Explanations of the relationships (foreign keys) from this table to others, and vice-versa</li> <li>Explanations of additional constraints and / or triggers</li> <li>Additional explanation of major views &amp; procs that touch the table, if they're not well documented already</li> </ul> <p>With all of the above, don't document for the sake of documenting - documentation that restates the obvious just gets in people's way. Instead, focus on the stuff that confused you at first, and spend a few minutes writing really clear, concise explanations. That'll help you think it through, and it'll <em>massively</em> help other developers who run into these tables for the first time.</p> <p>As others have mentioned, there are a wide variety of tools to help you manage this, like <a href="http://www.sparxsystems.com.au/" rel="noreferrer">Enterprise Architect</a>, <a href="http://www.red-gate.com/products/SQL_Doc/index.htm" rel="noreferrer">Red Gate SQL Doc</a>, and the built-in tools from various vendors. But while tool support is helpful (and even critical, in bigger databases), doing the hard work of <em>understanding</em> and <em>explaining</em> the conceptual model of the database is the real win. From that perspective, you can even do it in a text file (though doing it in Wiki form would allow several people to collaborate on adding to that documentation incrementally - so, every time someone figures out something, they can add it to the growing body of documentation instantly).</p>
<p>Well, a picture tells a thousand words so I would recommend creating ER diagrams where you can view the relationship between tables at a glance, something that is hard to do with a text-only description.</p> <p>You don't have to do the whole database in one diagram, break it up into sections. We use Visual Paradigm at work but EA is a good alternative as is ERWIN, and no doubt there are lots of others that are just as good.</p> <p>If you have the patience, then using html to document the tables and columns makes your documentation easier to access.</p>
48,225
<p>I am new to RESTful stuff. But, I want to use it in my rails app. When I add this to my routes.rb <code>map.resources :notes</code> I get routes to these methods created:</p> <ul> <li>index</li> <li>create</li> <li>new</li> <li>edit</li> <li>show</li> <li>update</li> <li>destroy</li> </ul> <p>What I am wondering is what is the difference between edit/update and create/new? Is there any standard definitions of how these method pairs vary and what each one does?</p>
<p>When you use the scaffold generator in Rails 2 <code>create</code> is the action called when the form from the <code>new</code> action is submitted. Likewise, <code>update</code> is the action called when the form from the <code>edit</code> action is submitted.</p> <p>As far as I know, you can blow that away and define them to do whatever you want depending on what <code>create/new/edit/update</code> means to your application.</p>
<p>When you use the scaffold generator in Rails 2 <code>create</code> is the action called when the form from the <code>new</code> action is submitted. Likewise, <code>update</code> is the action called when the form from the <code>edit</code> action is submitted.</p> <p>As far as I know, you can blow that away and define them to do whatever you want depending on what <code>create/new/edit/update</code> means to your application.</p>
37,021
<p>I am wrapping existing C++ code from a <strong>BSD</strong> project in our own custom wrapper and I want to integrate it to our code with as few changes as possible. This code uses <code>fprintf</code> to print to <strong>stderr</strong> in order to log / report errors.</p> <p>I want to redirect this to an alternative place within the same process. On <strong>Unix</strong> I have done this with a <code>socketpair</code> and a <code>thread</code>: one end of the socket is where I send <strong>stderr</strong> (via a call to <code>dup2</code>) and the other end is monitored in a thread, where I can then process the output.</p> <p>This does not work on <strong>Windows</strong> though because a socket is not the same as a file handle.</p> <p>All documents I have found on the web show how to redirect output from a child process, which is not what I want. How can I redirect <strong>stderr</strong> within the same process getting a callback of some sort when output is written? (and before you say so, I've tried <code>SetStdHandle</code> but cannot find any way to make this work)...</p>
<p>You can use a similar technique on Windows, you just need to use different words for the same concepts. :) This article: <a href="http://msdn.microsoft.com/en-us/library/ms682499.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms682499.aspx</a> uses a win32 pipe to handle I/O from another process, you just have to do the same thing with threads within the same process. Of course, in your case all output to stderr from anywhere in the process will be redirected to your consumer.</p> <p>Actually, other pieces of the puzzle you may need are <a href="http://msdn.microsoft.com/en-us/library/dye30d82(VS.80).aspx" rel="noreferrer">_fdopen</a> and <a href="http://msdn.microsoft.com/en-us/library/bdts1c9x(VS.71).aspx" rel="noreferrer">_open_osfhandle</a>. In fact, here's a related example from some <a href="http://hewgill.com/pilot/copilot/" rel="noreferrer">code</a> I released years ago:</p> <pre><code>DWORD CALLBACK DoDebugThread(void *) { AllocConsole(); SetConsoleTitle("Copilot Debugger"); // The following is a really disgusting hack to make stdin and stdout attach // to the newly created console using the MSVC++ libraries. I hope other // operating systems don't need this kind of kludge.. :) stdout-&gt;_file = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT); stdin-&gt;_file = _open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT); debug(); stdout-&gt;_file = -1; stdin-&gt;_file = -1; FreeConsole(); CPU_run(); return 0; } </code></pre> <p>In this case, the main process was a GUI process which doesn't start with stdio handles at all. It opens a console, then shoves the right handles into stdout and stdin so the debug() function (which was designed as a stdio interactive function) can interact with the newly created console. You should be able to open some pipes and do the same sort of thing to redirect stderr.</p>
<p>You mention that you don't want to use a named pipe for internal use; it's probably worth poining out that the documentation for <a href="http://msdn.microsoft.com/en-us/library/aa365152(VS.85).aspx" rel="nofollow noreferrer">CreatePipe()</a> states, <em>"Anonymous pipes are implemented using a named pipe with a unique name. Therefore, you can often pass a handle to an anonymous pipe to a function that requires a handle to a named pipe."</em> So, I suggest that you just write a function that creates a similar pipe with the correct settings for async reading. I tend to use a GUID as a string (generated using <code>CoCreateGUID()</code> and <code>StringFromIID()</code>) to give me a unique name and then create the server and client ends of the named pipe with the correct settings for overlapped I/O (more details on this, and code, here: <a href="http://www.lenholgate.com/blog/2008/02/process-management-using-jobs-on-windows.html" rel="nofollow noreferrer">http://www.lenholgate.com/blog/2008/02/process-management-using-jobs-on-windows.html</a>).</p> <p>Once I have that I wire up some code that I have to read a file using overlapped I/O with an I/O Completion Port and, well, then I just get async notifications of the data as it arrives... However, I've got a fair amount of well tested library code in there that makes it all happen... </p> <p>It's probably possible to set up the named pipe and then just do an overlapped read with an event in your <code>OVERLAPPED</code> structure and check the event to see if data was available... I don't have any code available that does that though.</p>
2,924
<p>I want to skeletize the surface mesh. For that I need to export .STL from Solidworks and then convert that into .OFF file to be able to use it in CGAL library for skeletonzation. How can I do this?</p>
<p>One aspect of having this level of control with 3d printing of a model is the removal of the need for supports and the attendant post-processing. In the case of the model shown in the video, some effects are created by printing the continents in a conformal manner that would otherwise be impossible with conventional 3d printing. Cosmetically, the results of the "5d" printer are superior in this example.</p> <p>There would also be some structural benefit for models with high organic content, that is curves and bulges, as opposed to orthogonal designs. Even with orthogonal designs, one can achieve stronger parts with cross-layered plastic in all directions, rather than being limited by x and y filament layers.</p> <p>I see on the web site that one can exchange tool heads as well. One could print a 3d model, layering the filament on all the surfaces, then use a tool head change to a milling bit and smooth the surface under CAD control. Alternatively, one could use foam or wood and mill a model shape to be covered with a 3d printed material.</p> <p>Considering the relative novelty of this product, it's likely that many aspects of the creative utility have yet to be discovered!</p>
<p>Slicing prints for printing in 5 Axis is not going to be simple with the current software. If you look at the web site for the 5AxisMaker you can see they are using Algorithmic modeling software (Grasshopper). You would probably need to buy this as well and then spend a decent amount of time learning how to use this software as well if you were going to try and take advantage of the 5th Axis for 3D printing. </p> <p>I have only seen Grasshopper used for 3D printing and 5 Axis used in research papers. </p>
429
<p>I am fairly comfortable with standalone Java app development, but will soon be working on a project using a Java EE application server.</p> <p>Does anyone know of a straightforward how-to tutorial to getting a hello-world type application working in an application server? I'm (perhaps naievly) assuming that the overall approach is similar between different frameworks, so I'm more interested in finding out the approach rather than getting bogged down in differences between the different frameworks.</p> <p>If you are not aware of a good guide, then could you post bullet-point type steps to getting a hello-world running?, i.e.</p> <ol> <li>Download XX</li> <li>Write some code to do YY</li> <li>Change file ZZ</li> <li>Other steps...</li> </ol> <p>Note: Just because I have a windows machine at home, I would prefer to run if this could be run on windows, but in the interest of a better answer, linux/mac based implementations are welcome.</p>
<p>I would choose JBoss AS or GlassFish for a start. However I'm not sure what you mean by Java EE "Hello World". If you just want to deploy some JSP you could use this tutorial (for JBoss):</p> <p><a href="http://www.centerkey.com/jboss/" rel="nofollow noreferrer">http://www.centerkey.com/jboss/</a></p> <p>If you want to get further and do the EJB stack and/or deploy an ear-file, you could read the very good JBoss documentation:</p> <p><a href="http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.3/doc/Installation_Guide/html/index.html" rel="nofollow noreferrer">Installation Guide</a></p> <p><a href="http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.3/doc/Getting_Started/html/index.html" rel="nofollow noreferrer">Getting started</a></p> <p><a href="http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.3/doc/Server_Configuration_Guide/html/index.html" rel="nofollow noreferrer">Configuration Guide</a></p> <p>In general you could also just do the basic installation and change or try the pre-installed example applications. </p> <p>I currently have JBoss installed (on windows). I develop with Eclipse and use the Java EE server integration to hot deploy or debug my code. After you get your first code running you realy should have a look at the ide integration since it makes development/deploy roundtrips so much faster.</p>
<p>As JeroenWyseur puts it, Java EE is a fairly big space. In addition to what he said, you should try to get more details of what exactly you'll be doing: servelts &amp; co, EJB (entity, session, message beans?) and try to get familiar with that. </p> <p>It should be clear for you that your code runs in a managed environment, which imposes a lot of constraints. in order to make sure you understand what happens you should get familiar with the concept of deployment. Then, if you do EJBs, transaction management is important too. If you don't understand exactly what happens when a bean or a servlet is deployed, how transactions are managed, how beans are invoked, you're going to have a hard time.</p> <p>A book that helped me a lot back in the time is Mastering EJB, by Ed Roman. </p> <p>Also, getting familiar with RMI will help you understand EJBs.</p>
11,636
<p>how good to use 3 point technique for risk assessment.</p>
<p>Is this what you mean? <a href="http://www.aof.mod.uk/aofcontent/tactical/risk/content/tpe.htm?zoom_highlight=simulation" rel="nofollow noreferrer">http://www.aof.mod.uk/aofcontent/tactical/risk/content/tpe.htm?zoom_highlight=simulation</a></p> <p>If so, it looks like that site's a pretty good overview and analysis.</p>
<p>Nice. Also, check out the ACM's <a href="http://www.acmqueue.com/figures/issue019/tiwana1.gif" rel="nofollow noreferrer">one minute risk assessment tool</a> which specifies 6 risk factors. Here is an <a href="http://www.dynamicalsoftware.com/cgi-bin/ViewBlogEntry.pl?id=9" rel="nofollow noreferrer">introduction</a> to that article.</p>
37,278
<p>Is there a way to restrict a specific SQL 2005 login on a Microsoft SQL Server 2005, standard version (sql is in mixed mode) to specific IP addresses, while other logins, Windows authenticated ones, are unaffected?</p>
<p>Yes, you can do this. You'll need to write a logon trigger as described here:</p> <p><a href="http://technet.microsoft.com/en-us/library/bb326598.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/bb326598.aspx</a></p> <p>I futzed around with it for the last fifteen minutes and had limited success, but maybe there's somebody else on here who's done a DDL logon trigger filtering by IP address that can show the source code.</p>
<p>Why do you need to restrict by IP address? If all your users are authenticated, just set up group permissions on SQL Server, and allow or deny the groups you want.</p> <p>If the problem is various users using applications with the same SQL login (you mentioned you're using mixed-mode), then the question is why do you want to allow some users using the applications to access SQL Server, and not allow others? Implement the security in the applications, don't bounce them at the database level.</p>
33,816
<p>My VPS provider (Slicehost) doesn't provide an SMTP server. I use Google Apps to send and receive mail for my domains, but I want to be able to programmatically send e-mail.</p> <p>I've been Googling this issue on and off for many months, and I just can't seem to get a clear picture of what I need to do. Do I just need an MTA like postfix? Do I configure it as a "satellite", or an "internet" site? Do I need to make any DNS changes? If I want to programmatically receive e-mail someday, are there any configuration options I should be careful about tinkering with? Also, if my VPS host <strong>did</strong> provide an SMTP server, what <em>wouldn't</em> I need to do, that I'm doing now?</p> <p>Thank you!</p> <p><strong>Edit</strong>: A quick synopsis of my findings:</p> <ul> <li>Update <code>/etc/hosts</code> and <code>/etc/hostname</code> to reflect the FQDN (for example, <code>mail.domain.com</code> or <code>sub.domain.com</code> instead of <code>slicename</code>) <ul> <li>Reboot and verify with <code>hostname -f</code></li> </ul></li> <li>Set up reverse DNS (which is owned by whoever owns the IP pool) to point at the same FQDN <ul> <li>Check that the RDNS has propogated with <code>dig -x server.ip.address</code></li> </ul></li> <li><code>sudo aptitude install postfix telnet mailx</code> <ul> <li>Use <strong>internet site</strong> setting</li> <li>Set FQDN to whatever was chosen above</li> </ul></li> <li>Test with <code>mail whateveryouremailis@gmail.com</code></li> </ul>
<p>Have you looked <a href="http://articles.slicehost.com/search?q=email" rel="nofollow noreferrer">here</a>, seems to me that there is plenty of information to get started. I found <a href="http://articles.slicehost.com/2008/9/2/mail-server-slice-setup" rel="nofollow noreferrer">mail-server-slice-setup</a> to be quite informative.</p>
<p>Just install something like postfix as "internet site" and you'll be able to send mails directly from your VPS</p> <p>it should work with default settings but it would be recommended to also read a few docs/how-to's to secure it properly </p>
23,913
<p>This problem started technically just before a major move but I had hoped it was a &quot;one off&quot; issue... I started up my trusty Ender 3 today to find it may have actually gotten worse and I'm not entirely sure what the solution is. I was printing a replica of a weapon from a game and I noticed at one point through the print I had a rather extreme X layer shift now today after finally getting the printer setup I've come to find the problem may have actually gotten worse, additionally I'm having a strange gap issue on the top most layers of my prints and strange waving patterns. Now I should note my printer is printing within an enclosure and its temperatures have been adjusted for it but this is rather extreme.<a href="https://i.stack.imgur.com/SSGmx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SSGmx.jpg" alt="major layer shift and waving" /></a></p> <p><a href="https://i.stack.imgur.com/8Ru7M.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Ru7M.jpg" alt="extreme gaps in print" /></a></p>
<p>Same G-code slice? The main cause of warping is temperature. If this is kept as a control variable and you have these results, it may be because of a different temperature the filament requires. Check the filament specs and adjust the bed/nozzle temperature to make the temperature difference smaller.</p> <p>Edit: Another reason it might be needing different temperatures is because of absorbing moisture.</p>
<p>Problem was displaced by a factory reset of the 3D printer FlashForge Adventurer 3.</p> <p><a href="https://i.stack.imgur.com/jxS9X.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jxS9X.jpg" alt="Photo of two versions" /></a></p> <p>Right: white PLA only, left: transparent PLA bottom layers plus white PLA above. View of the bottom sides. No difference of print bed adhesion now.</p> <p>The reason of the problem was not found, but print bed adhesion is good after the factory reset for both white and transparent PLA.</p>
2,048
<p>I'm looking for an Access 2007 equivalent to SQL Server's COALESCE function.</p> <p>In SQL Server you could do something like:</p> <p><strong>Person</strong></p> <pre><code>John Steve Richard </code></pre> <p><strong>SQL</strong></p> <pre><code>DECLARE @PersonList nvarchar(1024) SELECT @PersonList = COALESCE(@PersonList + ',','') + Person FROM PersonTable PRINT @PersonList </code></pre> <p>Which produces: John, Steve, Richard</p> <p>I want to do the same but in Access 2007.</p> <p>Does anyone know how to combine rows like this in Access 2007?</p>
<p>Here is a sample User Defined Function (UDF) and possible usage.</p> <p>Function:</p> <pre><code>Function Coalsce(strSQL As String, strDelim, ParamArray NameList() As Variant) Dim db As Database Dim rs As DAO.Recordset Dim strList As String Set db = CurrentDb If strSQL &lt;&gt; "" Then Set rs = db.OpenRecordset(strSQL) Do While Not rs.EOF strList = strList &amp; strDelim &amp; rs.Fields(0) rs.MoveNext Loop strList = Mid(strList, Len(strDelim)) Else strList = Join(NameList, strDelim) End If Coalsce = strList End Function </code></pre> <p>Usage:</p> <pre><code>SELECT documents.MembersOnly, Coalsce("SELECT FName From Persons WHERE Member=True",":") AS Who, Coalsce("",":","Mary","Joe","Pat?") AS Others FROM documents; </code></pre> <p>An ADO version, inspired by a comment by onedaywhen</p> <pre><code>Function ConcatADO(strSQL As String, strColDelim, strRowDelim, ParamArray NameList() As Variant) Dim rs As New ADODB.Recordset Dim strList As String On Error GoTo Proc_Err If strSQL &lt;&gt; "" Then rs.Open strSQL, CurrentProject.Connection strList = rs.GetString(, , strColDelim, strRowDelim) strList = Mid(strList, 1, Len(strList) - Len(strRowDelim)) Else strList = Join(NameList, strColDelim) End If ConcatADO = strList Exit Function Proc_Err: ConcatADO = "***" &amp; UCase(Err.Description) End Function </code></pre> <p>From: <a href="http://wiki.lessthandot.com/index.php/Concatenate_a_List_into_a_Single_Field_%28Column%29" rel="noreferrer">http://wiki.lessthandot.com/index.php/Concatenate_a_List_into_a_Single_Field_%28Column%29</a></p>
<p>I think Nz is what you're after, syntax is <code>Nz(variant, [if null value])</code>. Here's the documentation link: <a href="http://office.microsoft.com/en-us/access/HA012288901033.aspx" rel="nofollow noreferrer">Nz Function</a></p> <pre><code>---Person--- John Steve Richard DECLARE @PersonList nvarchar(1024) SELECT @PersonList = Nz(@PersonList + ',','') + Person FROM PersonTable PRINT @PersonList </code></pre>
11,816
<p>What concerns, processes, and questions do you take into account when deciding when and how to cache. Is it always a no win situation?</p> <p>This presupposes you are stuck with a code base that has been optimized. </p>
<p>I have been working with DotNetNuke most recently for web applications and there are a number of things that I consider each time I implement caching solutions.</p> <ul> <li>Do all users need to see cached content?</li> <li>How often does each bit of content change?</li> <li>Can I cache the entire page?</li> <li>Do I need a manual way to purge the cache?</li> <li>Can I use a single cache mechanism for the entire site, or do I need multiple solutions?</li> <li>What impacts occur if informaiton is somehow out of date?</li> </ul>
<p>What language are you using? With ASP you have some very easy caching with only adding some property tag over the method and the value is cached depending of the time.</p> <p>If you want more control over the cache, you can use some popular system like MemCached and have a control with time or by event.</p>
14,044
<p>How do you apply stroke (outline around text) to a textblock in xaml in WPF?</p>
<p>Below is my more idiomatically WPF, full-featured take on this. It supports pretty much everything you'd expect, including:</p> <ul> <li>all font related properties including stretch and style</li> <li>text alignment (left, right, center, justify)</li> <li>text wrapping</li> <li>text trimming</li> <li>text decorations (underline, strike through etcetera)</li> </ul> <p>Here's a simple example of what can be achieved with it:</p> <pre><code>&lt;local:OutlinedTextBlock FontFamily="Verdana" FontSize="20pt" FontWeight="ExtraBold" TextWrapping="Wrap" StrokeThickness="1" Stroke="{StaticResource TextStroke}" Fill="{StaticResource TextFill}"&gt; Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit &lt;/local:OutlinedTextBlock&gt; </code></pre> <p>Which results in:</p> <p><img src="https://i.stack.imgur.com/gyDYX.png" alt="enter image description here"></p> <p>Here's the code for the control:</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.ComponentModel; using System.Globalization; using System.Windows; using System.Windows.Documents; using System.Windows.Markup; using System.Windows.Media; [ContentProperty("Text")] public class OutlinedTextBlock : FrameworkElement { public static readonly DependencyProperty FillProperty = DependencyProperty.Register( "Fill", typeof(Brush), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register( "Stroke", typeof(Brush), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register( "StrokeThickness", typeof(double), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner( typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner( typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner( typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner( typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner( typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty TextProperty = DependencyProperty.Register( "Text", typeof(string), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextInvalidated)); public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register( "TextAlignment", typeof(TextAlignment), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register( "TextDecorations", typeof(TextDecorationCollection), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register( "TextTrimming", typeof(TextTrimming), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register( "TextWrapping", typeof(TextWrapping), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated)); private FormattedText formattedText; private Geometry textGeometry; public OutlinedTextBlock() { this.TextDecorations = new TextDecorationCollection(); } public Brush Fill { get { return (Brush)GetValue(FillProperty); } set { SetValue(FillProperty, value); } } public FontFamily FontFamily { get { return (FontFamily)GetValue(FontFamilyProperty); } set { SetValue(FontFamilyProperty, value); } } [TypeConverter(typeof(FontSizeConverter))] public double FontSize { get { return (double)GetValue(FontSizeProperty); } set { SetValue(FontSizeProperty, value); } } public FontStretch FontStretch { get { return (FontStretch)GetValue(FontStretchProperty); } set { SetValue(FontStretchProperty, value); } } public FontStyle FontStyle { get { return (FontStyle)GetValue(FontStyleProperty); } set { SetValue(FontStyleProperty, value); } } public FontWeight FontWeight { get { return (FontWeight)GetValue(FontWeightProperty); } set { SetValue(FontWeightProperty, value); } } public Brush Stroke { get { return (Brush)GetValue(StrokeProperty); } set { SetValue(StrokeProperty, value); } } public double StrokeThickness { get { return (double)GetValue(StrokeThicknessProperty); } set { SetValue(StrokeThicknessProperty, value); } } public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public TextAlignment TextAlignment { get { return (TextAlignment)GetValue(TextAlignmentProperty); } set { SetValue(TextAlignmentProperty, value); } } public TextDecorationCollection TextDecorations { get { return (TextDecorationCollection)this.GetValue(TextDecorationsProperty); } set { this.SetValue(TextDecorationsProperty, value); } } public TextTrimming TextTrimming { get { return (TextTrimming)GetValue(TextTrimmingProperty); } set { SetValue(TextTrimmingProperty, value); } } public TextWrapping TextWrapping { get { return (TextWrapping)GetValue(TextWrappingProperty); } set { SetValue(TextWrappingProperty, value); } } protected override void OnRender(DrawingContext drawingContext) { this.EnsureGeometry(); drawingContext.DrawGeometry(this.Fill, new Pen(this.Stroke, this.StrokeThickness), this.textGeometry); } protected override Size MeasureOverride(Size availableSize) { this.EnsureFormattedText(); // constrain the formatted text according to the available size // the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions // the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw this.formattedText.MaxTextWidth = Math.Min(3579139, availableSize.Width); this.formattedText.MaxTextHeight = Math.Max(0.0001d, availableSize.Height); // return the desired size return new Size(this.formattedText.Width, this.formattedText.Height); } protected override Size ArrangeOverride(Size finalSize) { this.EnsureFormattedText(); // update the formatted text with the final size this.formattedText.MaxTextWidth = finalSize.Width; this.formattedText.MaxTextHeight = finalSize.Height; // need to re-generate the geometry now that the dimensions have changed this.textGeometry = null; return finalSize; } private static void OnFormattedTextInvalidated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var outlinedTextBlock = (OutlinedTextBlock)dependencyObject; outlinedTextBlock.formattedText = null; outlinedTextBlock.textGeometry = null; outlinedTextBlock.InvalidateMeasure(); outlinedTextBlock.InvalidateVisual(); } private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var outlinedTextBlock = (OutlinedTextBlock)dependencyObject; outlinedTextBlock.UpdateFormattedText(); outlinedTextBlock.textGeometry = null; outlinedTextBlock.InvalidateMeasure(); outlinedTextBlock.InvalidateVisual(); } private void EnsureFormattedText() { if (this.formattedText != null || this.Text == null) { return; } this.formattedText = new FormattedText( this.Text, CultureInfo.CurrentUICulture, this.FlowDirection, new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, FontStretches.Normal), this.FontSize, Brushes.Black); this.UpdateFormattedText(); } private void UpdateFormattedText() { if (this.formattedText == null) { return; } this.formattedText.MaxLineCount = this.TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue; this.formattedText.TextAlignment = this.TextAlignment; this.formattedText.Trimming = this.TextTrimming; this.formattedText.SetFontSize(this.FontSize); this.formattedText.SetFontStyle(this.FontStyle); this.formattedText.SetFontWeight(this.FontWeight); this.formattedText.SetFontFamily(this.FontFamily); this.formattedText.SetFontStretch(this.FontStretch); this.formattedText.SetTextDecorations(this.TextDecorations); } private void EnsureGeometry() { if (this.textGeometry != null) { return; } this.EnsureFormattedText(); this.textGeometry = this.formattedText.BuildGeometry(new Point(0, 0)); } } </code></pre>
<p>&lt;TextBlock&gt; has no decorative attributes itself. I would put it on a &lt;Canvas&gt; with a &lt;Rectangle&gt; and apply the stroke there.</p>
11,920
<p>I have installed CherryPy 3.1.0,. Here is what happens when I try to run tutorial 9:</p> <pre><code>$ cd /Library/Python/2.5/site-packages/cherrypy/tutorial/ $ python tut09_files.py Traceback (most recent call last): File "tut09_files.py", line 48, in &lt;module&gt; from cherrypy.lib import static ImportError: cannot import name static </code></pre> <p>The previous line in the file:</p> <pre><code>import cherrypy </code></pre> <p>passes without error, so it appears that it can find cherrypy on the path. What am I missing?</p>
<p>I am a big fan of the proposed HTML 5 solution (<code>data-</code> prefixed attributes). Edit: I'd add that there are probably better examples for the use of custom attributes. For instance, data that a custom application will use that have no analogue in standard attributes (eg. customization for event handlers based on something that can't necessarily be expressed in a className or id).</p>
<p>My personal feeling in your example is that the span route is more appropriate, as it meets the standards of the XHTML specification. However, i can see an argment for custom attributes, but I think they add a level of confusion that isn't needed.</p>
25,703
<p>I have a class that I need to binary serialize. The class contains one field as below:</p> <pre><code>private T[,] m_data; </code></pre> <p>These multi-dimensional arrays can be fairly large (hundreds of thousands of elements) and of any primitive type. When I tried standard .net serialization on an object the file written to disk was large and I think .net is storing a lot of repeated data about element types and possibly not as efficiently as could be done.</p> <p>I have looked around for custom serializers but have not seen any that deal with multi-dimensional generic arrays. I have also experimented with built-in .net compression on a byte array of the memory stream following serializing with some success, but not as quick / compressed as I had hoped.</p> <p>My question is, should I try and write a custom serializer to optimally serialize this array for the appropriate type (this seems a little daunting), or should I use standard .net serialization and add compression?</p> <p>Any advice on the best approach would be most appreciated, or links to resources showing how to tackle serialization of a multi-dimensional generic array - as mentioned <a href="http://www.codeproject.com/KB/dotnet/FastSerializer.aspx" rel="noreferrer">existing examples</a> I have found do not support such structures.</p>
<p>Here's what I came up with. The code below makes an int[1000][10000] and writes it out using the BinaryFormatter to 2 files - one zipped and one not. </p> <p>The zipped file is 1.19 MB (1,255,339 bytes) Unzipped is 38.2 MB (40,150,034 bytes)</p> <pre><code> int width = 1000; int height = 10000; List&lt;int[]&gt; list = new List&lt;int[]&gt;(); for (int i = 0; i &lt; height; i++) { list.Add(Enumerable.Range(0, width).ToArray()); } int[][] bazillionInts = list.ToArray(); using (FileStream fsZ = new FileStream("c:\\temp_zipped.txt", FileMode.Create)) using (FileStream fs = new FileStream("c:\\temp_notZipped.txt", FileMode.Create)) using (GZipStream gz = new GZipStream(fsZ, CompressionMode.Compress)) { BinaryFormatter f = new BinaryFormatter(); f.Serialize(gz, bazillionInts); f.Serialize(fs, bazillionInts); } </code></pre> <p>I can't think of a better/easy way to do this. The zipped version is pretty damn tight.</p> <p>I'd go with the BinaryFormatter + GZipStream. Making something custom would not be fun at all.</p> <hr> <p>[edit by MG] I hope you won't be offended by an edit, but the uniform repeated Range(0,width) is skewing things vastly; change to:</p> <pre><code> int width = 1000; int height = 10000; Random rand = new Random(123456); int[,] bazillionInts = new int[width, height]; for(int i = 0 ; i &lt; width;i++) for (int j = 0; j &lt; height; j++) { bazillionInts[i, j] = rand.Next(50000); } </code></pre> <p>And try it; you'll see <code>temp_notZipped.txt</code> at 40MB, <code>temp_zipped.txt</code> at 62MB. Not so appealing...</p>
<p>The best code length/output size ratio would be to encode your array using BitConverter, converting all elements into their compact binary format. It's manual, I know, but will save 80-90% space compared to .NET binary serialization.</p>
27,629
<p>I don't want to have the user install Google Gears so I can show him his guessed location. Is there a way to get the location without having to use Google Gears?</p> <p>I have found <a href="http://www.wipmania.com/de/blog/google-geolocation-api/" rel="noreferrer">http://www.wipmania.com/de/blog/google-geolocation-api/</a> but it does not offer an example.</p>
<p>This is typically called IP Geolocation.</p> <p>An example is <a href="http://www.geody.com/geoip.php" rel="noreferrer">here</a>.</p> <p>The thing is, most sites (if you plan on calling this as a web service) will charge you for it. Otherwise, throw together a web service that grabs a geolocation page, parses it for the address, and returns that piece of information.</p> <p>In PHP, this seems to work pretty well:</p> <pre><code>&lt;?php if(isset($_GET["ip"])){ echo geolocate($_GET["ip"]); } function geolocate($ip){ $raw_html = file_get_contents("http://www.geody.com/geoip.php?ip=$ip"); if(preg_match('/Location:(.*)/',$raw_html,$matches)){ $location_raw = $matches[1]; //Get rid of pesky HTML tags $location = preg_replace("/&lt;[^&gt;]*&gt;/","",$location_raw); return $location; }else{ return "ERROR"; } } </code></pre>
<p>If your users are on mobile, <a href="http://xtify.com" rel="nofollow noreferrer">Xitfy</a> is also a free option. They have a small client that after the user agrees can be seamlessly installed on their handset. You can then call a REST based api to get their exact lat/lon sourced from gps / wifi or cell tower.</p> <p>They support Android, Windows Mobile, BlackBerry and Symbian which covers almost all smartphones.</p>
40,466
<p>How do you find a memory leak in Java (using, for example, JHat)? I have tried to load the heap dump up in JHat to take a basic look. However, I do not understand how I am supposed to be able to find the root reference (<a href="https://stackoverflow.com/questions/104/anatomy-of-a-memory-leak">ref</a>) or whatever it is called. Basically, I can tell that there are several hundred megabytes of hash table entries ([java.util.HashMap$Entry or something like that), but maps are used all over the place... Is there some way to search for large maps, or perhaps find general roots of large object trees?</p> <p>[Edit] Ok, I've read the answers so far but let's just say I am a cheap bastard (meaning I am more interested in learning how to use JHat than to pay for JProfiler). Also, JHat is always available since it is part of the JDK. Unless of course there is no way with JHat but brute force, but I can't believe that can be the case.</p> <p>Also, I do not think I will be able to actually modify (adding logging of <em>all</em> map sizes) and run it for long enough for me to notice the leak.</p>
<p>I use following approach to finding memory leaks in Java. I've used jProfiler with great success, but I believe that any specialized tool with graphing capabilities (diffs are easier to analyze in graphical form) will work.</p> <ol> <li>Start the application and wait until it get to "stable" state, when all the initialization is complete and the application is idle.</li> <li>Run the operation suspected of producing a memory leak several times to allow any cache, DB-related initialization to take place.</li> <li>Run GC and take memory snapshot.</li> <li>Run the operation again. Depending on the complexity of operation and sizes of data that is processed operation may need to be run several to many times.</li> <li>Run GC and take memory snapshot.</li> <li>Run a diff for 2 snapshots and analyze it.</li> </ol> <p>Basically analysis should start from greatest positive diff by, say, object types and find what causes those extra objects to stick in memory.</p> <p>For web applications that process requests in several threads analysis gets more complicated, but nevertheless general approach still applies.</p> <p>I did quite a number of projects specifically aimed at reducing memory footprint of the applications and this general approach with some application specific tweaks and trick always worked well.</p>
<p>You really need to use a memory profiler that tracks allocations. Take a look at <a href="http://www.ej-technologies.com/products/jprofiler/overview.html" rel="nofollow noreferrer">JProfiler</a> - their "heap walker" feature is great, and they have integration with all of the major Java IDEs. It's not free, but it isn't that expensive either ($499 for a single license) - you will burn $500 worth of time pretty quickly struggling to find a leak with less sophisticated tools.</p>
6,132
<p>The CodePlex team has a <a href="https://rads.stackoverflow.com/amzn/click/com/0767907698" rel="noreferrer" rel="nofollow noreferrer">Slack</a> time policy, and it's worked out very well for them.</p> <ul> <li>Jim Newkirk and myself used it to work on the <a href="http://www.codeplex.com/xunit" rel="noreferrer">xUnit.net</a> project.</li> <li>Jonathan Wanagel used it to work on <a href="http://www.codeplex.com/SvnBridge" rel="noreferrer">SvnBridge</a>.</li> <li>Scott Densmore and myself used it to work on an <a href="http://www.codeplex.com/ObjectBuilder" rel="noreferrer">ObjectBuilder 2.0</a> prototype.</li> </ul> <p>For others, it was a great time to explore things that were technically not on the schedule, but could eventually end up being of great use to the rest of the team. I'm so convinced of the value of this that if I'm ever running a team again, I'm going to make it part of the team culture.</p> <p>Have you had a formalized Slack policy on your team? How did it work out?</p> <p><strong>Edited:</strong> I just realized I didn't define Slack. For those who haven't read the book, Slack is what Google's "20% time" is: you're given some slice of your day/week/month/year on which to work on things that are not necessarily directly related to your day-to-day job, but might have an indirect benefit (obviously if you work on stuff that's totally not useful for your job or your company, your manager probably won't think very well of the way you spent the time :-p).</p>
<p>I just want to mention Google's policy on the subject.<br> 20% of the day should be used for private projects and research. </p> <p>I think it is time for managers to face the fact that most good developers are a bit lazy. If they weren't, we wouldn't have concepts like code reuse.<br> If this laziness can be focused into a creative force, and the developers can read up on technical issues and experiment with architecture and language features, I am certain that the end result will be better code and a more satisfied developer. </p> <p>So, if you are a manager: Let your developers slack of now and then. Encourage them to hold small seminars with the team to discuss new ways of doing stuff. </p> <p>If you are a developer: Read, learn and love your craft. You have one of the best jobs in the world, as long as you are willing to put some time into learning the best ways to do your job.</p>
<p>I've never worked anywhere that had a formalized policy, but practically every manager I've ever had has allowed me to spend some time on things that weren't directly related to the current project or fighting a fire.</p> <p>I think the key is to talk about the things you'd like to try. Most managers want their teams to do something cool, something extraordinary, so if you can convince them that you might deliver something, you might get the chance. Or they might let you do it just to keep you happy.</p> <p>Now that I'm a contractor rather than an employee, I don't get paid to do fun stuff, but I generally only work 30-35 hours per week, so I still have time to learn and to play.</p>
3,434
<p>How to insert data into a particular cell in a Excel Work sheet in Asp.net</p>
<p>I think you need to provide a little more information..</p> <p>Off the top of my head, you could approach this a number of different ways :</p> <p><em>1)</em> MS Office Automation - Using javascript you could open Excel, open the 'correct' document and then insert the particular data in the cell.</p> <p><strong>Issues with this method</strong> </p> <p>You will need to ensure that your site is in the trusted sites list in IE to perform office automation. This may not be possible unless you are writing an intranet application.</p> <p>I've only used automation in IE before, it may not work in Firefox.</p> <p>It relies on the user having Excel installed and the correct file downloaded to their computer and available.</p> <p><em>2)</em> Roll your own Excel document - Probably easiest if your users version of Excel supports xml worksheets, Open the excel sheet server side, then using something like XPath queries find the relevant cell in the worksheet and insert your data. Stream the sheet out to the user as part of the HTTP Response.</p> <p><strong>Issues with this method</strong> </p> <p>The spreadsheet will always be from the server copy, unless you provide some mechanism for the user to upload their spreadsheet first. This has a whole raft of issues associated with it though.</p> <p><em>3)</em> Purchase an Excel Spreadsheet producer application - There are a number of programs out there which have wrapped up the process of creating 'true' (i.e. .xls) spreadsheets into nice easy to use .dll libraries.</p> <p><strong>Issues with this method</strong> </p> <p>$$$ Involved.</p>
<p>Does the worksheet already exist? If it does you can open the worksheet using the open-source component <a href="http://sourceforge.net/projects/koogra/" rel="nofollow noreferrer">Koogra</a> og the commercial component from <a href="http://infragistics.com/" rel="nofollow noreferrer">Infragistics</a> (there are others as well) and modify it in code. The alternative is to open the worksheet using excel automation, but that is not recommended in a web project. </p> <p>By the way. <a href="https://stackoverflow.com/questions/tagged/excel">You are not the first to ask this question.</a></p>
32,711
<p>I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?</p> <ul> <li><p>When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python?</p></li> <li><p>When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup?</p></li> <li><p>How do you handle/prevent typing errors (typos)?</p></li> <li><p>Are UnitTest's used as a substitute for static type checking?</p></li> </ul> <p>As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.</p>
<h2>Don't use a screw driver as a hammer</h2> <p>Python is not a statically typed language, so don't try to use it that way.</p> <p>When you use a specific tool, you use it for what it has been built. For Python, it means:</p> <ul> <li><p><strong>Duck typing</strong> : no type checking. Only behavior matters. Therefore your code must be designed to use this feature. A good design means generic signatures, no dependences between components, high abstraction levels.. So if you change anything, you won't have to change the rest of the code. Python will not complain either, that what it has been built for. Types are not an issue.</p></li> <li><p><strong>Huge standard library</strong>. You do not need to change all your calls in the program if you use standard features you haven't coded yourself. And Python come with batteries included. I keep discovering them everyday. I had no idea of the number of modules I could use when I started and tried to rewrite existing stuff like everybody. It's OK, you can't get it all right from the beginning.</p></li> </ul> <p>You don't write Java, C++, Python, PHP, Erlang, whatever, the same way. They are good reasons why there is room for each of so many different languages, they do not do the same things.</p> <h2>Unit tests are not a substitute</h2> <p>Unit tests must be performed with any language. The most famous unit test library (<a href="http://en.wikipedia.org/wiki/JUnit" rel="noreferrer">JUnit</a>) is from the Java world!</p> <p>This has nothing to do with types. You check behaviors, again. You avoid trouble with regression. You ensure your customer you are on tracks.</p> <h2>Python for large scale projects</h2> <blockquote> <p>Languages, libraries and frameworks don't scale. Architectures do.</p> </blockquote> <p>If you design a solid architecture, if you are able to make it evolves quickly, then it will scale. Unit tests help, automatic code check as well. But they are just safety nets. And small ones.</p> <p>Python is especially suitable for large projects because it enforces some good practices and has a lot of usual design patterns built-in. But again, do not use it for what it is not designed. E.g : Python is not a technology for CPU intensive tasks.</p> <p>In a huge project, you will most likely use several different technologies anyway. As a <a href="https://stackoverflow.com/questions/980813/what-is-sgbd">SGBD</a> (French for <a href="https://en.wikipedia.org/wiki/Database" rel="noreferrer">DBMS</a>) and a templating language, or else. Python is no exception.</p> <p>You will probably want to use C/C++ for the part of your code you need to be fast. Or Java to fit in a <a href="http://en.wikipedia.org/wiki/Apache_Tomcat" rel="noreferrer">Tomcat</a> environment. Don't know, don't care. Python can play well with these.</p> <h2>As a conclusion</h2> <p>My answer may feel a bit rude, but don't get me wrong: this is a very good question.</p> <p>A lot of people come to Python with old habits. I screwed myself trying to code Java like Python. You can, but will never get the best of it.</p> <p>If you have played / want to play with Python, it's great! It's a wonderful tool. But just a tool, really.</p>
<p>The usual answer to that is testing testing testing. You're supposed to have an extensive unit test suite and run it often, particularly before a new version goes online.</p> <p>Proponents of dynamically typed languages make the case that you have to test anyway because even in a statically typed language conformance to the crude rules of the type system covers only a small part of what can potentially go wrong.</p>
29,259
<p>I would like display something more meaningful that animated gif while users upload file to my web application. What possibilities do I have? </p> <p><em>Edit: I am using .Net but I don't mind if somebody shows me platform agnostic version.</em></p>
<p>Here are a couple of versions of what you're looking for for some common JavaScript toolkits.</p> <ul> <li>Mootools - <a href="http://digitarald.de/project/fancyupload/" rel="noreferrer">http://digitarald.de/project/fancyupload/</a></li> <li>Extjs - <a href="http://extjs.com/learn/Extension:UploadForm" rel="noreferrer">http://extjs.com/learn/Extension:UploadForm</a></li> </ul>
<p>jQuery UI Progressbar - <a href="http://jqueryui.com/demos/progressbar/" rel="nofollow noreferrer">http://jqueryui.com/demos/progressbar/</a></p>
7,219
<p>What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice.</p> <p>So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm.</p>
<p>The fastest (O(n)) and most memory efficient (O(1)) way is with the XOR operation.</p> <p>In C:</p> <pre><code>int arr[] = {3, 2, 5, 2, 1, 5, 3}; int num = 0, i; for (i=0; i &lt; 7; i++) num ^= arr[i]; printf("%i\n", num); </code></pre> <p>This prints "1", which is the only one that occurs once.</p> <p>This works because the first time you hit a number it marks the num variable with itself, and the second time it unmarks num with itself (more or less). The only one that remains unmarked is your non-duplicate.</p>
<p>You could simply put the elements in the set into a hash until you find a collision. In ruby, this is a one-liner.</p> <pre><code>def find_dupe(array) h={} array.detect { |e| h[e]||(h[e]=true; false) } end </code></pre> <p>So, <code>find_dupe([1,2,3,4,5,1])</code> would return 1. </p> <p>This is actually a common "trick" interview question though. It is normally about a list of consecutive integers with one duplicate. In this case the interviewer is often looking for you to use the Gaussian sum of <em>n</em>-integers trick e.g. <code>n*(n+1)/2</code> subtracted from the actual sum. The textbook answer is something like this. </p> <pre><code>def find_dupe_for_consecutive_integers(array) n=array.size-1 # subtract one from array.size because of the dupe array.sum - n*(n+1)/2 end </code></pre>
5,561
<p>Just got a request from my boss for an application I'm working on. Basically we're getting an email address setup for an external client to submit excel files to. </p> <p>What I need is a way to automatically pick up any email sent to this address, so I can take the attachment, process it and save it to a folder.</p> <p>Any information of even where to start would be helpful.\</p> <p>Note: We're using a lotus notes server to do this, but a generic way would be more helpful (If possible).</p>
<p>Email -> mailserver ->[something] -> file-on-disk.</p> <p>File on disk is pretty easy to parse, use <a href="http://java.sun.com/products/javamail/javadocs/javax/mail/package-summary.html" rel="noreferrer">JavaMail</a>.</p> <p>The [something] could be:</p> <ul> <li>listener for smtp connections (overkill)!</li> <li><a href="http://java.sun.com/products/javamail/javadocs/com/sun/mail/pop3/package-summary.html" rel="noreferrer">Pop3</a>/<a href="http://java.sun.com/products/javamail/javadocs/com/sun/mail/imap/package-summary.html" rel="noreferrer">imap</a> client</li> <li><a href="http://en.wikipedia.org/wiki/Maildir" rel="noreferrer">Maildir</a>/Mailbox</li> </ul>
<p>Lotus Notes/Domino stores mail in a Notes database. There are APIs available for getting documents (emails), reading field values (From, Subject), and detaching files.</p> <p>APIs include</p> <p>-LotusScript (VB variant, available within the Notes database)</p> <p>-Java (from within or external to the database)</p> <p>-C API (external)</p> <p>-Same API available through COM server</p> <p>You can create a "scheduled agent" within the database (using LotusScript or Java) that can locate documents created since it last ran, locate the attachments, and extract them. The agent will need to be signed with an ID that has the appropriate permissions on the server, including those required to write to the file system and initiate any other processes.</p> <p>External to the database, you can use any API except LotusScript to log-in to the server/mail database, and follow a similar process, e.g. extracting the files locally on a client or separate server. C API and COM require a notes client install, but Java applications can be set up to run via CORBA/DIIOP without a full install.</p> <p>Consult the Domino Designer help (or IBM's website for C API) for more information.</p> <p>As to a "generic way" to do this, if you are accessing data in Notes and needing to extract attachments, I believe these APIs are your best option. If you envision porting the application to another mail system, consider decoupling the API routines via an "interface" so you only need to add a new implementation of that interface to support a new mail system.</p>
8,078
<p>I'm quoting part of an answer which I received for <a href="https://stackoverflow.com/questions/83088/phpmysql-regular-recalcuation-of-benchmark-values-as-new-users-submit-their-data">another question of mine</a>:</p> <blockquote> <p>In the PHP/MySQL world I would say stored procedures are no-go</p> </blockquote> <p>I would like to know: Is that so? Why? Why not?</p> <p>[edit]I mean this as a general question without a specific need in mind[/edit]</p>
<p>I develop and maintain a large PHP/MySQL application. Here is my experience with stored procedures.</p> <p>Over time our application has grown very complex. And with all the logic on the php side, some operations would query the database with over 100 short queries.</p> <p>MySQL is so quick that the performance was still acceptable, but not great.</p> <p>We made the decision in our latest version of the software to move some of the logic to stored procedures for complex operations.</p> <p>We did achieve a significant performance gain due to the fact that we did not have to send data back and forth between PHP and MySQL.</p> <p>I do agree with the other posters here that PL/SQL is not a modern language and is difficult to debug.</p> <p>Bottom Line: Stored Procedures are a great tool for certain situations. But I would not recommend using them unless you have a good reason. For simple applications, stored procedures are not worth the hassle.</p>
<p>I think that using stored procedures can offer some abstraction in certain applications, as in any where you would use the same SQL code chunk to update or add the same data, you could then create the one sproc save_user($attr.....) rather that repeating yourself all over the place. </p> <p>Agreed the syntax is hairy and if your used to MSSQL and oracle sprocs there are differences that can fustrate.</p>
10,908
<p>Trying to create several layers of folders at once C:\pie\applepie\recipies\ without using several different commands, is there an easy way similar to Directory.CreateDirectory()</p>
<p>Here's some code I used in one of my projects. It requires a reference be added to the project for the file system object.</p> <p>First, click Project -> References, scroll down to "Microsoft Scripting Runtime" and select it. Then you can use this function:</p> <pre><code>Public Sub MakePath(ByVal Folder As String) Dim arTemp() As String Dim i As Long Dim FSO As Scripting.FileSystemObject Dim cFolder As String Set FSO = New Scripting.FileSystemObject arTemp = Split(Folder, "\") For i = LBound(arTemp) To UBound(arTemp) cFolder = cFolder &amp; arTemp(i) &amp; "\" If Not FSO.FolderExists(cFolder) Then Call FSO.CreateFolder(cFolder) End If Next End Sub </code></pre>
<p>As an alternative, here is a function I wrote that takes a complete path including a drive letter if needed as a parameter. It then walks the path and traps the VB error number 76 (path not found). When the error handler traps an error 76 it creates the folder that caused the error and resumes walking the path.</p> <pre> Public Function Check_Path(rsPath As String) As Boolean Dim dPath As String Dim i As Integer Dim sProductName As String On Error GoTo Check_Path_Error If Left$(UCase$(rsPath), 2) Left$(UCase$(CurDir), 2) Then ChDrive Left$(rsPath, 2) End If i = 3 Do While InStr(i + 1, rsPath, "\") > 0 dPath = Left$(rsPath, InStr(i + 1, rsPath, "\") - 1) i = InStr(i + 1, rsPath, "\") ChDir dPath Loop dPath = rsPath ChDir dPath Check_Path = True Exit Function Check_Path_Error: If Err.Number = 76 Then 'path not found' MkDir dPath 'create the folder' Resume Else sProductName = IIf(Len(App.ProductName) = 0, App.EXEName, App.ProductName) MsgBox "There was an unexpected error while verifying/creating directories." _ & vbCrLf & vbCrLf & "Error: " & CStr(Err.Number) & ", " & Err.Description & ".", _ vbOKOnly + vbCritical, sProductName & " - Error Creating File" Check_Path = False End If End Function </pre>
36,187
<p>The design for the website I am working on calls for a custom image on lists instead of a bullet. Using the image is fine, but I have been having difficulties ensuring that it is centered against the text of the list item across all browsers. Does anyone know of a standard solution for this?</p>
<p>If you are referring to using a custom image bullet for your list this is the code you'll want to use, it will be vertically centered. I'm assuming here that the bullet image is 12px by 12px.</p> <pre class="lang-css prettyprint-override"><code>ul li { background: transparent url(/link/to/custom/bullet.gif) no-repeat 0 50%; padding-left: 18px; } </code></pre> <p>The only problem with this is that sometimes on long multi-line list items it looks odd. In that case it might be best to assign the background position to a slight indent from the top and the left (i.e. no-repeat 0 7px). </p> <p>cheers, Bruce</p>
<p>Have you tried adding the following code in your CSS file?</p> <pre class="lang-css prettyprint-override"><code>li { background-image: URL('custom.png'); background-repeat: no-repeat; background-position: center; } </code></pre>
8,985
<p>I hope it is correct term-wise to say that components in a GUI is like JButton, JPanel, JTextField, all that good stuff.</p> <p>I want to create a text field that takes in an integer. Then a submit button can be pressed and based on the integer that was inputted, create that many textfields in a popup window or whatever.</p> <p>I have no clue, could someone get me started in the right direction?</p> <p>The trouble I'm having is that I have no clue how to create a for loop to create the GUI components. I mean if I have a for loop and do something like:</p> <pre><code>print("JTextField num1 = new JTextField()"); </code></pre> <p>then in a for loop it will only create 1 text field when I want many. How do I generically create variables of JTextFields?</p> <p>Thanks for your help...</p>
<p>Use an appropriate LayoutManager (e.g. GridLayout) to create and add your textfields.</p> <pre><code>for (i = 0; i &lt; numberOfTextFields; i++) { JTextField textField = new JTextField(); container.add(textField); /* also store textField somewhere else. */ } </code></pre>
<p>I would create a List to store the text fields, and then you can get them back by index. Then you can have as many fields as you need.</p> <pre><code>List fields = new ArrayList(); // Create as many elements as you need for (int i = 0; i &lt; numberOfElements; i++){ JTextField field = new JTextField(); // Add the fields to some panel so they are shown in the screen. // I assume that the component is called parent panel parentPanel.add(field); // Store the component in the list so you can retrieve it later fields.add(field); } // ... // When you want to retrieve a particular one: JTextField field = (JTextField)fields.get( indexToRetrieve ); </code></pre>
48,027
<p>I've been here for a little while. I am still a low-reputation of SE, with most of my involvement being here. I know that each SE has it's own personality, somewhat derived from the charter, somewhat from the written standards, and somewhat determined by the customary practices in the community.</p> <p>I have found from reading many answers that the first line is often &quot;soft&quot;. A welcome to a new user. A word of appreciation for the question. A social throat-clearing before jumping into the substance of the answer. Over time, I have adopted this form myself, especially with a user who is new to 3D Printing SE.</p> <p>Three days ago, one of my answers was edited to remove the preliminary social lubricant. I'm fine with this, and I understand it is in keeping with the position that the value of SE to the investors is in the responsive content of the answers, not in the social glue. I would have approved the edits myself except that one can not do that from the app. Today, I connected through a desktop and found that the edit had been auto-approved. Again, no problem.</p> <p>But to the question.</p> <p>We want to be welcoming to new users, and we hope they will stay close to the site and become active members. To do so requires communication, the informal, person-to-person communication that builds oxytocin rather than facts. This doesn't fit the business purpose of SE, but it is necessary to support the mission of SE which must succeed for the business to succeed.</p> <p>Is the right method to:</p> <ol> <li>Welcome people in an answer,</li> <li>Welcome people in a comment, where it is also not appropriate,</li> <li>Do not welcome people -- just stick to the facts, or</li> <li>Welcome people in an answer but go back later and strip it out?</li> </ol>
<p>I struggled with the same question since I saw the edit, good that you brought this to Meta! Thanks!</p> <p>As the community of regular and active members is limited, I think it is okay to welcome people in a comment or an answer. It would be a shame to scare people away after their first question, resulting in abandoned questions and unaccepted answers. But, we do need to conform to the Q&amp;A format and sometimes need to remind people this isn't a forum of threaded messages and we do have some rules to participate. We have created some <a href="/q/303/">standard comments</a> that welcome and thank new members but at the same time lead them to the rules of the site.</p> <p>It might be a good idea to approach first time (SE) members friendly. Welcoming comments can and tend to be deleted after a while when users aren't new anymore (everybody can raise a flag on a comment to vote for <em>”It's no longer needed&quot;</em>). So option 4 would be my preferred option.</p> <p>Personally I think this site is more welcoming than larger sites as SO for instance. My first experiences at SO didn't make me feel welcome.</p>
<p>I struggled with the same question since I saw the edit, good that you brought this to Meta! Thanks!</p> <p>As the community of regular and active members is limited, I think it is okay to welcome people in a comment or an answer. It would be a shame to scare people away after their first question, resulting in abandoned questions and unaccepted answers. But, we do need to conform to the Q&amp;A format and sometimes need to remind people this isn't a forum of threaded messages and we do have some rules to participate. We have created some <a href="/q/303/">standard comments</a> that welcome and thank new members but at the same time lead them to the rules of the site.</p> <p>It might be a good idea to approach first time (SE) members friendly. Welcoming comments can and tend to be deleted after a while when users aren't new anymore (everybody can raise a flag on a comment to vote for <em>”It's no longer needed&quot;</em>). So option 4 would be my preferred option.</p> <p>Personally I think this site is more welcoming than larger sites as SO for instance. My first experiences at SO didn't make me feel welcome.</p>
77
<p>Lists in C# have the <code>.ToArray()</code> method. I want the inverse, where an array is transformed into a list. I know how to create a list and loop through it but I would like a one liner to swap it back.</p> <p>I am using the <code>String.Split</code> method in the .NET 2.0 environment, so LINQ, etc. is not available to me.</p>
<pre><code>string s = ... new List&lt;string&gt;(s.Split(....)); </code></pre>
<p>If all you need is an object that implements the IList interface and you do not need to add new items you might also do it like this:</p> <pre><code>IList&lt;string&gt; list = myString.Split(' '); </code></pre>
31,388
<p>I'm looking for a simple, but cross-platform <em>negate</em>-process that negates the value a process returns. It should map 0 to some value != 0 and any value != 0 to 0, i.e. the following command should return "yes, nonexistingpath doesn't exist":</p> <pre><code> ls nonexistingpath | negate &amp;&amp; echo "yes, nonexistingpath doesn't exist." </code></pre> <p>The ! - operator is great but unfortunately not shell-independent.</p>
<p><sup><em>Previously, the answer was presented with what's now the first section as the last section.</em></sup></p> <h3>POSIX Shell includes a <code>!</code> operator</h3> <p>Poking around the shell specification for other issues, I recently (September 2015) noticed that the POSIX shell supports a <code>!</code> operator. For example, it is listed as a <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_04" rel="noreferrer">reserved word</a> and can appear at the start of a <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_02" rel="noreferrer">pipeline</a> — where a simple command is a special case of 'pipeline'. It can, therefore, be used in <code>if</code> statements and <code>while</code> or <code>until</code> loops too — in POSIX-compliant shells. Consequently, despite my reservations, it is probably more widely available than I realized back in 2008. A quick check of POSIX 2004 and SUS/POSIX 1997 shows that <code>!</code> was present in both those versions.</p> <p>Note that the <code>!</code> operator must appear at the <em>beginning</em> of the pipeline and negates the status code of the entire pipeline (i.e. the <em>last</em> command). Here are some examples.</p> <pre><code># Simple commands, pipes, and redirects work fine. $ ! some-command succeed; echo $? 1 $ ! some-command fail | some-other-command fail; echo $? 0 $ ! some-command &lt; succeed.txt; echo $? 1 # Environment variables also work, but must come after the !. $ ! RESULT=fail some-command; echo $? 0 # A more complex example. $ if ! some-command &lt; input.txt | grep Success &gt; /dev/null; then echo 'Failure!'; recover-command; mv input.txt input-failed.txt; fi Failure! $ ls *.txt input-failed.txt </code></pre> <h3>Portable answer — works with antique shells</h3> <p>In a Bourne (Korn, POSIX, Bash) script, I use:</p> <pre><code>if ...command and arguments... then : it succeeded else : it failed fi </code></pre> <p>This is as portable as it gets. The 'command and arguments' can be a pipeline or other compound sequence of commands.</p> <h3>A <code>not</code> command</h3> <p>The '!' operator, whether built-in to your shell or provided by the o/s, is not universally available. It isn't dreadfully hard to write, though - the code below dates back to at least 1991 (though I think I wrote a previous version even longer ago). I don't tend to use this in my scripts, though, because it is not reliably available.</p> <pre class="lang-c prettyprint-override"><code>/* @(#)File: $RCSfile: not.c,v $ @(#)Version: $Revision: 4.2 $ @(#)Last changed: $Date: 2005/06/22 19:44:07 $ @(#)Purpose: Invert success/failure status of command @(#)Author: J Leffler @(#)Copyright: (C) JLSS 1991,1997,2005 */ #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/wait.h&gt; #include &quot;stderr.h&quot; #ifndef lint static const char sccs[] = &quot;@(#)$Id: not.c,v 4.2 2005/06/22 19:44:07 jleffler Exp $&quot;; #endif int main(int argc, char **argv) { int pid; int corpse; int status; err_setarg0(argv[0]); if (argc &lt;= 1) { /* Nothing to execute. Nothing executed successfully. */ /* Inverted exit condition is non-zero */ exit(1); } if ((pid = fork()) &lt; 0) err_syserr(&quot;failed to fork\n&quot;); if (pid == 0) { /* Child: execute command using PATH etc. */ execvp(argv[1], &amp;argv[1]); err_syserr(&quot;failed to execute command %s\n&quot;, argv[1]); /* NOTREACHED */ } /* Parent */ while ((corpse = wait(&amp;status)) &gt; 0) { if (corpse == pid) { /* Status contains exit status of child. */ /* If exit status of child is zero, it succeeded, and we should exit with a non-zero status */ /* If exit status of child is non-zero, if failed and we should exit with zero status */ exit(status == 0); /* NOTREACHED */ } } /* Failed to receive notification of child's death -- assume it failed */ return (0); } </code></pre> <p>This returns 'success', the opposite of failure, when it fails to execute the command. We can debate whether the 'do nothing successfully' option was correct; maybe it should report an error when it isn't asked to do anything. The code in '<code>&quot;stderr.h&quot;</code>' provides simple error reporting facilities - I use it everywhere. Source code on request - see my profile page to contact me.</p>
<p>Note: sometimes you will see <code>!(command || other command)</code>.<br> Here <code>! ls nonexistingpath &amp;&amp; echo "yes, nonexistingpath doesn't exist."</code> is enough.<br> No need for a sub-shell.</p> <p>Git 2.22 (Q2 2019) illustrates that better form with:</p> <p><a href="https://github.com/git/git/commit/74ec8cf6747a60885e15d4c36e6b47bc37764748" rel="nofollow noreferrer">Commit 74ec8cf</a>, <a href="https://github.com/git/git/commit/3fae7ad96d89e670a75b1335824c8ad3a92c8db0" rel="nofollow noreferrer">commit 3fae7ad</a>, <a href="https://github.com/git/git/commit/0e67c32955cee24c5ff534dd3f5f0de58ba91d02" rel="nofollow noreferrer">commit 0e67c32</a>, <a href="https://github.com/git/git/commit/07353d9042f19fec749ec8413ff7e6824460ee59" rel="nofollow noreferrer">commit 07353d9</a>, <a href="https://github.com/git/git/commit/3bc2702b883030b138a8c7585d7bc9adb4b4a399" rel="nofollow noreferrer">commit 3bc2702</a>, <a href="https://github.com/git/git/commit/8c3b9f7faa4f39ddb89be229b706d4a9f9c659a4" rel="nofollow noreferrer">commit 8c3b9f7</a>, <a href="https://github.com/git/git/commit/80a539acf6663ec97bfbf552faa32105bd7f599f" rel="nofollow noreferrer">commit 80a539a</a>, <a href="https://github.com/git/git/commit/c5c39f4e348dc4759638927343a36e79f2da7bb5" rel="nofollow noreferrer">commit c5c39f4</a> (13 Mar 2019) by <a href="https://github.com/szeder" rel="nofollow noreferrer">SZEDER Gábor (<code>szeder</code>)</a>.<br> See <a href="https://github.com/git/git/commit/99e37c2560ecb1cc44bb743a2e4aaaedb5da1a90" rel="nofollow noreferrer">commit 99e37c2</a>, <a href="https://github.com/git/git/commit/9f82b2a6a754c7cec37282d954208b4b429a3a05" rel="nofollow noreferrer">commit 9f82b2a</a>, <a href="https://github.com/git/git/commit/900721e15c43742955878dbbdb24c5a2ce262630" rel="nofollow noreferrer">commit 900721e</a> (13 Mar 2019) by <a href="https://github.com/dscho" rel="nofollow noreferrer">Johannes Schindelin (<code>dscho</code>)</a>.<br> <sup>(Merged by <a href="https://github.com/gitster" rel="nofollow noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/579b75ad9530827fe00740b8551963f16f279c40" rel="nofollow noreferrer">commit 579b75a</a>, 25 Apr 2019)</sup> </p> <blockquote> <h2><code>t9811-git-p4-label-import</code>: fix pipeline negation</h2> <p>In '<code>t9811-git-p4-label-import.sh</code>', the test '<code>tag that cannot be exported</code>' runs:</p> <pre><code>!(p4 labels | grep GIT_TAG_ON_A_BRANCH) </code></pre> <p>to check that the given string is not printed by '<code>p4 labels</code>'.<br> This is problematic, <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_02" rel="nofollow noreferrer">because according to <strong>POSIX</strong></a>:</p> <blockquote> <p>"If the pipeline begins with the reserved word <code>!</code> and <code>command1</code> is a subshell command, the application shall ensure that the <code>(</code> operator at the beginning of <code>command1</code> is separated from the <code>!</code> by one or more <code>&lt;blank&gt;</code> characters.<br> <strong>The behavior of the reserved word <code>!</code> immediately followed by the <code>(</code> operator is unspecified.</strong>"</p> </blockquote> <p>While most common shells still interpret this '<code>!</code>' as "negate the exit code of the last command in the pipeline", '<code>mksh/lksh</code>' don't and interpret it as a negative file name pattern instead.<br> As a result, they attempt to run a command made up of the pathnames in the current directory (it contains a single directory called '<code>main</code>'), which, of course, fails the test.</p> <p>We could fix it simply by adding a space between the '<code>!</code>' and '<code>(</code>', but instead let's fix it by removing the unnecessary subshell. In particular, <a href="https://github.com/git/git/commit/74ec8cf6747a60885e15d4c36e6b47bc37764748" rel="nofollow noreferrer">Commit 74ec8cf</a></p> </blockquote>
47,915
<p>svg is an xml based graphics and you can add JavaScripts to it. I have tried to access to the script functions defined in a svg. The script in my svg is something like this:</p> <pre><code>&lt;svg ... onload="RunScript(evt);"...&gt; &lt;script type="text/javascript"&gt; ... function RunScript(loadEvent) { // Get object in my html by id var objElement = top.document.getElementById('objid1'); if (objElement) { // Extend object tag object's methods objElement.SVGsetDimension = setDimension; ... } function setDimention(w, h) {...} </code></pre> <p>In my main html file, the svg is embedded in an object tag like this:</p> <pre><code>&lt;object id="objid1" data="mygrahic.svg" ... &gt; &lt;a href="#" onclick="document.getElementById('objid1').SVGsetDimention(10, 10); return false;" ...&gt;Set new dimention&lt;/a&gt;... </code></pre> <p>This one works fine. However if the svg xml file is referenced by a full URL (on another site) like this:</p> <pre><code>&lt;object id="objid1" data="http://www.artlibrary.net/myaccount/mygrahic.svg" ... &gt; </code></pre> <p>the codes do not work any more. It looks like that I cannot attach the method defined in my svg script to a method in my main html object tag element, or the top or document is not available in this case, or getElementById(..) just cannot find my object element in my svg script. Is there any way I can do in the svg xml script to find my html element?</p> <p>Not sure if this problem is caused by the different DOMs, and there is no way for my svg script codes to figure out another DOM's object or element. It would be nice if there is any solution.</p>
<p>I think the clue might be in 'on another site'. There are strict rules about when JavaScript programs from different sites are allowed to communicate with teach other. The embedded SVG is being treated the same way a document inside an <code>iframe</code> would.</p>
<p>From my experiense; Your Code is true ,so that run exactly. My PC Windows 7,IE9,installed Adobe Viewer. Both unless SVG Viewer,IE9 SVG drawed,but can't run SVG TAG Animation, only can run Javascript Animation. So,under Windows XP,IE8,installed Adobe SVG Viewer, Same result(run exactly).</p> <p>Firefox SVG can't run(SVG ecmascript animation) exactly under my PC.</p>
30,754
<p>I'm wondering if there is a "best" choice for collation in MySQL for a general website where you aren't 100% sure of what will be entered? I understand that all the encodings should be the same, such as MySQL, Apache, the HTML and anything inside PHP.</p> <p>In the past I have set PHP to output in "UTF-8", but which collation does this match in MySQL? I'm thinking it's one of the UTF-8 ones, but I have used <code>utf8_unicode_ci</code>, <code>utf8_general_ci</code>, and <code>utf8_bin</code> before.</p>
<p>The main difference is sorting accuracy (when comparing characters in the language) and performance. The only special one is utf8_bin which is for comparing characters in binary format.</p> <p><code>utf8_general_ci</code> is somewhat faster than <code>utf8_unicode_ci</code>, but less accurate (for sorting). The <em>specific language utf8 encoding</em> (such as <code>utf8_swedish_ci</code>) contain additional language rules that make them the most accurate to sort for those languages. Most of the time I use <code>utf8_unicode_ci</code> (I prefer accuracy to small performance improvements), unless I have a good reason to prefer a specific language.</p> <p>You can read more on specific unicode character sets on the MySQL manual - <a href="http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html</a></p>
<p>In your database upload file, add the followin line before any line:</p> <pre><code>SET NAMES utf8; </code></pre> <p>And your problem should be solved.</p>
47,993
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
<p>Using <a href="http://www.python.org/doc/2.5.2/lib/module-cPickle.html" rel="noreferrer">cPickle</a> on the dictionary would be my choice. Dictionaries are a natural fit for these kind of data, so given your requirements I see no reason not to use them. That, unless you are thinking about reading them from non-python applications, in which case you'd have to use a language neutral text format. And even here you could get away with the pickle plus an export tool.</p>
<p>If you have a database, I might suggest storing the settings in the database. However, it sounds like ordinary files might suit your environment better.</p> <p>You probably don't want to store <em>all</em> the users settings in the same file, because you might run into trouble with concurrent access to that one file. If you stored each user's settings as a dictionary in their own pickled file, then they would be able to act independently.</p> <p>Pickling is a reasonable way to store such data, but unfortunately the pickle data format is notoriously not-human-readable. You might be better off storing it as <code>repr(dictionary)</code> which will be a more readable format. To reload the user settings, use <code>eval(open("file").read())</code> or something like that.</p>
24,477
<p>How do you convert decimal values to their hexadecimal equivalent in JavaScript?</p>
<p>Convert a number to a hexadecimal string with:</p> <pre><code>hexString = yourNumber.toString(16); </code></pre> <p>And reverse the process with:</p> <pre><code>yourNumber = parseInt(hexString, 16); </code></pre>
<p>Here's my solution:</p> <pre><code>hex = function(number) { return '0x' + Math.abs(number).toString(16); } </code></pre> <p>The question says: <em>"How to convert decimal to hexadecimal in JavaScript"</em>. While, the question does not specify that the hexadecimal string should begin with a 0x prefix, anybody who writes code should know that 0x is added to hexadecimal codes to distinguish <em>hexadecimal codes</em> from <em>programmatic identifiers</em> and <em>other numbers</em> (1234 could be hexadecimal, decimal, or even octal).</p> <p>Therefore, to correctly answer this question, for the purpose of script-writing, you must add the 0x prefix.</p> <p>The Math.abs(N) function converts negatives to positives, and as a bonus, it doesn't look like somebody ran it through a wood-chipper.</p> <p>The answer I wanted, would have had a field-width specifier, so we could for example show 8/16/32/64-bit values the way you would see them listed in a hexadecimal editing application. That, is the actual, correct answer.</p>
8,221
<p>Is there any way to change the entire width of the horizontal scroll bar on a scrolling div (including the nudge arrows and the handle).</p> <p>EDIT: I only need an IE7 solution - it's for a scrolling DIV on a touch screen terminal</p> <p>Thanks</p> <p>Matt</p>
<p>Actually, I revise my statement... <strong>in IE7</strong>, you <strong>CAN</strong> do some scaling.</p> <pre><code>&lt;div style="zoom:5;font-size:20%;overflow-x:auto;"&gt; Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! &lt;/div&gt; </code></pre> <p>zoom tells IE to scale up the contents by 500%, and I've set the font-size to be 1/5 of normal (thus remain the same)... this scales the scrollbars (but it looks a bit ugly at this zoom, since the images are raster based, not vector based.</p>
<p>There is a way, but it's IMO not possible with JS or CSS.</p> <p>If you have access to the terminal in question, you can set the theme property to have a larger scrollbar. It's at Control Panels -> Display -> tab Appearance -> Advanced -> item Scrollbar -> adjust size as desired (<a href="http://i33.tinypic.com/idt7x1.png" rel="nofollow noreferrer">screenshot</a>)</p>
32,366
<p>I have a database table named call with columns call_time, location, emergency_type and there are three types of emergency: paramedics, police and firefighters. In the windows form I created CheckBoxes 'paramedics', 'police', 'firefighters' and I want to retrieve all table columns which meet user's selection.</p> <p>I created a function:</p> <pre><code>public static DataTable GetHistory(DateTime from, DateTime to, bool paramedics, bool police, bool firefighters) { string select = "SELECT call_time, location, emergency_type where call_time between @from AND @to AND"; if(paramedics) { select += " emergency_type = 'paramedics' "; } if(paramedics &amp;&amp; police) { select +=" emergency_type = 'paramedics' OR emergency_type = 'police'; } ... } </code></pre> <p>This code however seems very dirty because if there were 30 kinds of emergency there would be 30! combinations and I would get old before writing all if statements.</p> <p>I would appreciate if you shared your practice for retrieving data that meet the selected search conditions if there are many options you can chosse.</p> <p>Thanks!</p>
<p>Well if you have to use emergency_type as a string then instead of passing in bools you could send in a List containing the text representation of the emergency type. For example to adjust the above code you could change the method signature to</p> <pre><code>public static DataTable GetHistory(DateTime from, DateTime to, List&lt;string&gt; types) { .. } </code></pre> <p>and then pass in a list that looked like these (for example)</p> <pre><code>List&lt;string&gt; types = new List&lt;string&gt; { "paramedics" }; or List&lt;string&gt; types = new List&lt;string&gt; { "paramedics", "police" }; </code></pre> <p>Then you could adapt your query to use the SQL IN statement in your where clause. Next convert the list of strings into a comma separated string like</p> <pre><code>string values = "'paramedics', 'police'" </code></pre> <p>A simple way to create the values variable is to use</p> <pre><code>string values = string.Empty; types.ForEach(s =&gt; { if (!string.IsNullOrEmpty(values)) values += ","; values += string.Format("'{0}'", s); }); </code></pre> <p>By the way you could use a parameterized command to avoid SQL injection. Once you have the string you can simply do</p> <pre><code>string select = "SELECT call_time, location, emergency_type where call_time between @from AND @to AND emergency_type IN " + values </code></pre>
<p>This is a dirty way of doing this.</p> <pre><code>string select = "SELECT call_time, location, emergency_type where call_time between @from AND @to AND (1=0"; if(paramedics) { select += " OR emergency_type = 'paramedics' "; } if(police) { select += " OR emergency_type = 'police'"; } if(xyz) { select += " OR emergency_type = 'xyz'"; } select += ")"; </code></pre>
31,900
<p>Does anyone know of any methods to create a file upload progress bar in PHP? I have often heard that it's impossible.</p> <p>I have one idea, but not sure if it would work: have a normal file upload, but instead submit to an iframe. When this is submitted, store the file information (size and temp location) in the session. At the same time, start an AJAX call to every say 10 seconds to check the size of the file compared to the size stored in the session. This would return the size to the AJAX and then a progress bar would be sized and maybe display the uploaded size to the user.</p> <p>Thoughts?</p>
<p>You're pretty much figured out how to do it. The main problem is you usually don't have access to the size of the uploaded file until it's done uploading.</p> <p>There are workarounds for this: Enabling APC, you to access this information if you include a field called "APC_UPLOAD_PROGRESS" and use apc_fetch() for retrieving a cache entry with the status.</p> <p>There's also a plugin called uploadprogress but it's not very well documented and doesn't work on Windows (last I checked anyway).</p> <p>An alternative is to use Flash for doing it. See scripts like <a href="http://digitarald.de/project/fancyupload/" rel="nofollow noreferrer">FancyUpload</a>.</p> <p>Before APC came along I had to write a CGI script in C that wrote information to a text file. APC seems like a much better way to do it now though.</p> <p>Hope this helps.</p>
<p>In pure PHP, you are correct: it's not possible.</p> <p>If you AJAX-ify this, then you could do what you're describing. The only progress meters I've ever seen are in Javascript or Flash, though I imagine Silverlight could do it also.</p>
19,218
<p>We want to show a hint for a JList that the user can select multiple items with the platform dependent key for multiselect. </p> <p>However I have not found any way to show the OS X COMMAND symbol in a JLabel, which means the symbol that's printed on the apple keyboard on the command key, also called apple key.</p> <p>Here's a picture of the symbol I want to display on OS X. <a href="https://i.stack.imgur.com/VKGb4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VKGb4.png" alt="COMMAND SYMBOL"></a><br> <sub>(source: <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Command_key.svg/120px-Command_key.svg.png" rel="nofollow noreferrer">wikimedia.org</a>)</sub> </p> <p>Also I do want to have it platform independent.</p> <p>I.e. something like </p> <pre><code>component.add( new JList() , BorderLayout.CENTER ); component.add( new JLabel( MessageFormat.format("With {0} you can " + "select multiple items", KeyStroke.getKeyStroke( ... , ... ) ) ) , BorderLayout.SOUTH ); </code></pre> <p>Where instead of the <em>{0}</em> there should appear above seen symbol...</p> <p>Does any one of you guys know how to do this? I know it must be possible somehow since in the JMenuItems there is the symbol...</p> <p>My own (non graphical solutions) looks like this:</p> <pre><code>add( new JLabel( MessageFormat.format( "With {0} you can select multiple items" , System.getProperty( "mrj.version" ) != null ? "COMMAND" : "CTRL" ) ) , BorderLayout.SOUTH ); </code></pre>
<p>The symbol in question is avaiable through Unicode, and the HTML character sets. All you need to do is make your JLabel display HTML by starting its text string with &lt;html&gt; and then include the character code.</p> <pre><code>JLabel label = new JLabel( "&lt;html&gt;&amp;#8984; is the Apple command symbol." ); </code></pre> <p>This will work on a Mac, but I've no idea what it'll do on other platforms, although you do seem to have that covered off.</p>
<p>Your solution looks perfect. I assume you intend to factor out the hint code so you reuse it.</p> <pre><code>add( new JLabel( MessageFormat.format( "With {0} you can select multiple items", getMetaKeyHint(), BorderLayout.SOUTH ); public String getMetaKeyHint() { return System.getProperty( "mrj.version" ) != null ? "COMMAND" : "CTRL" ); } </code></pre>
28,349
<p>Is there any way for a DBA to peek in on the execution plan of a long-running query in SQL Server 2000? I know how to get the SQL being run using fn_get_sql(). And yes, theoretically if open a new connection and set the environment flags the same, it should generate the same plan for the SQL. However, I'm in a data warehouse environment and this query has run for 12 hours with a data load in between, so there's no guarantee that the new plan would match the old plan. I just want to know exactly what the server is doing.</p> <p>And no, I'm certainly not going to kill the currently running statement unless I can see the plan and know for certain that I can do better with index and join hints.</p> <p>UPDATE: I feel so close, but I still think it can be done. It can definitely be done in 2K5 and later. If you look at the syscacheobjects virtual table, there are object ids for every cached plan. You can call sp_OA* methods on these ids, but without knowledge of the object model (which is proprietary), I can't get anywhere.</p>
<p>I don't think you can do such a thing, it needs to be submitted to the server with the original query: </p> <p><a href="http://msdn.microsoft.com/en-us/library/aa178303(SQL.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa178303(SQL.80).aspx</a> . </p> <p>You could load up the query and get the estimated execution plan.</p>
<p>Maybe...</p> <p>Run profiler, and expand the "performance" events node. Choose one of the SHOWPLAN options.</p> <p>Hopefully, you will be able to trap the end of execution. I know you can log query plans, but I don't know if it works in this case.</p> <p>I don't have SQL 2k profiler, only 2k5, to test something or see the options.</p>
46,504
<p>I want a list of hyperlinks on a basic html page, which point to files on our corporate intranet.</p> <p>When a user clicks the link, I want the file to open. They are excel spreadsheets, and this is an intranet environment, so I can count on everyone having Excel installed.</p> <p>I've tried two things:</p> <ol> <li>The obvious and simple thing:</li> </ol> <pre class="lang-html prettyprint-override"><code>&lt;a href="file://server/directory/file.xlsx"&gt;Click me!&lt;/a&gt; </code></pre> <ol start="2"> <li>A <a href="/questions/tagged/vbscript" class="post-tag" title="show questions tagged &#39;vbscript&#39;" rel="tag">vbscript</a> option that I found in a Google search:</li> </ol> <pre class="lang-html prettyprint-override"><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;SCRIPT LANGUAGE=VBScript&gt; Dim objExcel Sub Btn1_onclick() call OpenWorkbook("\\server\directory\file.xlsx") End Sub Sub OpenWorkbook(strLocation) Set objExcel = CreateObject("Excel.Application") objExcel.Visible = true objExcel.Workbooks.Open strLocation objExcel.UserControl = true End Sub &lt;/SCRIPT&gt; &lt;TITLE&gt;Launch Excel&lt;/Title&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;INPUT TYPE=BUTTON NAME=Btn1 VALUE="Open Excel File"&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>I know this is a very basic question, but I would appreciate any help I can get.</p> <p><strong><em>Edit: Any suggestions that work in both IE and Firefox?</em></strong></p>
<p>Try formatting the link like this (looks hellish, but it works in Firefox 3 under Vista for me) :</p> <pre><code>&lt;a href="file://///SERVER/directory/file.ext"&gt;file.ext&lt;/a&gt; </code></pre>
<p>Your first idea used to be the way but I've also noticed issues doing this using Firefox, try a straight http:// to the file - href='<a href="http://server/directory/file.xlsx" rel="nofollow noreferrer">http://server/directory/file.xlsx</a>'</p>
12,707
<p>I have a base URL :</p> <pre><code>http://my.server.com/folder/directory/sample </code></pre> <p>And a relative one :</p> <pre><code>../../other/path </code></pre> <p>How to get the absolute URL from this ? It's pretty straighforward using string manipulation, but I would like to do this in a secure way, using the <code>Uri</code> class or something similar.</p> <p>It's for a standard a C# app, not an ASP.NET one.</p>
<pre><code>var baseUri = new Uri("http://my.server.com/folder/directory/sample"); var absoluteUri = new Uri(baseUri,"../../other/path"); </code></pre> <p>OR</p> <pre><code>Uri uri; if ( Uri.TryCreate("http://base/","../relative", out uri) ) doSomething(uri); </code></pre>
<p>Some might be looking for Javascript solution that would allow conversion of urls 'on the fly' when debugging </p> <pre><code>var absoluteUrl = function(href) { var link = document.createElement("a"); link.href = href; return link.href; } </code></pre> <p>use like: </p> <p><code>absoluteUrl("http://google.com")</code></p> <blockquote> <p><code>http://google.com/</code></p> </blockquote> <p>or</p> <p><code>absoluteUrl("../../absolute")</code></p> <blockquote> <p><code>http://stackoverflow.com/absolute</code></p> </blockquote>
15,683
<p>How do I segment a 2D image into blobs of similar values efficiently? The given input is a n array of integer, which includes hue for non-gray pixels and brightness of gray pixels.</p> <p>I am writing a virtual mobile robot using Java, and I am using segmentation to analyze the map and also the image from the camera. This is a well-known problem in <a href="http://en.wikipedia.org/wiki/Computer_vision" rel="nofollow noreferrer">Computer Vision</a>, but when it's on a robot performance does matter so I wanted some inputs. Algorithm is what matters, so you can post code in any language.</p> <ul> <li>Wikipedia article: <a href="http://en.wikipedia.org/wiki/Segmentation_%28image_processing%29" rel="nofollow noreferrer">Segmentation (image processing)</a></li> <li><a href="http://robots.stanford.edu/cs223b04/CS%20223-B%20L11%20Segmentation.ppt" rel="nofollow noreferrer">[PPT] Stanford CS-223-B Lecture 11 Segmentation and Grouping</a> (which says Mean Shift is perhaps the best technique to date)</li> <li><a href="http://www.caip.rutgers.edu/~comanici/MSPAMI/msPamiResults.html" rel="nofollow noreferrer">Mean Shift Pictures</a> (paper is also available from <a href="http://www.caip.rutgers.edu/~comanici/" rel="nofollow noreferrer">Dorin Comaniciu</a>)</li> </ul>
<p>I would downsample,in colourspace and in number of pixels, use a vision method(probably meanshift) and upscale the result.</p> <p>This is good because downsampling also increases the robustness to noise, and makes it more likely that you get meaningful segments.</p> <p>You could use floodfill to smooth edges afterwards if you need smoothness.</p> <p>Some more thoughts (in response to your comment).</p> <p>1) Did you blend as you downsampled? y[i]=(x[2i]+x[2i+1])/2 This should eliminate noise.</p> <p>2)How fast do you want it to be?</p> <p>3)Have you tried dynamic meanshift?(also google for dynamic x for all algorithms x)</p>
<p>What I have now:</p> <ol> <li>Make a buffer of the same size as the input image, initialized to <code>UNSEGMENTED</code>.</li> <li><p>For each pixel in the image where the corresponding buffer value is not <code>UNSEGMENTED</code>, flood the buffer using the pixel value.</p> <p>a. The border checking of the flooding is done by checking if pixel is within <code>EPSILON</code> (currently set to 10) of the originating pixel's value.</p> <p>b. <a href="http://en.wikipedia.org/wiki/Flood_fill#Alternative_implementations" rel="nofollow noreferrer">Flood filling algorithm</a>.</p></li> </ol> <p>Possible issue:</p> <p>The 2.a.'s border checking is called many times in the flood filling algorithm. I could turn it into a lookup if I could precalculate the border using edge detection, but that may add more time than current check.</p> <pre><code>private boolean isValuesCloseEnough(int a_lhs, int a_rhs) { return Math.abs(a_lhs - a_rhs) &lt;= EPSILON; } </code></pre> <p>Possible Enhancement:</p> <p>Instead of checking every single pixel for <code>UNSEGMENTED</code>, I could randomly pick a few points. If you are expecting around 10 blobs, picking random points in that order may suffice. Drawback is that you might miss a useful but small blob.</p>
46,319
<p>The following snippet is supposed to take the value of PROJECT (defined in the Makefile) and create an include file name. For example, if PROJECT=classifier, then it should at the end generate classifier_ir.h for PROJECTINCSTR</p> <p>I find that this code works as long as I am not trying to use an underscore in the suffix. However the use of the underscore is not optional - our code base uses them everywhere. I can work around this because there are a limited number of values for PROJECT but I would like to know how to make the following snippet actually work, with the underscore. Can it be escaped?</p> <pre><code>#define PROJECT classifier #define QMAKESTR(x) #x #define MAKESTR(x) QMAKESTR(x) #define MAKEINC(x) x ## _ir.h #define PROJECTINC MAKEINC(PROJECT) #define PROJECTINCSTR MAKESTR(PROJECTINC) #include PROJECTINCSTR </code></pre> <p>Edit: The compiler should try to include classifier_ir.h, not PROJECT_ir.h.</p>
<pre><code>#define QMAKESTR(x) #x #define MAKESTR(x) QMAKESTR(x) #define SMASH(x,y) x##y #define MAKEINC(x) SMASH(x,_ir.h) #define PROJECTINC MAKEINC(PROJECT) #define PROJECTINCSTR MAKESTR(PROJECTINC)</code></pre>
<p>That barebone example works with gcc (v4.1.2) and tries to include "PROJECT_ir.h"</p>
17,152
<p>I'm in the process of moving one of our projects from VS6 to VS2008 and I've hit the following compile error with mshtml.h:</p> <pre><code>1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5272) : error C2143: syntax error : missing '}' before 'constant' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C2143: syntax error : missing ';' before '}' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2143: syntax error : missing ';' before '}' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}' </code></pre> <p>Following the first error statement drops into this part of the mshtml.h code, pointing at the "True = 1" line:</p> <pre><code>EXTERN_C const GUID CLSID_CDocument; EXTERN_C const GUID CLSID_CScriptlet; typedef enum _BoolValue { True = 1, False = 0, BoolValue_Max = 2147483647L } BoolValue; EXTERN_C const GUID CLSID_CPluginSite; </code></pre> <p>It looks like someone on expert-sexchange also came across this error but I'd rather not dignify that site with a "7 day free trial".</p> <p>Any suggestions would be most welcome.</p>
<p>There is probably a #define changing something. Try running just the preprocessor on your .cpp and generating a .i file. The setting is in the project property pages.</p> <p>EDIT: Also, you can get the answer from that other expert site by scrolling to the bottom of the page. They have to do that or Google will take them out of their indexes.</p>
<p>What other incodes do ou have in the currently compiling file? It may be that <code>True</code> has been defined by a macro already as <code>1</code>. That would explain the error.</p>
14,456
<p>I'm making a simple 2 player game in XNA and started looking into saving the player's high scores.</p> <p>I want the game to work on the XBox 360 as well as Windows, so I have to use the framework to save the data.</p> <p>It seems that you save data to a particular user's gamer tag - so my question is, what to do with high scores?</p> <ul> <li>Save the user's own scores in their profile? (So you can only see your own scores if you're the only one signed in)</li> <li>Try and save other player's scores in all profiles? (Seems like a pain to try and keep this sync'd)</li> <li>Store scores online <ul> <li>The 360 seems to have a standard method for showing friend's high scores. Can this be accessed from within XNA, or is it only available to published games?</li> <li>Roll my own. (Seems excessive for such a small personal project.)</li> </ul></li> </ul>
<p>You're right -- looks like Eclipse has acknowledged it as a <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=199499" rel="nofollow noreferrer">bug</a>. It's fixed in 3.5.</p>
<p>I was initially thinking <kbd>Alt</kbd>-<kbd>←</kbd> and <kbd>Alt</kbd>-<kbd>→</kbd> might do what you want, but that's more for going forward and backwards in history of tabs you've viewed. Which might sort of get you what you want, but is probably just as confusing as <kbd>Alt</kbd>-<kbd>F6</kbd>.</p> <p>I think it sounds more like a bug in Eclipse, might be worth going over to eclipse.org to see if there's a pre-existing bug for this.</p>
8,698
<p>Before I upgraded to Firefox 3 I used to constantly use the <a href="https://addons.mozilla.org/en-US/firefox/addon/655" rel="nofollow noreferrer">View Source Chart Firefox Addon</a> which shows the source HTML in a very organized, graphical form. Unfortunately, this addon is only for Firefox 2 and the beta version for Firefox 3 now costs $10 on the author's site. </p> <p>Anyone know of a similar addon that works for Firefox 3?</p> <p>(of course, I might indeed pay $10 for this, but first want to ask around if there isn't anything better and free, as the version for Firefox 2 had its limitations and I don't really want to pay $10 for something in beta that I can't test out before paying for it.)</p>
<p>Is <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow noreferrer">Firebug</a> not sufficient?</p>
<p>You could always try Firefug. It sounds like it does a similar thing, plus more :)</p>
6,947
<p>What I'd like to accomplish is to present charts on webpages. For example aspx pages gridviews that present a two column table are able to be copied &amp; placed into Excel then a chart created. The pages I currently use most are ASP.NET 3.0 or SharePoint team sites with stored procedures. People are very interested in how people perform chats in webpages. </p> <p>Thanks in advance, Catto</p>
<p>The Google Chart API makes it easy to embed charts into web pages. No server-side install needed, at all.</p> <p><a href="http://code.google.com/apis/chart/" rel="nofollow noreferrer">http://code.google.com/apis/chart/</a></p>
<p>So you want to maybe export the GridView to MS Excel which should I can imagine contain a generated macro to generate the chart on the data. Something like that you mean. Or do you just want to get the data from the website into excel? i.e. CSV format is really simple to accomplish. For the Excel format, this is also possible and in my opinion good fun. I would imagine you can also generate the macros through C# tp embed in the generated Excel file.</p> <p>Andrew</p>
26,601
<p>I've recently been working on a beginner's project in Scala, and have a beginner question about Scala's Lists.</p> <p>Say I have a list of tuples ( <code>List[Tuple2[String, String]]</code>, for example). Is there a convenience method to return the first occurence of a specified tuple from the List, or is it necessary to iterate through the list by hand?</p>
<pre> scala> val list = List(("A", "B", 1), ("C", "D", 1), ("E", "F", 1), ("C", "D", 2), ("G", "H", 1)) list: List[(java.lang.String, java.lang.String, Int)] = List((A,B,1), (C,D,1), (E,F,1), (C,D,2), (G,H,1)) scala> list find {e => e._1 == "C" && e._2 == "D"} res0: Option[(java.lang.String, java.lang.String, Int)] = Some((C,D,1)) </pre>
<p>You could also do this, which doesn't require knowing the field names in the Tuple2 class--it uses pattern matching instead:</p> <pre><code>list find { case (x,y,_) =&gt; x == "C" &amp;&amp; y == "D" } </code></pre> <p>"find" is good when you know you only need one; if you want to find all matching elements you could either use "filter" or the equivalent sugary for comprehension:</p> <pre><code>for ( (x,y,z) &lt;- list if x == "C" &amp;&amp; y == "D") yield (x,y,z) </code></pre>
7,759
<p>I just wanna ask what would be better approach to supply these objects in my unit tests.</p> <p>In my unit test I am testing CSLA object. CSLA object is internally using one property and one method of ApplicationUser object. ApplicationUser is inherited from IPrincipal. The properties are: 1) ApplicationContext.User.IsInRole(...) - the method is part of IPrincipal 2) ApplicationContext.User.Identity.Name - the name is property of IIdentity which is part of ApplicationUser aka IPricipal</p> <p>Example of my test (using RhinoMock):</p> <pre><code>public void BeforeTest() { mocks = new MockRepository(); IPrincipal mockPrincipal = mocks.CreateMock&lt;IPrincipal&gt;(); ApplicationContext.User = mockPrincipal; using (mocks.Record()) { Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true); Expect.Call(mockPrincipal.Identity.Name).Return("ju"); //doesn't work!!!! return null ref exc } } </code></pre> <p>I have slight problem with second value, the identity name. I tried to mock it but have problem to assign mocked IIdentity to ApplicationUser, as it is done internaly. I was told to just create some IIPrincipal (including IIdentity) by myself and not to mock it at all. Which can be done for sure. Not sure if this can be called as Stub using?</p> <p>So can you advice me how to deal with IPrincipal and IIdentity? Any suggestion most welcome.</p>
<p>The reason you're getting a null reference error is because <code>IPrincipal.Identity</code> is null; it hasn't been set in your mocked <code>IPrincipal</code> yet. Calling <code>.Name</code> the null <code>Identity</code> results in your exception.</p> <p>The answer, as Carlton pointed out, is to mock <code>IIdentity</code> <em>also</em>, and set it up to return "ju" for its <code>Name</code> property. Then you can tell <code>IPrincipal.Identity</code> to return the mock <code>IIdentity</code>.</p> <p>Here is an expansion of your code to do this (using Rhino Mocks rather than Stubs):</p> <pre><code>public void BeforeTest() { mocks = new MockRepository(); IPrincipal mockPrincipal = mocks.CreateMock&lt;IPrincipal&gt;(); IIdentity mockIdentity = mocks.CreateMock&lt;IIdentity&gt;(); ApplicationContext.User = mockPrincipal; using (mocks.Record()) { Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true); Expect.Call(mockIdentity.Name).Return("ju"); Expect.Call(mockPrincipal.Identity).Return(mockIdentity); } } </code></pre>
<p>Here is the code I use to return a test user (using Stubs):</p> <pre><code> [SetUp] public void Setup() { var identity = MockRepository.GenerateStub&lt;IIdentity&gt;(); identity.Stub(p =&gt; p.Name).Return("TestUser").Repeat.Any(); var principal = MockRepository.GenerateStub&lt;IPrincipal&gt;(); principal.Stub(p =&gt; p.Identity).Return(identity).Repeat.Any(); Thread.CurrentPrincipal = principal; } </code></pre> <p>I've got linq in other code so I'm using the var type for the variables; just substitute the correct types (IPrincipal, IIdentity) if needed.</p>
19,652
<p>I have an XmlDocument that already exists and is read from a file. </p> <p>I would like to add a chunk of Xml to a node in the document. Is there a good way to create and add all the nodes without cluttering my code with many .CreateNote and .AppendChild calls?</p> <p>I would like some way of making a string or stringBuilder of a valid Xml section and just appending that to an XmlNode.</p> <p>ex: Original XmlDoc:</p> <pre><code>&lt;MyXml&gt; &lt;Employee&gt; &lt;/Employee&gt; &lt;/MyXml&gt; </code></pre> <p>and, I would like to add a Demographic (with several children) tag to Employee:</p> <pre><code>&lt;MyXml&gt; &lt;Employee&gt; &lt;Demographic&gt; &lt;Age/&gt; &lt;DOB/&gt; &lt;/Demographic&gt; &lt;/Employee&gt; &lt;/MyXml&gt; </code></pre>
<p>I suggest using <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createdocumentfragment.aspx" rel="noreferrer">XmlDocument.CreateDocumentFragment</a> if you have the data in free form strings. You'll still have to use AppendChild to add the fragment to a node, but you have the freedom of building the XML in your StringBuilder.</p> <pre><code>XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(@"&lt;MyXml&gt;&lt;Employee&gt;&lt;/Employee&gt;&lt;/MyXml&gt;"); XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment(); xfrag.InnerXml = @"&lt;Demographic&gt;&lt;Age/&gt;&lt;DOB/&gt;&lt;/Demographic&gt;"; xdoc.DocumentElement.FirstChild.AppendChild(xfrag); </code></pre>
<p>All that I do is creating a new dataset object and open the xml file using ReadXML <code>myDataset.ReadXML(path and file name)</code>. </p> <p>Then add or remove the rows that I need and save the document again using <code>myDataset.WriteXML(path and file name)</code>.</p> <p>Bye.</p>
21,606
<p>Following on from a <a href="https://stackoverflow.com/questions/221417/how-do-i-programmatically-access-the-target-path-of-a-windows-symbolic-link">previous question</a>, I am creating a symbolic link on a Server 2008 from a Vista machine using UNC paths. I can create the link just fine. I can go to the Server 2008 box and double click on the link in explorer to open the target file. What I cannot do though is use FileCreateW to get a handle to the UNC path link (from the Vista box). When I try it, it fails and GetLastError() returns error code 1463 (0x5B7), which is:</p> <blockquote> <p>The symbolic link cannot be followed because its type is disabled.</p> </blockquote> <p>How to enable its "type" in Server 2008 (assuming the error means what it says)?</p>
<p>To add to <a href="https://stackoverflow.com/a/230047/45375">@David Arno's helpful answer</a>, based on W7:</p> <hr /> <p><code>fsutil.exe</code> can be made to show what arguments it takes by simply running:</p> <pre><code>fsutil behavior set /? </code></pre> <p>To <strong>report the <em>current</em> configuration</strong>, run <code>fsutil behavior query SymlinkEvaluation</code> - see <a href="https://stackoverflow.com/a/24364595/45375">@Jake1164's answer</a>, particularly with respect to how a <strong>group policy</strong> may be controlling the behavior.</p> <p>The <strong>symbolic-link resolution behavior is set on the machine that <em>accesses</em> a given link</strong>, not the machine that hosts it.</p> <p>The <strong>behavior codes</strong> for <code>fsutil behavior set SymlinkEvaluation</code> - namely <code>L2L</code>, <code>L2R</code>, <code>R2L</code>, and <code>R2R</code> - mean the following:</p> <ul> <li><code>L</code> stands for &quot;Local&quot;, and <code>R</code> for &quot;Remote&quot;</li> <li>The FIRST <code>L</code> or <code>R</code> - <em>before</em> the <code>2</code> - refers to the location of the link itself (as opposed to its target) <em>relative to the machine ACCESSING the link</em>.</li> <li>The SECOND <code>L</code> or <code>R</code> - <em>after</em> the <code>2</code> - refers to the location of the link's <em>target relative to the machine where the LINK itself is located</em>.</li> </ul> <p>Thus, for instance, executing <code>fsutil behavior set SymlinkEvaluation R2L</code> means that you can access links:</p> <ul> <li>located on a remote machine (<code>R</code>)</li> <li>that point to targets on that same remote machine (<code>L</code>)</li> </ul> <hr /> <p>Unlike what David experienced on Vista, I, on W7, was able to resolve a remote link that pointed to a resource on another remote machine by enabling R2R alone (and not also having to enable R2L).</p>
<p>Remote junction points work by default. For files you still need symlinks.</p>
28,429
<p>I'm thinking that the reason I can't do this is because it might be a huge security hole, but here goes...</p> <p>I want to have a bookmark on my browser (FF3, preferably) that is only a snippet of javascript code. It would merely construct a URL based on the current date and then do a window.location = on that URL.</p> <p>I know that I could make a page and keep it on my local machine and just refer to it that way, but I was just wondering if you could bypass that step and actually have the "location" of the bookmark really just be javascript. I could have sworn that this was possible years ago, but I can't find anything that tells me either way now.</p>
<p>What you want is a <a href="http://en.wikipedia.org/wiki/Bookmarklet" rel="noreferrer">bookmarklet</a> they are easy to create and should work in most major browsers.</p> <p>Edit: Stack overflow seems not to allow creating bookmarklets in the context of the site, basically you can create a new bookmark and type the following in the location field</p> <pre>javascript:window.location='http://www.google.com/search?q='+Date()</pre> <p>to get a bookmarklet that searches google for the current date.</p>
<p>Well, I just created a bookmark in FF3, went back and updated it and added the following test:</p> <pre><code>javascript:alert('Wacky%20test%20yo'); </code></pre> <p>Low and behold, after I saved and loaded, I was able to get my alert.</p> <p>I'm sure you can work up something similar for your needs.</p>
3,057
<p>From a HTML application (<code>.hta file</code>), you can drag any image and drop it into the desktop for example.</p> <p>Does anybody know how to disable this capability?</p> <p>I want the <code>.hta</code> files to have the same behavior as the <code>.html</code> files.</p>
<p>Have a look at the <a href="http://pages.cs.wisc.edu/~bart/fuzz/" rel="nofollow noreferrer">Fuzz Testing of Application Reliability</a> website of the University of Wisconsin. They did a research study some years ago to test the reliability of desktop software and on that page you find a link to their FTP site providing fuzz testing tools.</p> <p>I've used the fuzz-nt tool from that site for my own tests and successfully found several bugs in our application. It has no option to choose the keyboard input values (but source is provided). Instead it lets you choose from these sources of random data:</p> <ul> <li>random keyboard events</li> <li>random mouse events</li> <li>random windows events (to be used with care or better not at all)</li> </ul>
<p>Here's a pseudocode (since you didn't mention the language you're using):</p> <ul> <li>Create an array that contains the alphabet from a-z, A-Z, 0-9 (depending on what keys you wish to send)</li> <li>for i = 0 to NumberOfKeyStrokes</li> <li>rand() % SizeOfArray</li> <li>delay for rand() milliseconds (the lower the range, the faster the key strokes are)</li> <li>send via an API or as a string</li> </ul> <p>For more information on sending a keystrike to an application on windows, research the API FindWindow and SendMessage</p>
29,635
<p>I have an asp.net website that allows the user to download largish files - 30mb to about 60mb. Sometimes the download works fine but often it fails at some varying point before the download finishes with the message saying that the connection with the server was reset.</p> <p>Originally I was simply using Server.TransmitFile but after reading up a bit I am now using the code posted below. I am also setting the Server.ScriptTimeout value to 3600 in the Page_Init event.</p> <pre><code>private void DownloadFile(string fname, bool forceDownload) { string path = MapPath(fname); string name = Path.GetFileName(path); string ext = Path.GetExtension(path); string type = ""; // set known types based on file extension if (ext != null) { switch (ext.ToLower()) { case ".mp3": type = "audio/mpeg"; break; case ".htm": case ".html": type = "text/HTML"; break; case ".txt": type = "text/plain"; break; case ".doc": case ".rtf": type = "Application/msword"; break; } } if (forceDownload) { Response.AppendHeader("content-disposition", "attachment; filename=" + name.Replace(" ", "_")); } if (type != "") { Response.ContentType = type; } else { Response.ContentType = "application/x-msdownload"; } System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000]; // Length of the file: int length; // Total bytes to read: long dataToRead; try { // Open the file. iStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; //Response.ContentType = "application/octet-stream"; //Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); // Read the bytes. while (dataToRead &gt; 0) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception ex) { // Trap the error, if any. Response.Write("Error : " + ex.Message); } finally { if (iStream != null) { //Close the file. iStream.Close(); } Response.Close(); } } </code></pre>
<p>Will</p> <pre><code>&lt;configuration&gt; &lt;system.web&gt; &lt;httpRuntime executionTimeout="3600"/&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>help anything?</p> <p>The inner loop that writes the data seems a bit convoluted, I would at least change it to:</p> <pre><code>int length; while( Response.IsClientConnected &amp;&amp; (length=iStream.Read(buffer,0,buffer.Length))&gt;0 ) { Response.OutputStream.Write(buffer,0,length); Response.Flush(); } </code></pre> <p>There is no need to reallocate the buffer each round through the loop, you can simply re-use it after you have written it to the output.</p> <p>A further improvement would be to use asyncronous IO but that is for another day.</p>
<p>What ended up working for me is doing a Response.End and also doing a using statement with the file stream. Here is the code that I have:</p> <pre><code>public partial class ssl_Report_StreamReport : BaseReportPage { protected void Page_Load(object sender, EventArgs e) { //Get the parameters string reportName = Utils.ParseStringRequest(Request, "reportName") ?? string.Empty; string reportGuid = Session["reportGuid"].ToString(); string path = Path.Combine(ReportPath(), Utils.GetSessionReportName(reportName, reportGuid)); using (var fileStream = File.Open(path, FileMode.Open)) { Response.ClearHeaders(); Response.Clear(); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=\"" + reportName + "\""); Response.AddHeader("Content-Length", fileStream.Length.ToString(CultureInfo.InvariantCulture)); StreamHelper.CopyStream(fileStream, Response.OutputStream); Response.Flush(); Response.End(); } ReportProcessor.ClearReport(Session.SessionID, path); } } public static class StreamHelper { public static void CopyStream(Stream input, Stream output) { byte[] buffer = new byte[32768]; int read; while ((read = input.Read(buffer, 0, buffer.Length)) &gt; 0) { output.Write(buffer, 0, read); } } } </code></pre>
22,638
<p>I'm on a project doing an iPhone application. We had a Cocoa consultant come in for a few weeks. He showed me an interesting idiom of Cocoa, dealing with interfaces, but there was a difficult language barrier between us, and he wasn't really able to explain <em>why</em> this was done or where it was documented so I could learn more on my own. I went into monkey see mode, and just used the style he prefers. But it's been bugging the hell out of me that I don't know more about the history of this style. It's certainly NOT an informal protocol. Sure enough, looking at <em>some</em> of the Cocoa API headers, I sometimes see the style he asserted was the 'Cocoa' way. Here's an example (note accessors, mutators, etc., each have their own interface declaration without the funny braces):</p> <pre><code>@interface AViewController : UIViewController &lt;UITextViewDelegate&gt; { @public UITableView *tableView; @private NSUInteger someIndex; } @property (nonatomic, retain) ... @end @interface AViewController (AViewControllerCreation) - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil withController:(id)controller; @end @interface AViewController (AViewControllerMutator) - (void) doSomeSettingStuff; @end @interface AViewController (AViewControllerAccessor) - (NSString *)doSomeAccessorStuff; @end @interface AViewController (AViewControllerAction) - (IBAction)cancel:(id)sender; @end @interface AViewController (AViewControllerTableViewDelegate) &lt;UITableViewDelegate, UITableViewDataSource&gt; @end </code></pre> <p>You can see this style of setting up the interface in NSButton, NSControl, etc. Interestingly, corresponding classes like UIButton, UIControl DON'T use this idiom. Hmm, these probably came after as I assume UIKit was done after AppKit. So is this idiom 'old hat'? Also, is there any reason for it other then style? Is it good style? Bad? Any docs that go over this? Thanks all.</p>
<p>These are what's known in Objective-C as "categories". Categories make it possible to have multiple @interface and @implementation blocks for the same class. This works even to the extent that you can add methods on classes in the standard Apple frameworks, e.g. adding a category on NSString to add new methods to it. Categories can add methods but not instance variables, so in your example the first @interface is the core class declaration and all of the others are categories on the AViewController class.</p> <p>It's not "old hat" by any means but your example takes the use of categories to a rather bizarre extreme. Categories make sense wherever it makes logical sense to break up a class's implementation into multiple blocks, for example if the class has a bunch of methods that logically fall into two or more groups. They're also sometimes used to declare pseudo-private methods by putting a category @interface named "private" in the same file as the @implementation. ObjC's dynamic dispatch means there's no such thing as a private method but this approach avoids publishing the names of methods you'd prefer people not to use.</p> <p>The example above is not actually wrong but it's kind of ridiculous. It suggests that the contractor got the idea that every new method should always have its own category for some reason, which is just not true.</p>
<p>I don't know; those look a lot like informal protocols to me, largely for delegates. See pages 297 - 298 of <em>Cocoa Programming with Mac OS X, 3rd Edition</em>. The protocols are implemented via Categories ... And in all honesty, they appear to be heavily overused in your sample.</p>
48,600
<p>In our application we've run into an error numerous times where we get error CS0433, which complains about a name collison in two separate dlls. This is an ASP.NET app developed in C# using webforms. It always complained about A TimeLog page. Anyone have advice for resolving this error?</p>
<p><a href="http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/aa9f90e8-534d-4e74-b656-99187eb3f281/" rel="nofollow noreferrer"> I found a link in the MSDN that describes this error.</a></p> <p>To summarize, a naming conflict can happen between the file name of a page (TimeLogTab.aspx) and the class in the code behind (public class TimeLogTab).</p> <p>The link recommends renaming one of them. I changed my class to Time_LogTab and the error went away.</p>
<p>The error can happen intermittently: I'm using "Publish Web Site" for a VS 2005 Web Application Project with "Delete all existing files prior to publish" and then XCOPY-Deploy to the target IIS folder (which won't delete existing files there). Today I ran into that error for the first time (no new .ascx/.aspx files since weeks), but simply recompiling and redeploying the same project solved the problem.</p> <p>The only difference: For the 2nd time, I hit the page causing the problem first. Now I'm wondering whether the exact click order really matters or rather whether an arbitrary unlucky click order effectively can crash an ASP.NET site?</p>
11,401
<p>I have uploaded some files to a directory under public and I try to access them using Dir.glob. But I get no results back. </p> <p>The Dir.glob works fine on dev server (mongrel) and also works fine when using script/console on the site installed on site5</p> <p>is there a way to get this working or a different way to get the list of files?</p>
<p>My guess is that executing a shell is prohibited by site5 or that you don't have access to /bin/sh. Globbing is generally implemented by running a shell... Try</p> <pre><code>Dir.entries("public").each do |f| puts(f) end </code></pre>
<p>Turns out that glob is allowed, but on mongrel I need to prefix the path with public whereas on the site hosted by site5 I need to skip it.</p> <p>valid in mongrel:</p> <pre><code>Dir.glob('public/files/images/*.jpg') </code></pre> <p>valid in site5:</p> <pre><code>Dir.glob('files/images/*.jpg') </code></pre> <p>Olliviers answer put me on the right track though.</p>
48,737
<p>I've been using htmldoc for a while, but I've run into some fairly serious limitations. I need the end solution to work on a Linux box. I'll be calling this library/utility/application from a Perl app, so any Perl interfaces would be a bonus.</p>
<p>Sorry to unearth this old post, but it came out first in my search for the best HTML/PDF conversion tool. On Linux <a href="http://wkhtmltopdf.org/" rel="noreferrer">wkhtmltopdf</a> is very good (takes into account CSS, among others) and GPL.</p>
<p>You might want to check out 'Document Conversion Service' by Peernet (at <a href="http://www.peernet.com/conversion-software/batch-document-converter/" rel="nofollow">http://www.peernet.com/conversion-software/batch-document-converter/</a>). This runs as a service on a Windows Desktop or Windows Server machine. It opens HTML documents in a web browser, then prints them through a print driver to create PDF documents, so that the PDF document produced looks exactly as if you had printed the HTML document from the browser.</p>
21,260
<p>Ok, I realize this situation is somewhat unusual, but I need to establish a TCP connection (the 3-way handshake) using only raw sockets (in C, in linux) -- i.e. I need to construct the IP headers and TCP headers myself. I'm writing a server (so I have to first respond to the incoming SYN packet), and for whatever reason I can't seem to get it right. Yes, I realize that a SOCK_STREAM will handle this for me, but for reasons I don't want to go into that isn't an option.</p> <p>The tutorials I've found online on using raw sockets all describe how to build a SYN flooder, but this is somewhat easier than actually establishing a TCP connection, since you don't have to construct a response based on the original packet. I've gotten the SYN flooder examples working, and I can read the incoming SYN packet just fine from the raw socket, but I'm still having trouble creating a valid SYN/ACK response to an incoming SYN from the client.</p> <p>So, does anyone know a good tutorial on using raw sockets that goes beyond creating a SYN flooder, or does anyone have some code that could do this (using SOCK_RAW, and not SOCK_STREAM)? I would be very grateful.</p> <hr> <p>MarkR is absolutely right -- the problem is that the kernel is sending reset packets in response to the initial packet because it thinks the port is closed. The kernel is beating me to the response and the connection dies. I was using tcpdump to monitor the connection already -- I should have been more observant and noticed that there were TWO replies one of which was a reset that was screwing things up, as well as the response my program created. D'OH!</p> <p>The solution that seems to work best is to use an iptables rule, as suggested by MarkR, to block the outbound packets. However, there's an easier way to do it than using the mark option, as suggested. I just match whether the reset TCP flag is set. During the course of a normal connection this is unlikely to be needed, and it doesn't really matter to my application if I block all outbound reset packets from the port being used. This effectively blocks the kernel's unwanted response, but not my own packets. If the port my program is listening on is 9999 then the iptables rule looks like this:</p> <pre><code>iptables -t filter -I OUTPUT -p tcp --sport 9999 --tcp-flags RST RST -j DROP </code></pre>
<p>You want to implement part of a TCP stack in userspace... this is ok, some other apps do this.</p> <p>One problem you will come across is that the kernel will be sending out (generally negative, unhelpful) replies to incoming packets. This is going to screw up any communication you attempt to initiate.</p> <p>One way to avoid this is to use an IP address and interface that the kernel does not have its own IP stack using- which is fine but you will need to deal with link-layer stuff (specifically, arp) yourself. That would require a socket lower than IPPROTO_IP, SOCK_RAW - you need a packet socket (I think).</p> <p>It may also be possible to block the kernel's responses using an iptables rule- but I rather suspect that the rules will apply to your own packets as well somehow, unless you can manage to get them treated differently (perhaps applying a netfilter "mark" to your own packets?)</p> <p>Read the man pages</p> <p>socket(7) ip(7) packet(7)</p> <p>Which explain about various options and ioctls which apply to types of sockets.</p> <p>Of course you'll need a tool like Wireshark to inspect what's going on. You will need several machines to test this, I recommend using vmware (or similar) to reduce the amount of hardware required.</p> <p>Sorry I can't recommend a specific tutorial.</p> <p>Good luck.</p>
<p>There are structures for IP and TCP headers declared in netinet/ip.h &amp; netinet/tcp.h respectively. You may want to look at the other headers in this directory for extra macros &amp; stuff that may be of use. </p> <p>You send a packet with the SYN flag set and a random sequence number (x). You should receive a SYN+ACK from the other side. This packet will have an acknowledgement number (y) that indicates the next sequence number the other side is expecting to receive as well as another sequence number (z). You send back an ACK packet that has sequence number x+1 and ack number z+1 to complete the connection. </p> <p>You also need to make sure you calculate appropriate TCP/IP checksums &amp; fill out the remainder of the header for the packets you send. Also, don't forget about things like host &amp; network byte order.</p> <p>TCP is defined in RFC 793, available here: <a href="http://www.faqs.org/rfcs/rfc793.html" rel="nofollow noreferrer">http://www.faqs.org/rfcs/rfc793.html</a></p>
13,559
<p>I would like to manipulate the HTML inside an iframe using jQuery.</p> <p>I thought I'd be able to do this by setting the context of the jQuery function to be the document of the iframe, something like:</p> <pre><code>$(function(){ //document ready $('some selector', frames['nameOfMyIframe'].document).doStuff() }); </code></pre> <p>However this doesn't seem to work. A bit of inspection shows me that the variables in <code>frames['nameOfMyIframe']</code> are <code>undefined</code> unless I wait a while for the iframe to load. However, when the iframe loads the variables are not accessible (I get <code>permission denied</code>-type errors).</p> <p>Does anyone know of a work-around to this?</p>
<p>I think what you are doing is subject to the <a href="http://en.wikipedia.org/wiki/Same_origin_policy" rel="noreferrer">same origin policy</a>. This should be the reason why you are getting <em>permission denied type</em> errors.</p>
<p>For even more robustness:</p> <pre><code>function getIframeWindow(iframe_object) { var doc; if (iframe_object.contentWindow) { return iframe_object.contentWindow; } if (iframe_object.window) { return iframe_object.window; } if (!doc &amp;&amp; iframe_object.contentDocument) { doc = iframe_object.contentDocument; } if (!doc &amp;&amp; iframe_object.document) { doc = iframe_object.document; } if (doc &amp;&amp; doc.defaultView) { return doc.defaultView; } if (doc &amp;&amp; doc.parentWindow) { return doc.parentWindow; } return undefined; } </code></pre> <p>and </p> <pre><code>... var frame_win = getIframeWindow( frames['nameOfMyIframe'] ); if (frame_win) { $(frame_win.contentDocument || frame_win.document).find('some selector').doStuff(); ... } ... </code></pre>
47,639
<p>Suppose I have following string:</p> <pre><code>String asd = "this is test ass this is test" </code></pre> <p>and I want to split the string using "ass" character sequence.</p> <p>I used:</p> <pre><code>asd.split("ass"); </code></pre> <p>It doesn't work. What do I need to do?</p>
<p>It seems to work fine for me:</p> <pre><code>public class Test { public static void main(String[] args) { String asd = "this is test ass this is test"; String[] bits = asd.split("ass"); for (String bit : bits) { System.out.println("'" + bit + "'"); } } } </code></pre> <p>Result:</p> <pre><code>'this is test ' ' this is test' </code></pre> <p>Is your real delimiter different perhaps? Don't forget that split uses its parameter as a regular expression...</p>
<pre><code>public class Splitter { public static void main(final String[] args) { final String asd = "this is test ass this is test"; final String[] parts = asd.split("ass"); for (final String part : parts) { System.out.println(part); } } } </code></pre> <p>Prints:</p> <pre><code>this is test this is test </code></pre> <p>Under Java 6. What output were you expecting?</p>
25,107
<p>What is the easiest way to check if a computer is alive and responding (say in ping/NetBios)? I'd like a deterministic method that I can time-limit.</p> <p>One solution is simple access the share (File.GetDirectories(@"\compname")) in a separate thread, and kill the thread if it takes too long.</p>
<p>Easy! Use <code>System.Net.NetworkInformation</code> namespace's ping facility!</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx" rel="noreferrer"> <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx</a></a></p>
<p>As long as you want to check a computer within the own subnet you could check it using <a href="http://en.wikipedia.org/wiki/Address_Resolution_Protocol" rel="nofollow">ARP</a>. Here's an example:</p> <pre><code> //for sending an arp request (see pinvoke.net) [DllImport("iphlpapi.dll", ExactSpelling = true)] public static extern int SendARP( int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen); public bool IsComputerAlive(IPAddress host) { //can't check the own machine (assume it's alive) if (host.Equals(IPAddress.Loopback)) return true; //Prepare the magic //this is only needed to pass a valid parameter byte[] macAddr = new byte[6]; uint macAddrLen = (uint)macAddr.Length; //Let's check if it is alive by sending an arp request if (SendARP((int)host.Address, 0, macAddr, ref macAddrLen) == 0) return true; //Igor it's alive! return false;//Not alive } </code></pre> <p>See <a href="http://www.pinvoke.net/default.aspx/iphlpapi.sendarp" rel="nofollow">Pinvoke.net</a> for more information.</p>
45,233
<p>Is it possible to use WSE 2.0 SP2 under VS 2008?</p> <p>I realise that the add-in (that generates the proxy classes/configuration) is not compatible but there are work-arounds to this (copying over the files from a VS 2003 solution). Our web services are relatively static so would not be making too many changes anwyay.</p> <p>We may at a future date move to WCF but taking baby-steps at the moment and want to get our existing services running under all the .NET 3.5 goodness.</p>
<p>You may want to use WSE 2.0 SP3 instead of SP2. Here is why: if you care about (or pay for) Microsoft support services for your application then <a href="http://www.microsoft.com/downloads/details.aspx?familyid=8070E1DE-22E1-4C78-AB9F-07A7FCF1B6AA&amp;displaylang=en" rel="nofollow noreferrer" title="SP3 docs">SP3</a> is supported under the .NET 2.0 framework. I think there were some incompatibilities between SP2 &amp; SP3 but the big thing is Microsoft specifically states that SP3 is supported on the .NET 2.0 framework. See the WSE 2.0 SP2 <a href="http://www.microsoft.com/downloads/details.aspx?familyid=FC5F06C5-821F-41D3-A4FE-6C7B56423841&amp;displaylang=en" rel="nofollow noreferrer" title="SP2 docs">documentation</a> and notice that it doesn't say .NET 2.0 is supported.</p> <p>It looks like you want to convert/rewrite your app in the .NET 3.5 framework. Both .NET 2.0 &amp; .NET 3.5 run under the same CLR 2.0 (yup, it's very confusing: a big thank you goes out to MS marketing!) so you probably are OK running WSE 2.0 SP3 with a.NET 3.5 app. But again, it not a supported configuration.</p>
<p>I have been able to use WSE2 under VS2005/.NET 2.0 with no problems, but I dont know specifically about 2008. I needed Dime attachments (java web service - ugh.. what a headache) which are only in WSE2.</p> <p>To get the functionality in VS, I actually installed WSE3 and then just changed the dll referenced in the application to the WebServices2 file and all of the Imports (VB - using c#) statements. After that, it worked like a charm. </p>
33,308
<p>On 16 September 2020, Autodesk announced changes in the way that Fusion 360 can be used for non-commercial use with their Personal license. As a hobbyist, most of these changes will not affect me very much, since I do not use Fusion 360's advanced features. The most irksome will be only being allowed to have up to ten &quot;documents&quot; active at any one time, the rest having to be archived.</p> <p>However, Autodesk are also restricting the number of file formats that you can export to. For example, the STEP file format will no longer be available with the Personal license. Will this mean that I will not be able to move my models to another CAD package, such as FreeCAD, once the changes come into effect (without first buying a commercial license)?</p> <p><a href="https://knowledge.autodesk.com/support/fusion-360/learn-explore/caas/sfdcarticles/sfdcarticles/Fusion-360-Free-License-Changes.html" rel="nofollow noreferrer">Autodesk: Changes to Fusion 360 for personal use</a></p> <p><strong>Edit: Good news. Autodesk have announced, on 25 September 2020, that the facility to export models to STEP files will be retained for the free-to-use, personal license.</strong></p>
<p>Most of my answer is based off of what Autodesk has said and <a href="https://www.youtube.com/watch?v=SlnEThQ4HR8" rel="nofollow noreferrer">this video</a> from Maker's Muse, which explains this topic in much more detail.</p> <p>In summary, Autodesk is planning on restricting your ability to export any parametric file formats like .STEP or .IGES, leaving no useful CAD-specific files available for users with personal licenses.</p> <p>I would recommend exporting everything you want to keep as .STEP right now just in case you do decide to switch programs later on, because you won't be able to switch after the changes go into effect.</p> <p>I hope that helps.</p> <p>EDIT: As Oscar has pointed out, .STEP exporting is now also part of the general consumer's license, and you can export to other CAD packages at any time. As far as I can tell, other parametric formats, notably .IGES, is still not available for consumers. This shouldn't pose too much of a problem.</p> <p>I'm going to leave my original post intact for now.</p>
<h1>If you use the private license: there was supposed to be a cutoff date.</h1> <p>As long as you use the &quot;private&quot; license, you will get some restrictions. Originally, including the lock off of <code>.step</code> and similar files as well as limiting you to 10 active projects. This means, that you will need to deactivate some to make room for new ones, but unless you have many interlocking parts, 10 can be quite a lot for a hobbyist.</p> <p>They also lock off features that are pretty much only useful for small companies - and if you are in the shoes missing those features, you are on the wrong free license anyway.</p> <p>In late (<a href="https://www.autodesk.com/products/fusion-360/blog/changes-to-fusion-360-for-personal-use/" rel="nofollow noreferrer">25<sup>th</sup></a>.) September 2020, the lock of <code>.step</code> was reversed, but other formats will still no longer be available.</p> <h1>This does not apply to all free licenses</h1> <p>Note that this does not apply to the free education license for teachers and students or the free business license for sub 100,000 \$ companies. You might want to consider swapping to either of these two plans if you qualify.</p> <h1>Last words</h1> <p>I agree with <a href="https://www.youtube.com/watch?v=t4CqWWQXaPE&amp;t=0s" rel="nofollow noreferrer">Thomas Sanladerer:</a> Autodesk is under no obligation to offer a free version at all and even a somewhat restricted, locked into the Autodesk-world version is much better than nothing. I will keep using it, but I am also in the education space and thus not directly affected.</p>
1,745
<p>I have a Queue&lt;T&gt; object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items. Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class?</p>
<p>I've knocked up a basic version of what I'm looking for, it's not perfect but it'll do the job until something better comes along.</p> <pre><code>public class LimitedQueue&lt;T&gt; : Queue&lt;T&gt; { public int Limit { get; set; } public LimitedQueue(int limit) : base(limit) { Limit = limit; } public new void Enqueue(T item) { while (Count &gt;= Limit) { Dequeue(); } base.Enqueue(item); } } </code></pre>
<p>You can use a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1?view=netcore-3.1" rel="nofollow noreferrer"><code>LinkedList&lt;T&gt;</code></a> and add thread safety:</p> <pre><code>public class Buffer&lt;T&gt; : LinkedList&lt;T&gt; { private int capacity; public Buffer(int capacity) { this.capacity = capacity; } public void Enqueue(T item) { // todo: add synchronization mechanism if (Count == capacity) RemoveLast(); AddFirst(item); } public T Dequeue() { // todo: add synchronization mechanism var last = Last.Value; RemoveLast(); return last; } } </code></pre> <p>One thing to note is the default enumeration order will be LIFO in this example. But that can be overridden if necessary.</p>
2,368
<p>I use Visual Studio to do a lot of my coding. I find the open containing folder feature quite helpful. But I don't want the folder to be "opened" by the windows explorer, instead I want to "explore" the folder -- you know, get the nice little frame showing me all the other folders on the left hand side. Does anyone know how to do this?</p> <p>Thank you, Rohit</p>
<p>What I do when I want to export a Quicktime movie is something like the following:</p> <pre><code>NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], QTMovieExport, [exportSettings objectForKey: @"subtype"], QTMovieExportType, [exportSettings objectForKey: @"manufacturer"], QTMovieExportManufacturer, [exportSettings objectForKey: @"settings"], QTMovieExportSettings, nil]; BOOL didSucceed = [movie writeToFile: tmpFileName withAttributes:dictionary error: &amp;error]; </code></pre>
<p>Those attributes are documented as things you can read but not write. However, you might be able to set them when you create the movie, with initWithAttributes:error:.</p>
24,679
<p>Working on a project where a sequential set of methods must be run every <code>x</code> seconds. Right now I have the methods contained within another "parent method", and just sequentially call them right after another.</p> <pre><code>class DoTheseThings() { DoThis(); NowDoThat(); NowDoThis(); MoreWork(); AndImSpent(); } </code></pre> <p>Each method must run successfully without throwing an exception before the next step can be done. So now I wrapped each of those methods with a <code>while</code> and <code>try..catch</code>, then in the <code>catch</code> execute that method again.</p> <pre><code>while( !hadError ) { try { DoThis(); } catch(Exception doThisException ) { hadError = true; } } </code></pre> <p>This seems smelly and not very dry. Is there a better way to do this so I'm not wrapping any new functionality in the same methods. Isn't some kind of Delegate collection the proper way to implement this? </p> <p>Is there a more "proper" solution?</p>
<pre><code>Action[] work=new Action[]{new Action(DoThis), new Action(NowDoThat), new Action(NowDoThis), new Action(MoreWork), new Action(AndImSpent)}; int current =0; while(current!=work.Length) { try { work[current](); current++; } catch(Exception ex) { // log the error or whatever // maybe sleep a while to not kill the processors if a successful execution depends on time elapsed } } </code></pre>
<p>What would be the reason that an error was occuring?</p> <p>If this were a resource issue, such as access to something like a connection or object, then you might want to look at using monitors, semaphores, or just locking. </p> <pre><code>lock (resource) { Dosomething(resource); } </code></pre> <p>This way if a previous method is accessing the resource, then you can wait until it releases the resource to continue. </p> <p>Ideally, you shouldn't have to run a loop to execute something each time it fails. It is failing at all, you would want to know about the issue and fix it. Having a loop to always just keep trying is not the right way to go here.</p>
29,340
<p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
<p>XHTML is easy, use <a href="http://lxml.de/validation.html" rel="noreferrer">lxml</a>.</p> <pre><code>from lxml import etree from StringIO import StringIO etree.parse(StringIO(html), etree.HTMLParser(recover=False)) </code></pre> <p>HTML is harder, since there's traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator, yikes). The easiest solution would be to execute external applications such as <a href="http://www.jclark.com/sp/" rel="noreferrer">nsgmls</a> or <a href="http://openjade.sourceforge.net/" rel="noreferrer">OpenJade</a>, and then parse their output.</p>
<p>I think that <a href="http://tidy.sourceforge.net/" rel="nofollow noreferrer">HTML tidy</a> will do what you want. There is a Python binding for it.</p>
5,606
<p>I need to use sendmail from Macs in an office. At the moment, I can get it to work on the two development Macs (which I think is due to MAMP being installed and working), but getting it to go on the others seems to be a problem...</p> <p>I assume it's down to some config issue, and hope there's someway to fix it (without resorting to installing MAMP on each machine !).</p> <p>I think it may be down to the 'local' nature of the from, but not sure. Here's a dump of /var/log/mail.log if that's any help: </p> <pre><code>Nov 14 14:37:06 claire-g5 postfix/master[5339]: daemon started -- version 2.4.3, configuration /etc/postfix Nov 14 14:37:06 claire-g5 postfix/qmgr[5341]: 2B625250BDB: from=&lt;claire@claire-g5.local&gt;, size=1131, nrcpt=1 (queue active) Nov 14 14:37:06 claire-g5 postfix/qmgr[5341]: D5D19250D5A: from=&lt;claire@claire-g5.local&gt;, size=1191, nrcpt=1 (queue active) Nov 14 14:37:06 claire-g5 postfix/smtp[5344]: 2B625250BDB: host mx01.xxx.uk[212.x.x.134] said: 451 cannot relay now to &lt;xx@xx.com&gt;, please try again later (in reply to RCPT TO command) Nov 14 14:37:06 claire-g5 postfix/smtp[5346]: D5D19250D5A: host mx01.xxx.uk[212.x.x.186] said: 451 cannot relay now to &lt;xx@xx.com&gt;, please try again later (in reply to RCPT TO command) Nov 14 14:37:07 claire-g5 postfix/smtp[5346]: D5D19250D5A: to=&lt;xx@xx.com&gt;, relay=mx01.xxx.uk[212.x.x.134]:25, delay=2350, delays=2349/0.08/0.7/0.12, dsn=4.0.0, status=deferred (host mx01.xxx.uk[212.x.x.134] said: 451 cannot Nov 14 14:37:07 claire-g5 postfix/pickup[5340]: 1A2EC2511D1: uid=501 from=&lt;claire </code></pre>
<p>Note that it's postfix that you have running on your mac, not sendmail.</p> <p>The problem is that the machine mx01.xxx.uk[212.x.x.134] is configured to block mail relaying (accepting an email over SMTP and sending it on to the final mail server). The postfix configuration files are normally stored in /etc/postfix so you could start by looking there. In particular, look at the mynetworks setting in main.cf.</p>
<p>Ah ha! Thanks Denis - this looks like the beasty... </p> <pre><code>### MAMP Postfix Configuration - Start ### myorigin = example.com myhostname = mailer.$myorigin smtpd_sender_restrictions = permit_inet_interfaces # smart host relayhost = auth.example.co.uk smtp_sasl_auth_enable = yes smtp_sasl_password_maps = hash:/etc/postfix/sasl_MAMP_passwd smtp_sasl_security_options = noanonymous ### MAMP Postfix Configuration - End ### # DONT REMOVE: MAMP PRO main.cf template compatibility version: 1 </code></pre> <p>I'll give it a go, and get back to you.</p>
37,010
<p>I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance.</p>
<p>At a command line:</p> <pre><code>SQLCMD -L </code></pre> <p>or </p> <pre><code>OSQL -L </code></pre> <p>(Note: must be a capital L)</p> <p>This will list all the sql servers installed on your network. There are configuration options you can set to prevent a SQL Server from showing in the list. To do this...</p> <p>At command line:</p> <pre><code>svrnetcn </code></pre> <p>In the enabled protocols list, select 'TCP/IP', then click properties. There is a check box for 'Hide server'.</p>
<p>If your within SSMS you might find it easier to use:</p> <pre><code>SELECT @@Version </code></pre>
17,049
<p>I have written a standalone app that controls a device through RS-232 port and some customers want to be able to use the device with LabVIEW. I have seen some threads describing where to start when learning to use LabVIEW, but I was wondering if anyone has experience with writing a plugin/driver (is that the right word?) for LabVIEW and perhaps point me in the right direction.</p> <p>The existing app is GUI that allows people to control the device with higher level concepts - rather than have to know the syntax and protocol of the serial port comms stuff. I want to abstract that away as well so that users can just plug something into LabVIEW and I suppose it exposes some verbs and methods that allow the device to be manipulated and also provide data to clients. </p> <p>I think there is a serial port interface from LabVIEW, but I am sure the people using this device do not want to have to write the code (parsers and etc) to communicate with the device.</p>
<p>If you are prepared to invest a bit of time into learning how to program in LabVIEW, the relevant info on how to develop an instrument driver can be found <a href="http://www.ni.com/devzone/idnet/development.htm" rel="noreferrer">here</a> and <a href="http://zone.ni.com/devzone/cda/tut/p/id/3271" rel="noreferrer">here</a> . </p> <p>Essentially you should provide a set of VI's (the unit of LabVIEW code) that implement the various operations supported by your device. LabVIEW programmers will chain a sequence of these together using the VISA resource (i.e. serial port) and error in/out terminals which your VI's should provide. See the second link for an example.</p> <p>If you don't want to learn how to do this properly - which your second post suggests you don't - then either create a DLL that exposes the necessary functions, or commission a LabVIEW programmer to write the driver for you. If you can supply adequate documentation of your protocol and it's not hideously complicated then it should take them an afternoon. If you have users who are keen on LabVIEW then one of them might be happy to do the job for you for an appropriate discount or incentive - it's really not hard for anyone competent in LabVIEW to do and they are the ones who already have their hands on your device and understand what it does. You might want to beta test the result with your other LabVIEW users first, as you won't be in a position to assess the quality of what they do yourself.</p> <p>If you go the DLL route you'll need to check that the parameters you require are compatible with LabVIEW data types. I'm not a C/C++ programmer so I can't tell you in detail what this means but <a href="http://lavag.org/topic/10902-whitepaper-on-how-to-write-a-labview-compatible-dll/" rel="noreferrer">this</a> might be helpful (Rolf Kalbermatter is the guru on interfacing LabVIEW with external code).</p> <p>If you want to find a LabVIEW programmer then National Instruments can refer you to one through their alliance scheme.</p> <p>(Edited to add link to LAVA forum post on writing DLLs for LabVIEW)</p>
<p>Your customer wants to use your code with LabVIEW. This doesn't mean you have to write LabVIEW code. </p> <p>LabVIEW can interact with DLLs. The trick here is to avoid the more complicated data structures. If you keep to pass by value of basic data types you will have no problem. LabVIEW can work with arrays to and from DLLs as well. Avoid pointers to pointers or pointers to structs. </p> <p>LabVIEW can also interact with .NET assemblies. </p> <p>There is also nothing to stop you from using a client/server model over TCP/IP.</p>
28,129
<p>I'm using reflection to loop through a <code>Type</code>'s properties and set certain types to their default. Now, I could do a switch on the type and set the <code>default(Type)</code> explicitly, but I'd rather do it in one line. Is there a programmatic equivalent of default?</p>
<ul> <li>In case of a value type use <a href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx" rel="noreferrer">Activator.CreateInstance</a> and it should work fine.</li> <li>When using reference type just return null</li> </ul> <pre><code>public static object GetDefault(Type type) { if(type.IsValueType) { return Activator.CreateInstance(type); } return null; } </code></pre> <p>In the newer version of .net such as .net standard, <code>type.IsValueType</code> needs to be written as <code>type.GetTypeInfo().IsValueType</code></p>
<pre><code> /// &lt;summary&gt; /// returns the default value of a specified type /// &lt;/summary&gt; /// &lt;param name="type"&gt;&lt;/param&gt; public static object GetDefault(this Type type) { return type.IsValueType ? (!type.IsGenericType ? Activator.CreateInstance(type) : type.GenericTypeArguments[0].GetDefault() ) : null; } </code></pre>
42,141
<p>i have a Sharepoint feature that essentially extends Lists with a new feature, using a List receiver. For each list the feature is attached to, i need to store some configuration.</p> <p>Now, the first thing that came into my mind is the obvious solution: Have a global list. That works of course, but I wonder if there is some way to store feature-specific configuration in a hidden place? Not that it's sensitive information, but I don't want to clutter the Users Display with too many lists. I believe I can hide lists, but at the same time I wonder if sharepoint allows me to use it's database?</p> <p>I am not talking about just using ADO.net to access the db directly (which is a big no-no with Sharepoint), I am thinking about some officially supported mechanism.</p>
<p>SPLists, unlike som other objects, do not have property bags, however all lists in a SharePoint site has a correlating SPFolder object stored in the RootFolder, and an SPFolder object has a property bag where you can store custom configuration data for the list.</p> <p>Edit: I've written an article that shows <a href="http://furuknap.blogspot.com/2009/01/consuming-rss-or-atom-feed-in.html" rel="nofollow noreferrer">how to use SPFolder</a> to store custom list data if you are interested.</p> <p>.b</p>
<p>You should take a look at <a href="http://www.codeplex.com/SPConfigStore" rel="nofollow noreferrer">Sharepoint Config Store</a>. It's made by <a href="http://www.sharepointnutsandbolts.com/" rel="nofollow noreferrer">Chris O'Brien</a>.</p> <p>With SPConfigStore you can retrieve config items this way </p> <pre><code>string sAdminEmail = ConfigStore.GetValue("MyApplication", "AdminEmail"); </code></pre>
46,558
<p>Is there a website I can create an HTML final four bracket?</p> <p>Or is there just HTML out there that will create it automatically and I can just fill in the specifics?</p>
<p>Stumbled upon this HTML code, this did the trick. I will post it just in case anyone down the road has the same question.</p> <pre><code>table.bracket { border-collapse: collapse; border: none; } .bracket td { vertical-align: middle; width: 40em; margin: 0; padding: 10px; } .bracket td p { border-bottom: solid 1px black; margin: 0; padding: 5px 5px 5px 5px; } .bracket th{ text-align:center; } &lt;table summary="Tournament Bracket" class="bracket"&gt; &lt;tr&gt; &lt;th&gt;National Semi-Finals&lt;br&gt;Saturday November 8th&lt;/th&gt; &lt;th&gt;National Championship&lt;br&gt;Sunday November 9th&lt;/th&gt; &lt;th&gt;NJCAA National Champion&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;p&gt;#1 Manchester CC (17-2-1)&lt;/p&gt;&lt;/td&gt; &lt;td rowspan="2"&gt;&lt;p&gt;&lt;/p&gt;&lt;/td&gt; &lt;td rowspan="4"&gt;&lt;p&gt;&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;p&gt;#4 Triton College (13-4-0)&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;p&gt;#2 Herkimer County CC (18-3-0)&lt;/p&gt;&lt;/td&gt; &lt;td rowspan="2"&gt;&lt;p&gt;&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;p&gt;#3 County College of Morris (17-3-0)&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>edit, fiddled: <a href="http://jsfiddle.net/4KZ6T/" rel="nofollow noreferrer">http://jsfiddle.net/4KZ6T/</a></p>
<p>I don't really know what you need from the question but from the looks of it try out:</p> <p><a href="http://www.bracketmaker.com/" rel="nofollow noreferrer">http://www.bracketmaker.com/</a></p>
32,776
<p>I'm trying to get crawl to work on two separate farms I have but can't get it to work on either one. They both have two WFE's with an additional WFE configured as an Index server. There is one more server dedicated for Query and two clustered SQL 2005 back end servers for the database. I have unsuccessfully tried at least 50 different websites that I found with solutions from a search engine. I have configured (extended) my Web App to use <a href="http://servername:12345" rel="nofollow noreferrer">http://servername:12345</a> as the default zone and <a href="http://abc.companyname.com" rel="nofollow noreferrer">http://abc.companyname.com</a> as the custom and intranet zones. When I enter each of those into the content source and then try to run a crawl, I get a couple of errors in the crawl log:</p> <p><a href="http://servername:12345" rel="nofollow noreferrer">http://servername:12345</a> returns:<br> "Could not connect to the server. Please make sure the site is accessible."</p> <p><a href="http://abc.companyname.com" rel="nofollow noreferrer">http://abc.companyname.com</a> returns:<br> "Deleted by the gatherer. (The start address or content source that contained this item was deleted and hence this item was deleted.)"</p> <p>However, I can click both URL's and the page is accessible.</p> <p>Any ideas?</p> <hr> <p>More info:</p> <p>I wiped the slate clean, so to speak, and ran another crawl to provide an updated sample.</p> <p>My content sources are as such:</p> <p><a href="http://servername:33333" rel="nofollow noreferrer">http://servername:33333</a><br> <a href="http://sharepoint.portal.fake.com" rel="nofollow noreferrer">http://sharepoint.portal.fake.com</a><br> sps3://servername:33333</p> <p>My current crawl log errors are:</p> <p>sps3://servername:33333<br> Error in PortalCrawl Web Service.</p> <p><a href="http://servername:33333/mysites" rel="nofollow noreferrer">http://servername:33333/mysites</a><br> Content for this URL is excluded by the server because a no-index attribute.</p> <p><a href="http://servername:33333/mysites" rel="nofollow noreferrer">http://servername:33333/mysites</a><br> Crawled</p> <p>sts3://servername:33333/contentdbid={62a647a...<br> Crawled</p> <p>sts3://servername:33333<br> Crawled</p> <p><a href="http://servername:33333" rel="nofollow noreferrer">http://servername:33333</a><br> Crawled</p> <p><a href="http://sharepoint.portal.fake.com" rel="nofollow noreferrer">http://sharepoint.portal.fake.com</a><br> The Crawler could not communicate with the server. Check that the server is available and that the firewall access is configured correctly.</p> <p>I double checked for typos above and I don't see any so this should be an accurate reflection.</p>
<p>One thing to remember is that crawling SharePoint sites is different from crawling file shares or non-SharePoint websites.</p> <p>A few other quick pointers:</p> <ul> <li>the sps3: protocol is for crawling user profiles for People Search. You can disregard anything the crawler says about it until you're ready for user profiles.</li> <li>your crawl account is supposed to have access to your entire farm. If you see permissions errors, find the KB article that tells you the how to reset your crawl account (it's a specific stsadm.exe command). If you're trying to crawl another farm's content, then you'll have to work something else out to grant your crawl account access. I think this is your biggest issue presently.</li> <li>The crawler (running from the index server) will attempt to visit the public URL. I've had inter-server communication issues before; make sure all three servers can ping each other, and make sure the index server can reach the public URL (open IE on the index server and check it out). If you have problems, it's time to dirty up your index server's hosts file. This is something SharePoint does for you anyway, so don't feel too bad doing it. If you've set up anything aside from Integrated Windows Authentication, you'll have to work harder to get your crawler working.</li> </ul> <p>Anyway, there's been a lot of back and forth in the responses, so I'm just shotgunning a bunch of suggestions out there, maybe one of them is on target.</p>
<p>In the Services on Server section check the properties for the search crawl account to make sure it is set up, and that it has permissions to access those sites.</p>
12,658
<p>I just recently installed the MVC beta. However, I assumed because the versioning numbers have changed and because it now uses the GAC instead of the bin folder that it wouldn't break existing applications.</p> <p>However, it has.</p> <p>What steps do I need to follow to ensure my existing preview 3 applications use a bin copy of the .dlls and are not broken by the installation of the beta?</p>
<p>ASP.NET MVC beta is also bin-deployable, Move the following DLL's from GAC to the bin folder of your app</p> <pre><code>* System.Web.Mvc * System.Web.Routing * System.Web.Abstractions </code></pre> <p><a href="http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx" rel="nofollow noreferrer">Check this article for more information</a></p>
<p>You'll need to force uninstall (gacutil /u /f System.Web.Mvc) the Beta DLL from the GAC, and then use bin deployment for all versions (including the beta).</p>
33,580
<p>Which databases does Adobe Flash support, if any?</p>
<p>None.</p> <p>Instead, you would need to create some middleware (say, a webservice) that you talked to that did the database CRUD for you.</p>
<p><a href="https://stackoverflow.com/questions/38674/does-adobe-flash-support-databases#38675">@SCdF</a> is correct. From <a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14482&amp;sliceId=2" rel="nofollow noreferrer">the horse's mouth</a>:</p> <blockquote> <p>A Macromedia Flash movie cannot communicate directly with a database. However, Macromedia Flash movies can "talk" to server-side applications (also referred to as "middleware"). Middleware can query a database and relay data back and forth. There are many server applications available. Some of the most common are CGI, ASP, PHP, ColdFusion and Tango.</p> </blockquote>
5,962
<p>As per my understanding stateless session beans are used to code the business logic. They can not store data in their instance variables because their instance is shared by multiple requests. So they seem to be more like Singleton classes. However the difference is contain creates (or reuses from pool) the separate instance of stateless session beans for every request.</p> <p>After googling I could find the reasoning that the Java EE specification says they are suppose to be single threaded. But I can't get the reason why the are specified to be <strong>SINGLE THREADED</strong>?</p>
<p>The SLSBs are single threaded because of the TX Context, Principal is associated with a bean instance when it is called. These beans are pooled and unless the max pool size is reached are processed in separate threads ( Vendor dependent).</p> <p>If SLSBs were designed thread safe every call would have looked like a servlet doGet/Post with request info containing Tx Context , Security Context info and etc. So at least the code looks clean (developer dependent). </p>
<p>The primary reason stateless session beans are single threaded is to make them highly scalable for the container. The container can make a lot of simplifying assumptions about the runtime environment. A second reason is to make life easier for the developer because the developer doesn't have to worry about any synchronization or re-entrancy in his business logic because the bean will never be called in another thread context.</p> <p>I remember the reasoning being discussed in the reviews of the original EJB 1.0 specification. I would look at the goals section of the specification. See <a href="http://java.sun.com/products/ejb/docs.html" rel="nofollow noreferrer">http://java.sun.com/products/ejb/docs.html</a> for the list of specifications.</p>
4,948
<p>Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to <strong><code>drop</code></strong> and then <strong>re-<code>create</code></strong> the constraints?</p>
<p>If you want to disable all constraints in the database just run this code:</p> <pre><code>-- disable all constraints EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all" </code></pre> <p>To switch them back on, run: (the print is optional of course and it is just listing the tables)</p> <pre><code>-- enable all constraints exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all" </code></pre> <p>I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment). </p> <p>If you are deleting all the data you may find <a href="https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql#156813">this solution</a> to be helpful.</p> <p>Also sometimes it is handy to disable all triggers as well, you can see the complete solution <a href="https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger#123966">here</a>.</p>
<p>You can easily turn of CONSTRAINT using : ALTER TABLE TableName NOCHECK CONSTRAINT ALL</p> <p>After you finish the transaction do not forget to turn them on again using: ALTER TABLE TableName CHECK CONSTRAINT ALL</p>
19,241
<p>Is there a query in SQL Server 2005 I can use to get the server's IP or name?</p>
<pre><code>SELECT CONNECTIONPROPERTY('net_transport') AS net_transport, CONNECTIONPROPERTY('protocol_type') AS protocol_type, CONNECTIONPROPERTY('auth_scheme') AS auth_scheme, CONNECTIONPROPERTY('local_net_address') AS local_net_address, CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port, CONNECTIONPROPERTY('client_net_address') AS client_net_address </code></pre> <p>The code here Will give you the IP Address; </p> <p>This will work for a remote client request to SQL 2008 and newer. </p> <p>If you have Shared Memory connections allowed, then running above on the server itself will give you </p> <ul> <li>"Shared Memory" as the value for 'net_transport', and </li> <li>NULL for 'local_net_address', and </li> <li>'<code>&lt;local machine&gt;</code>' will be shown in 'client_net_address'.</li> </ul> <p>'client_net_address' is the address of the computer that the request originated from, whereas 'local_net_address' would be the SQL server (thus NULL over Shared Memory connections), and the address you would give to someone if they can't use the server's NetBios name or FQDN for some reason.</p> <p>I advice strongly against using <a href="https://stackoverflow.com/a/142157/578411">this answer</a>. Enabling the shell out is a very bad idea on a production SQL Server.</p>
<p>It is possible to use the host_name() function</p> <pre><code>select HOST_NAME() </code></pre>
17,184
<p>The .NET <code>System.Security.Cryptography</code> namespace has a rather bewildering collection of algorithms that I could use for encryption of credit card details. Which is the best?</p> <p>It clearly needs to be secure for a relatively short string. </p> <p>EDIT: I'm in the UK, where I understand we're OK storing encrypted credit card details so long as the three-digit CVV number is never stored. And thanks all for the great responses.</p>
<p>No offense, but the question is a little "misguided". There is no "silver bullet" solution. I would recommend to read up on cryptography in general and then do some threat modeling. Some questions (by no means a comprehensive list) you should ask yourself:</p> <ul> <li>Is the module doing the encryption the one which needs to decrypt it (in this case use symmetric crypto) or will it send data to an other module (on an other machine) which will use it (in which case you should consider public-key crypto)</li> <li>What do you want to protect against? Someone accessing the database but not having the sourcecode (in which case you can hardcode the encryption key directly into the source)? Someone sniffing your local network (you should consider transparent solutions like IPSec)? Someone stealing your server (it can happen even in data centers - in which case full disk encryption should be considered)?</li> <li>Do you really need to keep the data? Can't you directly pass it to the credit card processor and erase it after you get the confirmation? Can't you store it locally at the client in a cookie or Flash LSO? If you store it at the client, make sure that you encrypt it at the server side before putting it in a cookie. Also, if you are using cookies, make sure that you make them http only.</li> <li>Is it enough to compare the equality of the data (ie the data that the client has given me is the same data that I have)? If so, consider storing a hash of it. Because credit card numbers are relatively short and use a reduced set of symbols, a unique salt should be generated for each before hashing.</li> </ul> <p><em>Later edit</em>: note that standard encryption algorithms from the same category (for example 3DES and AES - both being symmetric block cyphers) are of comparable strength. Most (commercial) systems are not broken because somebody bruteforced their encryption, but because their threat modelling was not detailed enough (or flat out they didn't have any). For example you can encrypt all the data, but if you happen to have a public facing web interface which is vulnerable to SQL injection, it won't help you much.</p>
<p>3des is pretty good, store the salt along side, and keep a standard key somewhere not in the database or a config file. That way if you get pwned, they can't decrypt it.</p>
6,252
<p>Suppose I have a stringbuilder in C# that does this:</p> <pre><code>StringBuilder sb = new StringBuilder(); string cat = "cat"; sb.Append("the ").Append(cat).(" in the hat"); string s = sb.ToString(); </code></pre> <p>would that be as efficient or any more efficient as having:</p> <pre><code>string cat = "cat"; string s = String.Format("The {0} in the hat", cat); </code></pre> <p>If so, why?</p> <p><strong>EDIT</strong> </p> <p>After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at <strong><em>injecting</em></strong> one string into another.</p> <p>In both cases above I want to inject one or more strings into the middle of a predefined template string.</p> <p>Sorry for the confusion</p>
<p><strong>NOTE:</strong> This answer was written when .NET 2.0 was the current version. This may no longer apply to later versions.</p> <p><code>String.Format</code> uses a <code>StringBuilder</code> internally:</p> <pre><code>public static string Format(IFormatProvider provider, string format, params object[] args) { if ((format == null) || (args == null)) { throw new ArgumentNullException((format == null) ? "format" : "args"); } StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8)); builder.AppendFormat(provider, format, args); return builder.ToString(); } </code></pre> <p>The above code is a snippet from mscorlib, so the question becomes "is <code>StringBuilder.Append()</code> faster than <code>StringBuilder.AppendFormat()</code>"? </p> <p>Without benchmarking I'd probably say that the code sample above would run more quickly using <code>.Append()</code>. But it's a guess, try benchmarking and/or profiling the two to get a proper comparison.</p> <p>This chap, Jerry Dixon, did some benchmarking:</p> <blockquote> <p><a href="http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm" rel="noreferrer">http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm</a></p> </blockquote> <p><strong>Updated:</strong></p> <p>Sadly the link above has since died. However there's still a copy on the Way Back Machine:</p> <blockquote> <p><a href="http://web.archive.org/web/20090417100252/http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm" rel="noreferrer">http://web.archive.org/web/20090417100252/http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm</a></p> </blockquote> <p>At the end of the day it depends whether your string formatting is going to be called repetitively, i.e. you're doing some serious text processing over 100's of megabytes of text, or whether it's being called when a user clicks a button now and again. Unless you're doing some huge batch processing job I'd stick with String.Format, it aids code readability. If you suspect a perf bottleneck then stick a profiler on your code and see where it really is.</p>
<p>I would suggest not, since String.Format was not designed for concatenation, it was design for formatting the output of various inputs such as a date.</p> <pre><code>String s = String.Format("Today is {0:dd-MMM-yyyy}.", DateTime.Today); </code></pre>
2,849
<p>Here's the quick and skinny of my issue:</p> <pre>$("a").toggle(function() { /*function A*/ }, function() { /*function B*/ });</pre> <p>Inside <code>function A</code> a form is displayed. If the user successfully completes the form, the form is hidden again (returning to it's original state).</p> <p>Inside <code>function B</code> the same form is hidden.</p> <p>The theory behind this is that the user can choose to display the form and fill it out, or they can click again and have the form go back into hiding. </p> <p>Now my question is this: currently, if the user fills out the form successfully--and it goes into hiding--the user would have to click on the link <strong><em>twice</em></strong> before returning to the toggle state that displays the form.</p> <p>Is there anyway to programmatically reset the toggle switch to its initial state?</p>
<p>jQuery has two <code>.toggle()</code> methods:</p> <p><a href="http://api.jquery.com/toggle/" rel="nofollow noreferrer"><code>.toggle()</code></a></p> <blockquote> <p>Toggles each of the set of matched elements. If they are shown, toggle makes them hidden. If they are hidden, toggle makes them shown.</p> </blockquote> <p><a href="https://api.jquery.com/toggle-event/" rel="nofollow noreferrer"><code>.toggle(even, odd)</code></a></p> <blockquote> <p>Toggle between two function calls every other click.</p> </blockquote> <p>In this case you want the first one. Something like this should do the trick:</p> <pre><code>$("a").click(function() { $("#theForm").toggle(); }); </code></pre>
<pre><code>$("#div_clicked").click(function() { if ($("#toggle_div").is(":visible")) { // do this } else { // do that } </code></pre> <p>Replace hidden with visible</p>
30,304
<p>I am attempting to import mxml files that I developed with Emacs into a new project in FlexBuilder...I have created a project and manually added all my MXML and actionscript files into FlexBuilder. </p> <p>I now can't figure out how to run the application. I believe the problem lies in the fact that FlexBuilder believes that all my mxml files are components, when in fact, they are applications...Is there a way to change this?</p> <p>When I right click on the file the "set as default application" and "run application" is disabled...</p> <p>Thanks.</p>
<p>I usually seem to have to go into the Project Properties, click 'Flex Applications' and add the MXMLs into that panel before I can run stuff.</p>
<p>Make sure the MXML files are in the main source folder. You can't have a runnable application in a secondary source directory or subdirectory of the main source dir.</p>
27,084
<p>Can this be done w/ linqtosql?</p> <pre><code>SELECT City, SUM(DATEDIFF(minute,StartDate,Completed)) AS Downtime FROM Incidents GROUP BY City </code></pre>
<p>It is in part to support scenarios (WebForms, WinForms, LINQ-to-SQL, etc) mixing generated code with programmer code.</p> <p>There are more reasons to use it. For example, if you have big classes in large, unwieldy files, but the classes have groups of logically related methods, partial classes may be an option to make your file sizes more manageable.</p>
<p>Correction, as Matt pointed out, both sides of the partial need to be in the same assembly. my bad.</p>
19,407
<p>I recently deploy one web application in one of my development servers. I'm using oracle, asp.net and c#. When I run the application in the server everything works fine, but when I try to run the application outside of the server (using my pc, for example) i get this error:</p> <pre><code>ORA-12154: TNS:could not resolve the connect identifier specified </code></pre> <p>If i run the application in my pc with visual studio it works fine.</p> <p>Oracle is installed in Server "A" and the application is in server "B". Server "A" is in one domain and server "B" is in other domain.My pc is in the same domain has Server "A".</p> <p>In my pc I can find the file tnsname.ora in C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN, but in Server "B" i can´t find it anywhere</p> <p>any idea? Thanks for the help.</p>
<p>Have you tried this yet? (from <a href="http://ora-12154.ora-code.com/" rel="nofollow noreferrer">http://ora-12154.ora-code.com/</a>)</p> <p>ORA-12154: TNS:could not resolve the connect identifier specified<br> Cause: A connection to a database or other service was requested using a connect identifier, and the connect identifier specified could not be resolved into a connect descriptor using one of the naming methods configured. For example, if the type of connect identifier used was a net service name then the net service name could not be found in a naming method repository, or the repository could not be located or reached.<br> Action: - If you are using local naming (TNSNAMES.ORA file):</p> <ul> <li><p>Make sure that "TNSNAMES" is listed as one of the values of the NAMES.DIRECTORY_PATH parameter in the Oracle Net profile (SQLNET.ORA)</p></li> <li><p>Verify that a TNSNAMES.ORA file exists and is in the proper directory and is accessible.</p></li> <li><p>Check that the net service name used as the connect identifier exists in the TNSNAMES.ORA file.</p></li> <li><p>Make sure there are no syntax errors anywhere in the TNSNAMES.ORA file. Look for unmatched parentheses or stray characters. Errors in a TNSNAMES.ORA file may make it unusable.</p></li> <li><p>If you are using directory naming:</p></li> <li><p>Verify that "LDAP" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).</p></li> <li><p>Verify that the LDAP directory server is up and that it is accessible.</p></li> <li><p>Verify that the net service name or database name used as the connect identifier is configured in the directory.</p></li> <li><p>Verify that the default context being used is correct by specifying a fully qualified net service name or a full LDAP DN as the connect identifier</p></li> <li><p>If you are using easy connect naming:</p></li> <li><p>Verify that "EZCONNECT" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).</p></li> <li><p>Make sure the host, port and service name specified are correct.</p></li> <li><p>Try enclosing the connect identifier in quote marks. See the Oracle Net Services Administrators Guide or the Oracle operating system specific guide for more information on naming.</p></li> </ul>
<p>Is ORACLE_HOME set on server B?</p>
19,682
<p>I have a class that contains two methods like these:</p> <pre><code>public String getFoo(Int32 a) { return getBar(a, "b", null); } public String getBar(Int32 a, String b, Int32 c) { //do something return ""; } </code></pre> <p>However when I compile my class I get two errors:</p> <ol> <li>The best overloaded method match for getBar(int,string,int) has some invalid arguments</li> <li>Argument '3': cannot convert from '<code>&lt;null&gt;</code>' to 'int'</li> </ol> <p>I think I understand why I'm getting this error: the compiler doesn't know at the time of compilation what the real type of the object is. Can someone confirm if I'm correct about the cause of the error or point out the real reason?</p> <p>More importantly, can I design my code this way? If so, what do I need to do to fix the errors? My reason for designing my class this way is because I don't want to duplicate the code in getBar, in getFoo. The two methods do essentially the same thing except one takes a third parameter.</p> <p>Thanks.</p>
<p>In .NET, there is a distinct concept between reference types and value types.</p> <p>A reference type is an object that is allocated on the heap (It will be a subclass of System.Object). All that is on the stack is a pointer to this object. Because of that, it is perfectly valid to store a null pointer.</p> <p>A value type is an object that is allocated on the stack, it will be a subclass of System.ValueType. Because a value type lives on the stack, when you pass its value to a function, you pass the entire contents of the object. </p> <p>Value types cannot be null.</p> <p>Most C# primitive types are value types. String is a special type of primitive that is actually a reference type.</p> <p>In .NET 2.0, MS added the ability to enclose a generic type inside of a struct so that it could simulate a nullable type. What really happens is that the logic inside of the Nullable&lt;T&gt; struct is emulating a null for you.</p> <p>They expressed it using a syntax shortcut by adding a question mark to the type, for example:</p> <pre><code>int? nullableInt = null; float? nullableFloat = null; </code></pre> <p>etc...</p> <p>If you don't like the int? syntax, you can always use Nullable&lt;SomeType&gt;</p> <pre><code>public String getBar(Int32 a, String b, Nullable&lt;Int32&gt; c) </code></pre> <p>As a side note, I prefer to add an overload when doing what you are doing, just to make the syntax nicer.</p> <pre><code>public String getBar(Int32 a, String b) { this.getBar(a,b,null); } public String getBar(Int32 a, String b, Nullable&lt;Int32&gt; c) { } </code></pre>
<p>Int32 cannot be null. Make it a nullable type instead:</p> <pre><code>public String getBar(Int32 a, String b, Int32? c) { if (c.HasValue) { ...do something with c.Value... } return ""; } </code></pre>
33,970
<p>Maybe this is an easy question, maybe not. I have a select box where I hardcode with width. Say 120px.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;select style="width: 120px"&gt; &lt;option&gt;REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT&lt;/option&gt; &lt;option&gt;ABC&lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p> <p>I want to be able to show the second option so that the user can see the full length of the text.</p> <p>Like everything else. This works fine in Firefox, but doesn't work with Internet Explorer6.</p>
<p>If you have the option pre-existing in a fixed-with <code>&lt;select&gt;</code>, and you don't want to change the width programmatically, you could be out of luck unless you get a little creative.</p> <ul> <li>You could try and set the <code>title</code> attribute to each option. This is non-standard HTML (if you care for this minor infraction here), but IE (and Firefox as well) will display the entire text in a mouse popup on mouse hover.</li> <li>You could use JavaScript to show the text in some positioned DIV when the user selects something. IMHO this is the <em>not-so-nice</em> way to do it, because it requires JavaScript on to work at all, and it works only <em>after</em> something has been selected - before there is a change in value no events fire for the select box.</li> <li>You don't use a select box at all, but <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2359319&amp;SiteID=1" rel="nofollow noreferrer">implement its functionality using other markup and CSS</a>. Not my favorite but I wanted to mention it.</li> </ul> <p>If you are adding a long option later through JavaScript, look here: <a href="https://stackoverflow.com/questions/261362/how-to-update-html-select-box-dynamically-in-ie">How to update HTML “select” box dynamically in IE</a></p>
<p>I improved the cychan's solution, to be like that:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style&gt; .wrapper{ display: inline; float: left; width: 180px; overflow: hidden; } .selectArrow{ display: inline; float: left; width: 17px; height: 20px; border:1px solid #7f9db9; border-left: none; background: url('selectArrow.png') no-repeat 1px 1px; } .selectArrow-mousedown{background: url('selectArrow-mousedown.png') no-repeat 1px 1px;} .selectArrow-mouseover{background: url('selectArrow-mouseover.png') no-repeat 1px 1px;} &lt;/style&gt; &lt;script language="javascript" src="jquery-1.3.2.min.js"&gt;&lt;/script&gt; &lt;script language="javascript"&gt; $(document).ready(function(){ $('#w1').wrap("&lt;div class='wrapper'&gt;&lt;/div&gt;"); $('.wrapper').after("&lt;div class='selectArrow'/&gt;"); $('.wrapper').find('select').mousedown(function(){ $(this).parent().next().addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover'); }). mouseup(function(){ $(this).parent().next().removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover'); }). hover(function(){ $(this).parent().next().addClass('selectArrow-mouseover'); }, function(){ $(this).parent().next().removeClass('selectArrow-mouseover'); }); $('.selectArrow').click(function(){ $(this).prev().find('select').focus(); }); $('.selectArrow').mousedown(function(){ $(this).addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover'); }). mouseup(function(){ $(this).removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover'); }). hover(function(){ $(this).addClass('selectArrow-mouseover'); }, function(){ $(this).removeClass('selectArrow-mouseover'); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;select id="w1"&gt; &lt;option value="0"&gt;AnyAnyAnyAnyAnyAnyAny&lt;/option&gt; &lt;option value="1"&gt;AnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAny&lt;/option&gt; &lt;/select&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><a href="http://img189.imageshack.us/gal.php?g=selectarrow.png" rel="nofollow noreferrer">The PNGs used in css classes are uploaded here...</a></p> <p>And you still need JQuery.....</p>
37,538